babylon.no-module.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. /**
  1397. * Constant used to convert a value to gamma space
  1398. * @ignorenaming
  1399. */
  1400. BABYLON.ToGammaSpace = 1 / 2.2;
  1401. /**
  1402. * Constant used to convert a value to linear space
  1403. * @ignorenaming
  1404. */
  1405. BABYLON.ToLinearSpace = 2.2;
  1406. /**
  1407. * Constant used to define the minimal number value in Babylon.js
  1408. * @ignorenaming
  1409. */
  1410. BABYLON.Epsilon = 0.001;
  1411. /**
  1412. * Class used to hold a RBG color
  1413. */
  1414. var Color3 = /** @class */ (function () {
  1415. /**
  1416. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1417. * @param r defines the red component (between 0 and 1, default is 0)
  1418. * @param g defines the green component (between 0 and 1, default is 0)
  1419. * @param b defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. function Color3(
  1422. /**
  1423. * Defines the red component (between 0 and 1, default is 0)
  1424. */
  1425. r,
  1426. /**
  1427. * Defines the green component (between 0 and 1, default is 0)
  1428. */
  1429. g,
  1430. /**
  1431. * Defines the blue component (between 0 and 1, default is 0)
  1432. */
  1433. b) {
  1434. if (r === void 0) { r = 0; }
  1435. if (g === void 0) { g = 0; }
  1436. if (b === void 0) { b = 0; }
  1437. this.r = r;
  1438. this.g = g;
  1439. this.b = b;
  1440. }
  1441. /**
  1442. * Creates a string with the Color3 current values
  1443. * @returns the string representation of the Color3 object
  1444. */
  1445. Color3.prototype.toString = function () {
  1446. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1447. };
  1448. /**
  1449. * Returns the string "Color3"
  1450. * @returns "Color3"
  1451. */
  1452. Color3.prototype.getClassName = function () {
  1453. return "Color3";
  1454. };
  1455. /**
  1456. * Compute the Color3 hash code
  1457. * @returns an unique number that can be used to hash Color3 objects
  1458. */
  1459. Color3.prototype.getHashCode = function () {
  1460. var hash = this.r || 0;
  1461. hash = (hash * 397) ^ (this.g || 0);
  1462. hash = (hash * 397) ^ (this.b || 0);
  1463. return hash;
  1464. };
  1465. // Operators
  1466. /**
  1467. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1468. * @param array defines the array where to store the r,g,b components
  1469. * @param index defines an optional index in the target array to define where to start storing values
  1470. * @returns the current Color3 object
  1471. */
  1472. Color3.prototype.toArray = function (array, index) {
  1473. if (index === undefined) {
  1474. index = 0;
  1475. }
  1476. array[index] = this.r;
  1477. array[index + 1] = this.g;
  1478. array[index + 2] = this.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1483. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1484. * @returns a new {BABYLON.Color4} object
  1485. */
  1486. Color3.prototype.toColor4 = function (alpha) {
  1487. if (alpha === void 0) { alpha = 1; }
  1488. return new Color4(this.r, this.g, this.b, alpha);
  1489. };
  1490. /**
  1491. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1492. * @returns the new array
  1493. */
  1494. Color3.prototype.asArray = function () {
  1495. var result = new Array();
  1496. this.toArray(result, 0);
  1497. return result;
  1498. };
  1499. /**
  1500. * Returns the luminance value
  1501. * @returns a float value
  1502. */
  1503. Color3.prototype.toLuminance = function () {
  1504. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1505. };
  1506. /**
  1507. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1508. * @param otherColor defines the second operand
  1509. * @returns the new Color3 object
  1510. */
  1511. Color3.prototype.multiply = function (otherColor) {
  1512. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1513. };
  1514. /**
  1515. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1516. * @param otherColor defines the second operand
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the current Color3
  1519. */
  1520. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1521. result.r = this.r * otherColor.r;
  1522. result.g = this.g * otherColor.g;
  1523. result.b = this.b * otherColor.b;
  1524. return this;
  1525. };
  1526. /**
  1527. * Determines equality between Color3 objects
  1528. * @param otherColor defines the second operand
  1529. * @returns true if the rgb values are equal to the given ones
  1530. */
  1531. Color3.prototype.equals = function (otherColor) {
  1532. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1533. };
  1534. /**
  1535. * Determines equality between the current Color3 object and a set of r,b,g values
  1536. * @param r defines the red component to check
  1537. * @param g defines the green component to check
  1538. * @param b defines the blue component to check
  1539. * @returns true if the rgb values are equal to the given ones
  1540. */
  1541. Color3.prototype.equalsFloats = function (r, g, b) {
  1542. return this.r === r && this.g === g && this.b === b;
  1543. };
  1544. /**
  1545. * Multiplies in place each rgb value by scale
  1546. * @param scale defines the scaling factor
  1547. * @returns the updated Color3
  1548. */
  1549. Color3.prototype.scale = function (scale) {
  1550. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1551. };
  1552. /**
  1553. * Multiplies the rgb values by scale and stores the result into "result"
  1554. * @param scale defines the scaling factor
  1555. * @param result defines the Color3 object where to store the result
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleToRef = function (scale, result) {
  1559. result.r = this.r * scale;
  1560. result.g = this.g * scale;
  1561. result.b = this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Scale the current Color3 values by a factor and add the result to a given Color3
  1566. * @param scale defines the scale factor
  1567. * @param result defines color to store the result into
  1568. * @returns the unmodified current Color3
  1569. */
  1570. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1571. result.r += this.r * scale;
  1572. result.g += this.g * scale;
  1573. result.b += this.b * scale;
  1574. return this;
  1575. };
  1576. /**
  1577. * Clamps the rgb values by the min and max values and stores the result into "result"
  1578. * @param min defines minimum clamping value (default is 0)
  1579. * @param max defines maximum clamping value (default is 1)
  1580. * @param result defines color to store the result into
  1581. * @returns the original Color3
  1582. */
  1583. Color3.prototype.clampToRef = function (min, max, result) {
  1584. if (min === void 0) { min = 0; }
  1585. if (max === void 0) { max = 1; }
  1586. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1587. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1588. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1589. return this;
  1590. };
  1591. /**
  1592. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1593. * @param otherColor defines the second operand
  1594. * @returns the new Color3
  1595. */
  1596. Color3.prototype.add = function (otherColor) {
  1597. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1598. };
  1599. /**
  1600. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1601. * @param otherColor defines the second operand
  1602. * @param result defines Color3 object to store the result into
  1603. * @returns the unmodified current Color3
  1604. */
  1605. Color3.prototype.addToRef = function (otherColor, result) {
  1606. result.r = this.r + otherColor.r;
  1607. result.g = this.g + otherColor.g;
  1608. result.b = this.b + otherColor.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1613. * @param otherColor defines the second operand
  1614. * @returns the new Color3
  1615. */
  1616. Color3.prototype.subtract = function (otherColor) {
  1617. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1618. };
  1619. /**
  1620. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1621. * @param otherColor defines the second operand
  1622. * @param result defines Color3 object to store the result into
  1623. * @returns the unmodified current Color3
  1624. */
  1625. Color3.prototype.subtractToRef = function (otherColor, result) {
  1626. result.r = this.r - otherColor.r;
  1627. result.g = this.g - otherColor.g;
  1628. result.b = this.b - otherColor.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Copy the current object
  1633. * @returns a new Color3 copied the current one
  1634. */
  1635. Color3.prototype.clone = function () {
  1636. return new Color3(this.r, this.g, this.b);
  1637. };
  1638. /**
  1639. * Copies the rgb values from the source in the current Color3
  1640. * @param source defines the source Color3 object
  1641. * @returns the updated Color3 object
  1642. */
  1643. Color3.prototype.copyFrom = function (source) {
  1644. this.r = source.r;
  1645. this.g = source.g;
  1646. this.b = source.b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Updates the Color3 rgb values from the given floats
  1651. * @param r defines the red component to read from
  1652. * @param g defines the green component to read from
  1653. * @param b defines the blue component to read from
  1654. * @returns the current Color3 object
  1655. */
  1656. Color3.prototype.copyFromFloats = function (r, g, b) {
  1657. this.r = r;
  1658. this.g = g;
  1659. this.b = b;
  1660. return this;
  1661. };
  1662. /**
  1663. * Updates the Color3 rgb values from the given floats
  1664. * @param r defines the red component to read from
  1665. * @param g defines the green component to read from
  1666. * @param b defines the blue component to read from
  1667. * @returns the current Color3 object
  1668. */
  1669. Color3.prototype.set = function (r, g, b) {
  1670. return this.copyFromFloats(r, g, b);
  1671. };
  1672. /**
  1673. * Compute the Color3 hexadecimal code as a string
  1674. * @returns a string containing the hexadecimal representation of the Color3 object
  1675. */
  1676. Color3.prototype.toHexString = function () {
  1677. var intR = (this.r * 255) | 0;
  1678. var intG = (this.g * 255) | 0;
  1679. var intB = (this.b * 255) | 0;
  1680. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1681. };
  1682. /**
  1683. * Computes a new Color3 converted from the current one to linear space
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.prototype.toLinearSpace = function () {
  1687. var convertedColor = new Color3();
  1688. this.toLinearSpaceToRef(convertedColor);
  1689. return convertedColor;
  1690. };
  1691. /**
  1692. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1693. * @param convertedColor defines the Color3 object where to store the linear space version
  1694. * @returns the unmodified Color3
  1695. */
  1696. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1697. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1698. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1699. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1700. return this;
  1701. };
  1702. /**
  1703. * Computes a new Color3 converted from the current one to gamma space
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.prototype.toGammaSpace = function () {
  1707. var convertedColor = new Color3();
  1708. this.toGammaSpaceToRef(convertedColor);
  1709. return convertedColor;
  1710. };
  1711. /**
  1712. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1713. * @param convertedColor defines the Color3 object where to store the gamma space version
  1714. * @returns the unmodified Color3
  1715. */
  1716. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1717. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1718. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1719. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1720. return this;
  1721. };
  1722. // Statics
  1723. /**
  1724. * Creates a new Color3 from the string containing valid hexadecimal values
  1725. * @param hex defines a string containing valid hexadecimal values
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromHexString = function (hex) {
  1729. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1730. return new Color3(0, 0, 0);
  1731. }
  1732. var r = parseInt(hex.substring(1, 3), 16);
  1733. var g = parseInt(hex.substring(3, 5), 16);
  1734. var b = parseInt(hex.substring(5, 7), 16);
  1735. return Color3.FromInts(r, g, b);
  1736. };
  1737. /**
  1738. * Creates a new Vector3 from the starting index of the given array
  1739. * @param array defines the source array
  1740. * @param offset defines an offset in the source array
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromArray = function (array, offset) {
  1744. if (offset === void 0) { offset = 0; }
  1745. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1746. };
  1747. /**
  1748. * Creates a new Color3 from integer values (< 256)
  1749. * @param r defines the red component to read from (value between 0 and 255)
  1750. * @param g defines the green component to read from (value between 0 and 255)
  1751. * @param b defines the blue component to read from (value between 0 and 255)
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.FromInts = function (r, g, b) {
  1755. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param start defines the start Color3 value
  1760. * @param end defines the end Color3 value
  1761. * @param amount defines the gradient value between start and end
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Lerp = function (start, end, amount) {
  1765. var result = new Color3(0.0, 0.0, 0.0);
  1766. Color3.LerpToRef(start, end, amount, result);
  1767. return result;
  1768. };
  1769. /**
  1770. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1771. * @param left defines the start value
  1772. * @param right defines the end value
  1773. * @param amount defines the gradient factor
  1774. * @param result defines the Color3 object where to store the result
  1775. */
  1776. Color3.LerpToRef = function (left, right, amount, result) {
  1777. result.r = left.r + ((right.r - left.r) * amount);
  1778. result.g = left.g + ((right.g - left.g) * amount);
  1779. result.b = left.b + ((right.b - left.b) * amount);
  1780. };
  1781. /**
  1782. * Returns a Color3 value containing a red color
  1783. * @returns a new Color3 object
  1784. */
  1785. Color3.Red = function () { return new Color3(1, 0, 0); };
  1786. /**
  1787. * Returns a Color3 value containing a green color
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.Green = function () { return new Color3(0, 1, 0); };
  1791. /**
  1792. * Returns a Color3 value containing a blue color
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1796. /**
  1797. * Returns a Color3 value containing a black color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Black = function () { return new Color3(0, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a white color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.White = function () { return new Color3(1, 1, 1); };
  1806. /**
  1807. * Returns a Color3 value containing a purple color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1811. /**
  1812. * Returns a Color3 value containing a magenta color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1816. /**
  1817. * Returns a Color3 value containing a yellow color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1821. /**
  1822. * Returns a Color3 value containing a gray color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a teal color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1831. /**
  1832. * Returns a Color3 value containing a random color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1836. return Color3;
  1837. }());
  1838. BABYLON.Color3 = Color3;
  1839. /**
  1840. * Class used to hold a RBGA color
  1841. */
  1842. var Color4 = /** @class */ (function () {
  1843. /**
  1844. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1845. * @param r defines the red component (between 0 and 1, default is 0)
  1846. * @param g defines the green component (between 0 and 1, default is 0)
  1847. * @param b defines the blue component (between 0 and 1, default is 0)
  1848. * @param a defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. function Color4(
  1851. /**
  1852. * Defines the red component (between 0 and 1, default is 0)
  1853. */
  1854. r,
  1855. /**
  1856. * Defines the green component (between 0 and 1, default is 0)
  1857. */
  1858. g,
  1859. /**
  1860. * Defines the blue component (between 0 and 1, default is 0)
  1861. */
  1862. b,
  1863. /**
  1864. * Defines the alpha component (between 0 and 1, default is 1)
  1865. */
  1866. a) {
  1867. if (r === void 0) { r = 0; }
  1868. if (g === void 0) { g = 0; }
  1869. if (b === void 0) { b = 0; }
  1870. if (a === void 0) { a = 1; }
  1871. this.r = r;
  1872. this.g = g;
  1873. this.b = b;
  1874. this.a = a;
  1875. }
  1876. // Operators
  1877. /**
  1878. * Adds in place the given Color4 values to the current Color4 object
  1879. * @param right defines the second operand
  1880. * @returns the current updated Color4 object
  1881. */
  1882. Color4.prototype.addInPlace = function (right) {
  1883. this.r += right.r;
  1884. this.g += right.g;
  1885. this.b += right.b;
  1886. this.a += right.a;
  1887. return this;
  1888. };
  1889. /**
  1890. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1891. * @returns the new array
  1892. */
  1893. Color4.prototype.asArray = function () {
  1894. var result = new Array();
  1895. this.toArray(result, 0);
  1896. return result;
  1897. };
  1898. /**
  1899. * Stores from the starting index in the given array the Color4 successive values
  1900. * @param array defines the array where to store the r,g,b components
  1901. * @param index defines an optional index in the target array to define where to start storing values
  1902. * @returns the current Color4 object
  1903. */
  1904. Color4.prototype.toArray = function (array, index) {
  1905. if (index === undefined) {
  1906. index = 0;
  1907. }
  1908. array[index] = this.r;
  1909. array[index + 1] = this.g;
  1910. array[index + 2] = this.b;
  1911. array[index + 3] = this.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1916. * @param right defines the second operand
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.add = function (right) {
  1920. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1921. };
  1922. /**
  1923. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1924. * @param right defines the second operand
  1925. * @returns a new Color4 object
  1926. */
  1927. Color4.prototype.subtract = function (right) {
  1928. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1929. };
  1930. /**
  1931. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1932. * @param right defines the second operand
  1933. * @param result defines the Color4 object where to store the result
  1934. * @returns the current Color4 object
  1935. */
  1936. Color4.prototype.subtractToRef = function (right, result) {
  1937. result.r = this.r - right.r;
  1938. result.g = this.g - right.g;
  1939. result.b = this.b - right.b;
  1940. result.a = this.a - right.a;
  1941. return this;
  1942. };
  1943. /**
  1944. * Creates a new Color4 with the current Color4 values multiplied by scale
  1945. * @param scale defines the scaling factor to apply
  1946. * @returns a new Color4 object
  1947. */
  1948. Color4.prototype.scale = function (scale) {
  1949. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1950. };
  1951. /**
  1952. * Multiplies the current Color4 values by scale and stores the result in "result"
  1953. * @param scale defines the scaling factor to apply
  1954. * @param result defines the Color4 object where to store the result
  1955. * @returns the current unmodified Color4
  1956. */
  1957. Color4.prototype.scaleToRef = function (scale, result) {
  1958. result.r = this.r * scale;
  1959. result.g = this.g * scale;
  1960. result.b = this.b * scale;
  1961. result.a = this.a * scale;
  1962. return this;
  1963. };
  1964. /**
  1965. * Scale the current Color4 values by a factor and add the result to a given Color4
  1966. * @param scale defines the scale factor
  1967. * @param result defines the Color4 object where to store the result
  1968. * @returns the unmodified current Color4
  1969. */
  1970. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1971. result.r += this.r * scale;
  1972. result.g += this.g * scale;
  1973. result.b += this.b * scale;
  1974. result.a += this.a * scale;
  1975. return this;
  1976. };
  1977. /**
  1978. * Clamps the rgb values by the min and max values and stores the result into "result"
  1979. * @param min defines minimum clamping value (default is 0)
  1980. * @param max defines maximum clamping value (default is 1)
  1981. * @param result defines color to store the result into.
  1982. * @returns the cuurent Color4
  1983. */
  1984. Color4.prototype.clampToRef = function (min, max, result) {
  1985. if (min === void 0) { min = 0; }
  1986. if (max === void 0) { max = 1; }
  1987. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1988. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1989. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1990. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1991. return this;
  1992. };
  1993. /**
  1994. * Multipy an Color4 value by another and return a new Color4 object
  1995. * @param color defines the Color4 value to multiply by
  1996. * @returns a new Color4 object
  1997. */
  1998. Color4.prototype.multiply = function (color) {
  1999. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2000. };
  2001. /**
  2002. * Multipy a Color4 value by another and push the result in a reference value
  2003. * @param color defines the Color4 value to multiply by
  2004. * @param result defines the Color4 to fill the result in
  2005. * @returns the result Color4
  2006. */
  2007. Color4.prototype.multiplyToRef = function (color, result) {
  2008. result.r = this.r * color.r;
  2009. result.g = this.g * color.g;
  2010. result.b = this.b * color.b;
  2011. result.a = this.a * color.a;
  2012. return result;
  2013. };
  2014. /**
  2015. * Creates a string with the Color4 current values
  2016. * @returns the string representation of the Color4 object
  2017. */
  2018. Color4.prototype.toString = function () {
  2019. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2020. };
  2021. /**
  2022. * Returns the string "Color4"
  2023. * @returns "Color4"
  2024. */
  2025. Color4.prototype.getClassName = function () {
  2026. return "Color4";
  2027. };
  2028. /**
  2029. * Compute the Color4 hash code
  2030. * @returns an unique number that can be used to hash Color4 objects
  2031. */
  2032. Color4.prototype.getHashCode = function () {
  2033. var hash = this.r || 0;
  2034. hash = (hash * 397) ^ (this.g || 0);
  2035. hash = (hash * 397) ^ (this.b || 0);
  2036. hash = (hash * 397) ^ (this.a || 0);
  2037. return hash;
  2038. };
  2039. /**
  2040. * Creates a new Color4 copied from the current one
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.clone = function () {
  2044. return new Color4(this.r, this.g, this.b, this.a);
  2045. };
  2046. /**
  2047. * Copies the given Color4 values into the current one
  2048. * @param source defines the source Color4 object
  2049. * @returns the current updated Color4 object
  2050. */
  2051. Color4.prototype.copyFrom = function (source) {
  2052. this.r = source.r;
  2053. this.g = source.g;
  2054. this.b = source.b;
  2055. this.a = source.a;
  2056. return this;
  2057. };
  2058. /**
  2059. * Copies the given float values into the current one
  2060. * @param r defines the red component to read from
  2061. * @param g defines the green component to read from
  2062. * @param b defines the blue component to read from
  2063. * @param a defines the alpha component to read from
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2067. this.r = r;
  2068. this.g = g;
  2069. this.b = b;
  2070. this.a = a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.set = function (r, g, b, a) {
  2082. return this.copyFromFloats(r, g, b, a);
  2083. };
  2084. /**
  2085. * Compute the Color4 hexadecimal code as a string
  2086. * @returns a string containing the hexadecimal representation of the Color4 object
  2087. */
  2088. Color4.prototype.toHexString = function () {
  2089. var intR = (this.r * 255) | 0;
  2090. var intG = (this.g * 255) | 0;
  2091. var intB = (this.b * 255) | 0;
  2092. var intA = (this.a * 255) | 0;
  2093. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2094. };
  2095. /**
  2096. * Computes a new Color4 converted from the current one to linear space
  2097. * @returns a new Color4 object
  2098. */
  2099. Color4.prototype.toLinearSpace = function () {
  2100. var convertedColor = new Color4();
  2101. this.toLinearSpaceToRef(convertedColor);
  2102. return convertedColor;
  2103. };
  2104. /**
  2105. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2106. * @param convertedColor defines the Color4 object where to store the linear space version
  2107. * @returns the unmodified Color4
  2108. */
  2109. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2110. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2111. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2112. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2113. convertedColor.a = this.a;
  2114. return this;
  2115. };
  2116. /**
  2117. * Computes a new Color4 converted from the current one to gamma space
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.prototype.toGammaSpace = function () {
  2121. var convertedColor = new Color4();
  2122. this.toGammaSpaceToRef(convertedColor);
  2123. return convertedColor;
  2124. };
  2125. /**
  2126. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2127. * @param convertedColor defines the Color4 object where to store the gamma space version
  2128. * @returns the unmodified Color4
  2129. */
  2130. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2131. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2132. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2133. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2134. convertedColor.a = this.a;
  2135. return this;
  2136. };
  2137. // Statics
  2138. /**
  2139. * Creates a new Color4 from the string containing valid hexadecimal values
  2140. * @param hex defines a string containing valid hexadecimal values
  2141. * @returns a new Color4 object
  2142. */
  2143. Color4.FromHexString = function (hex) {
  2144. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2145. return new Color4(0.0, 0.0, 0.0, 0.0);
  2146. }
  2147. var r = parseInt(hex.substring(1, 3), 16);
  2148. var g = parseInt(hex.substring(3, 5), 16);
  2149. var b = parseInt(hex.substring(5, 7), 16);
  2150. var a = parseInt(hex.substring(7, 9), 16);
  2151. return Color4.FromInts(r, g, b, a);
  2152. };
  2153. /**
  2154. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @returns a new Color4 object
  2159. */
  2160. Color4.Lerp = function (left, right, amount) {
  2161. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2162. Color4.LerpToRef(left, right, amount, result);
  2163. return result;
  2164. };
  2165. /**
  2166. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2167. * @param left defines the start value
  2168. * @param right defines the end value
  2169. * @param amount defines the gradient factor
  2170. * @param result defines the Color4 object where to store data
  2171. */
  2172. Color4.LerpToRef = function (left, right, amount, result) {
  2173. result.r = left.r + (right.r - left.r) * amount;
  2174. result.g = left.g + (right.g - left.g) * amount;
  2175. result.b = left.b + (right.b - left.b) * amount;
  2176. result.a = left.a + (right.a - left.a) * amount;
  2177. };
  2178. /**
  2179. * Creates a new Color4 from a Color3 and an alpha value
  2180. * @param color3 defines the source Color3 to read from
  2181. * @param alpha defines the alpha component (1.0 by default)
  2182. * @returns a new Color4 object
  2183. */
  2184. Color4.FromColor3 = function (color3, alpha) {
  2185. if (alpha === void 0) { alpha = 1.0; }
  2186. return new Color4(color3.r, color3.g, color3.b, alpha);
  2187. };
  2188. /**
  2189. * Creates a new Color4 from the starting index element of the given array
  2190. * @param array defines the source array to read from
  2191. * @param offset defines the offset in the source array
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromArray = function (array, offset) {
  2195. if (offset === void 0) { offset = 0; }
  2196. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2197. };
  2198. /**
  2199. * Creates a new Color3 from integer values (< 256)
  2200. * @param r defines the red component to read from (value between 0 and 255)
  2201. * @param g defines the green component to read from (value between 0 and 255)
  2202. * @param b defines the blue component to read from (value between 0 and 255)
  2203. * @param a defines the alpha component to read from (value between 0 and 255)
  2204. * @returns a new Color3 object
  2205. */
  2206. Color4.FromInts = function (r, g, b, a) {
  2207. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2208. };
  2209. /**
  2210. * Check the content of a given array and convert it to an array containing RGBA data
  2211. * If the original array was already containing count * 4 values then it is returned directly
  2212. * @param colors defines the array to check
  2213. * @param count defines the number of RGBA data to expect
  2214. * @returns an array containing count * 4 values (RGBA)
  2215. */
  2216. Color4.CheckColors4 = function (colors, count) {
  2217. // Check if color3 was used
  2218. if (colors.length === count * 3) {
  2219. var colors4 = [];
  2220. for (var index = 0; index < colors.length; index += 3) {
  2221. var newIndex = (index / 3) * 4;
  2222. colors4[newIndex] = colors[index];
  2223. colors4[newIndex + 1] = colors[index + 1];
  2224. colors4[newIndex + 2] = colors[index + 2];
  2225. colors4[newIndex + 3] = 1.0;
  2226. }
  2227. return colors4;
  2228. }
  2229. return colors;
  2230. };
  2231. return Color4;
  2232. }());
  2233. BABYLON.Color4 = Color4;
  2234. /**
  2235. * Class representing a vector containing 2 coordinates
  2236. */
  2237. var Vector2 = /** @class */ (function () {
  2238. /**
  2239. * Creates a new Vector2 from the given x and y coordinates
  2240. * @param x defines the first coordinate
  2241. * @param y defines the second coordinate
  2242. */
  2243. function Vector2(
  2244. /** defines the first coordinate */
  2245. x,
  2246. /** defines the second coordinate */
  2247. y) {
  2248. if (x === void 0) { x = 0; }
  2249. if (y === void 0) { y = 0; }
  2250. this.x = x;
  2251. this.y = y;
  2252. }
  2253. /**
  2254. * Gets a string with the Vector2 coordinates
  2255. * @returns a string with the Vector2 coordinates
  2256. */
  2257. Vector2.prototype.toString = function () {
  2258. return "{X: " + this.x + " Y:" + this.y + "}";
  2259. };
  2260. /**
  2261. * Gets class name
  2262. * @returns the string "Vector2"
  2263. */
  2264. Vector2.prototype.getClassName = function () {
  2265. return "Vector2";
  2266. };
  2267. /**
  2268. * Gets current vector hash code
  2269. * @returns the Vector2 hash code as a number
  2270. */
  2271. Vector2.prototype.getHashCode = function () {
  2272. var hash = this.x || 0;
  2273. hash = (hash * 397) ^ (this.y || 0);
  2274. return hash;
  2275. };
  2276. // Operators
  2277. /**
  2278. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2279. * @param array defines the source array
  2280. * @param index defines the offset in source array
  2281. * @returns the current Vector2
  2282. */
  2283. Vector2.prototype.toArray = function (array, index) {
  2284. if (index === void 0) { index = 0; }
  2285. array[index] = this.x;
  2286. array[index + 1] = this.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Copy the current vector to an array
  2291. * @returns a new array with 2 elements: the Vector2 coordinates.
  2292. */
  2293. Vector2.prototype.asArray = function () {
  2294. var result = new Array();
  2295. this.toArray(result, 0);
  2296. return result;
  2297. };
  2298. /**
  2299. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2300. * @param source defines the source Vector2
  2301. * @returns the current updated Vector2
  2302. */
  2303. Vector2.prototype.copyFrom = function (source) {
  2304. this.x = source.x;
  2305. this.y = source.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Sets the Vector2 coordinates with the given floats
  2310. * @param x defines the first coordinate
  2311. * @param y defines the second coordinate
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.copyFromFloats = function (x, y) {
  2315. this.x = x;
  2316. this.y = y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the Vector2 coordinates with the given floats
  2321. * @param x defines the first coordinate
  2322. * @param y defines the second coordinate
  2323. * @returns the current updated Vector2
  2324. */
  2325. Vector2.prototype.set = function (x, y) {
  2326. return this.copyFromFloats(x, y);
  2327. };
  2328. /**
  2329. * Add another vector with the current one
  2330. * @param otherVector defines the other vector
  2331. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2332. */
  2333. Vector2.prototype.add = function (otherVector) {
  2334. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2335. };
  2336. /**
  2337. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @param result defines the target vector
  2340. * @returns the unmodified current Vector2
  2341. */
  2342. Vector2.prototype.addToRef = function (otherVector, result) {
  2343. result.x = this.x + otherVector.x;
  2344. result.y = this.y + otherVector.y;
  2345. return this;
  2346. };
  2347. /**
  2348. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2349. * @param otherVector defines the other vector
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.addInPlace = function (otherVector) {
  2353. this.x += otherVector.x;
  2354. this.y += otherVector.y;
  2355. return this;
  2356. };
  2357. /**
  2358. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2359. * @param otherVector defines the other vector
  2360. * @returns a new Vector2
  2361. */
  2362. Vector2.prototype.addVector3 = function (otherVector) {
  2363. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2364. };
  2365. /**
  2366. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2367. * @param otherVector defines the other vector
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.subtract = function (otherVector) {
  2371. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2372. };
  2373. /**
  2374. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2375. * @param otherVector defines the other vector
  2376. * @param result defines the target vector
  2377. * @returns the unmodified current Vector2
  2378. */
  2379. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2380. result.x = this.x - otherVector.x;
  2381. result.y = this.y - otherVector.y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @returns the current updated Vector2
  2388. */
  2389. Vector2.prototype.subtractInPlace = function (otherVector) {
  2390. this.x -= otherVector.x;
  2391. this.y -= otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Multiplies in place the current Vector2 coordinates by the given ones
  2396. * @param otherVector defines the other vector
  2397. * @returns the current updated Vector2
  2398. */
  2399. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2400. this.x *= otherVector.x;
  2401. this.y *= otherVector.y;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2406. * @param otherVector defines the other vector
  2407. * @returns a new Vector2
  2408. */
  2409. Vector2.prototype.multiply = function (otherVector) {
  2410. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2411. };
  2412. /**
  2413. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2414. * @param otherVector defines the other vector
  2415. * @param result defines the target vector
  2416. * @returns the unmodified current Vector2
  2417. */
  2418. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2419. result.x = this.x * otherVector.x;
  2420. result.y = this.y * otherVector.y;
  2421. return this;
  2422. };
  2423. /**
  2424. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2425. * @param x defines the first coordinate
  2426. * @param y defines the second coordinate
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.multiplyByFloats = function (x, y) {
  2430. return new Vector2(this.x * x, this.y * y);
  2431. };
  2432. /**
  2433. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns a new Vector2
  2436. */
  2437. Vector2.prototype.divide = function (otherVector) {
  2438. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2439. };
  2440. /**
  2441. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @param result defines the target vector
  2444. * @returns the unmodified current Vector2
  2445. */
  2446. Vector2.prototype.divideToRef = function (otherVector, result) {
  2447. result.x = this.x / otherVector.x;
  2448. result.y = this.y / otherVector.y;
  2449. return this;
  2450. };
  2451. /**
  2452. * Divides the current Vector2 coordinates by the given ones
  2453. * @param otherVector defines the other vector
  2454. * @returns the current updated Vector2
  2455. */
  2456. Vector2.prototype.divideInPlace = function (otherVector) {
  2457. return this.divideToRef(otherVector, this);
  2458. };
  2459. /**
  2460. * Gets a new Vector2 with current Vector2 negated coordinates
  2461. * @returns a new Vector2
  2462. */
  2463. Vector2.prototype.negate = function () {
  2464. return new Vector2(-this.x, -this.y);
  2465. };
  2466. /**
  2467. * Multiply the Vector2 coordinates by scale
  2468. * @param scale defines the scaling factor
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.scaleInPlace = function (scale) {
  2472. this.x *= scale;
  2473. this.y *= scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2478. * @param scale defines the scaling factor
  2479. * @returns a new Vector2
  2480. */
  2481. Vector2.prototype.scale = function (scale) {
  2482. var result = new Vector2(0, 0);
  2483. this.scaleToRef(scale, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Scale the current Vector2 values by a factor to a given Vector2
  2488. * @param scale defines the scale factor
  2489. * @param result defines the Vector2 object where to store the result
  2490. * @returns the unmodified current Vector2
  2491. */
  2492. Vector2.prototype.scaleToRef = function (scale, result) {
  2493. result.x = this.x * scale;
  2494. result.y = this.y * scale;
  2495. return this;
  2496. };
  2497. /**
  2498. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2499. * @param scale defines the scale factor
  2500. * @param result defines the Vector2 object where to store the result
  2501. * @returns the unmodified current Vector2
  2502. */
  2503. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2504. result.x += this.x * scale;
  2505. result.y += this.y * scale;
  2506. return this;
  2507. };
  2508. /**
  2509. * Gets a boolean if two vectors are equals
  2510. * @param otherVector defines the other vector
  2511. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2512. */
  2513. Vector2.prototype.equals = function (otherVector) {
  2514. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2515. };
  2516. /**
  2517. * Gets a boolean if two vectors are equals (using an epsilon value)
  2518. * @param otherVector defines the other vector
  2519. * @param epsilon defines the minimal distance to consider equality
  2520. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2521. */
  2522. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2523. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2524. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2525. };
  2526. /**
  2527. * Gets a new Vector2 from current Vector2 floored values
  2528. * @returns a new Vector2
  2529. */
  2530. Vector2.prototype.floor = function () {
  2531. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2532. };
  2533. /**
  2534. * Gets a new Vector2 from current Vector2 floored values
  2535. * @returns a new Vector2
  2536. */
  2537. Vector2.prototype.fract = function () {
  2538. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2539. };
  2540. // Properties
  2541. /**
  2542. * Gets the length of the vector
  2543. * @returns the vector length (float)
  2544. */
  2545. Vector2.prototype.length = function () {
  2546. return Math.sqrt(this.x * this.x + this.y * this.y);
  2547. };
  2548. /**
  2549. * Gets the vector squared length
  2550. * @returns the vector squared length (float)
  2551. */
  2552. Vector2.prototype.lengthSquared = function () {
  2553. return (this.x * this.x + this.y * this.y);
  2554. };
  2555. // Methods
  2556. /**
  2557. * Normalize the vector
  2558. * @returns the current updated Vector2
  2559. */
  2560. Vector2.prototype.normalize = function () {
  2561. var len = this.length();
  2562. if (len === 0)
  2563. return this;
  2564. var num = 1.0 / len;
  2565. this.x *= num;
  2566. this.y *= num;
  2567. return this;
  2568. };
  2569. /**
  2570. * Gets a new Vector2 copied from the Vector2
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.clone = function () {
  2574. return new Vector2(this.x, this.y);
  2575. };
  2576. // Statics
  2577. /**
  2578. * Gets a new Vector2(0, 0)
  2579. * @returns a new Vector2
  2580. */
  2581. Vector2.Zero = function () {
  2582. return new Vector2(0, 0);
  2583. };
  2584. /**
  2585. * Gets a new Vector2(1, 1)
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.One = function () {
  2589. return new Vector2(1, 1);
  2590. };
  2591. /**
  2592. * Gets a new Vector2 set from the given index element of the given array
  2593. * @param array defines the data source
  2594. * @param offset defines the offset in the data source
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.FromArray = function (array, offset) {
  2598. if (offset === void 0) { offset = 0; }
  2599. return new Vector2(array[offset], array[offset + 1]);
  2600. };
  2601. /**
  2602. * Sets "result" from the given index element of the given array
  2603. * @param array defines the data source
  2604. * @param offset defines the offset in the data source
  2605. * @param result defines the target vector
  2606. */
  2607. Vector2.FromArrayToRef = function (array, offset, result) {
  2608. result.x = array[offset];
  2609. result.y = array[offset + 1];
  2610. };
  2611. /**
  2612. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2613. * @param value1 defines 1st point of control
  2614. * @param value2 defines 2nd point of control
  2615. * @param value3 defines 3rd point of control
  2616. * @param value4 defines 4th point of control
  2617. * @param amount defines the interpolation factor
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2621. var squared = amount * amount;
  2622. var cubed = amount * squared;
  2623. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2624. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2625. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2626. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2627. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2628. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2629. return new Vector2(x, y);
  2630. };
  2631. /**
  2632. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2633. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2634. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2635. * @param value defines the value to clamp
  2636. * @param min defines the lower limit
  2637. * @param max defines the upper limit
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Clamp = function (value, min, max) {
  2641. var x = value.x;
  2642. x = (x > max.x) ? max.x : x;
  2643. x = (x < min.x) ? min.x : x;
  2644. var y = value.y;
  2645. y = (y > max.y) ? max.y : y;
  2646. y = (y < min.y) ? min.y : y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2651. * @param value1 defines the 1st control point
  2652. * @param tangent1 defines the outgoing tangent
  2653. * @param value2 defines the 2nd control point
  2654. * @param tangent2 defines the incoming tangent
  2655. * @param amount defines the interpolation factor
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2659. var squared = amount * amount;
  2660. var cubed = amount * squared;
  2661. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2662. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2663. var part3 = (cubed - (2.0 * squared)) + amount;
  2664. var part4 = cubed - squared;
  2665. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2666. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2671. * @param start defines the start vector
  2672. * @param end defines the end vector
  2673. * @param amount defines the interpolation factor
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Lerp = function (start, end, amount) {
  2677. var x = start.x + ((end.x - start.x) * amount);
  2678. var y = start.y + ((end.y - start.y) * amount);
  2679. return new Vector2(x, y);
  2680. };
  2681. /**
  2682. * Gets the dot product of the vector "left" and the vector "right"
  2683. * @param left defines first vector
  2684. * @param right defines second vector
  2685. * @returns the dot product (float)
  2686. */
  2687. Vector2.Dot = function (left, right) {
  2688. return left.x * right.x + left.y * right.y;
  2689. };
  2690. /**
  2691. * Returns a new Vector2 equal to the normalized given vector
  2692. * @param vector defines the vector to normalize
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Normalize = function (vector) {
  2696. var newVector = vector.clone();
  2697. newVector.normalize();
  2698. return newVector;
  2699. };
  2700. /**
  2701. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2702. * @param left defines 1st vector
  2703. * @param right defines 2nd vector
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Minimize = function (left, right) {
  2707. var x = (left.x < right.x) ? left.x : right.x;
  2708. var y = (left.y < right.y) ? left.y : right.y;
  2709. return new Vector2(x, y);
  2710. };
  2711. /**
  2712. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2713. * @param left defines 1st vector
  2714. * @param right defines 2nd vector
  2715. * @returns a new Vector2
  2716. */
  2717. Vector2.Maximize = function (left, right) {
  2718. var x = (left.x > right.x) ? left.x : right.x;
  2719. var y = (left.y > right.y) ? left.y : right.y;
  2720. return new Vector2(x, y);
  2721. };
  2722. /**
  2723. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2724. * @param vector defines the vector to transform
  2725. * @param transformation defines the matrix to apply
  2726. * @returns a new Vector2
  2727. */
  2728. Vector2.Transform = function (vector, transformation) {
  2729. var r = Vector2.Zero();
  2730. Vector2.TransformToRef(vector, transformation, r);
  2731. return r;
  2732. };
  2733. /**
  2734. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2735. * @param vector defines the vector to transform
  2736. * @param transformation defines the matrix to apply
  2737. * @param result defines the target vector
  2738. */
  2739. Vector2.TransformToRef = function (vector, transformation, result) {
  2740. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2741. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2742. result.x = x;
  2743. result.y = y;
  2744. };
  2745. /**
  2746. * Determines if a given vector is included in a triangle
  2747. * @param p defines the vector to test
  2748. * @param p0 defines 1st triangle point
  2749. * @param p1 defines 2nd triangle point
  2750. * @param p2 defines 3rd triangle point
  2751. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2752. */
  2753. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2754. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2755. var sign = a < 0 ? -1 : 1;
  2756. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2757. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2758. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2759. };
  2760. /**
  2761. * Gets the distance between the vectors "value1" and "value2"
  2762. * @param value1 defines first vector
  2763. * @param value2 defines second vector
  2764. * @returns the distance between vectors
  2765. */
  2766. Vector2.Distance = function (value1, value2) {
  2767. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2768. };
  2769. /**
  2770. * Returns the squared distance between the vectors "value1" and "value2"
  2771. * @param value1 defines first vector
  2772. * @param value2 defines second vector
  2773. * @returns the squared distance between vectors
  2774. */
  2775. Vector2.DistanceSquared = function (value1, value2) {
  2776. var x = value1.x - value2.x;
  2777. var y = value1.y - value2.y;
  2778. return (x * x) + (y * y);
  2779. };
  2780. /**
  2781. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2782. * @param value1 defines first vector
  2783. * @param value2 defines second vector
  2784. * @returns a new Vector2
  2785. */
  2786. Vector2.Center = function (value1, value2) {
  2787. var center = value1.add(value2);
  2788. center.scaleInPlace(0.5);
  2789. return center;
  2790. };
  2791. /**
  2792. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2793. * @param p defines the middle point
  2794. * @param segA defines one point of the segment
  2795. * @param segB defines the other point of the segment
  2796. * @returns the shortest distance
  2797. */
  2798. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2799. var l2 = Vector2.DistanceSquared(segA, segB);
  2800. if (l2 === 0.0) {
  2801. return Vector2.Distance(p, segA);
  2802. }
  2803. var v = segB.subtract(segA);
  2804. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2805. var proj = segA.add(v.multiplyByFloats(t, t));
  2806. return Vector2.Distance(p, proj);
  2807. };
  2808. return Vector2;
  2809. }());
  2810. BABYLON.Vector2 = Vector2;
  2811. /**
  2812. * Classed used to store (x,y,z) vector representation
  2813. * A Vector3 is the main object used in 3D geometry
  2814. * It can represent etiher the coordinates of a point the space, either a direction
  2815. * Reminder: Babylon.js uses a left handed forward facing system
  2816. */
  2817. var Vector3 = /** @class */ (function () {
  2818. /**
  2819. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2820. * @param x defines the first coordinates (on X axis)
  2821. * @param y defines the second coordinates (on Y axis)
  2822. * @param z defines the third coordinates (on Z axis)
  2823. */
  2824. function Vector3(
  2825. /**
  2826. * Defines the first coordinates (on X axis)
  2827. */
  2828. x,
  2829. /**
  2830. * Defines the second coordinates (on Y axis)
  2831. */
  2832. y,
  2833. /**
  2834. * Defines the third coordinates (on Z axis)
  2835. */
  2836. z) {
  2837. if (x === void 0) { x = 0; }
  2838. if (y === void 0) { y = 0; }
  2839. if (z === void 0) { z = 0; }
  2840. this.x = x;
  2841. this.y = y;
  2842. this.z = z;
  2843. }
  2844. /**
  2845. * Creates a string representation of the Vector3
  2846. * @returns a string with the Vector3 coordinates.
  2847. */
  2848. Vector3.prototype.toString = function () {
  2849. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2850. };
  2851. /**
  2852. * Gets the class name
  2853. * @returns the string "Vector3"
  2854. */
  2855. Vector3.prototype.getClassName = function () {
  2856. return "Vector3";
  2857. };
  2858. /**
  2859. * Creates the Vector3 hash code
  2860. * @returns a number which tends to be unique between Vector3 instances
  2861. */
  2862. Vector3.prototype.getHashCode = function () {
  2863. var hash = this.x || 0;
  2864. hash = (hash * 397) ^ (this.y || 0);
  2865. hash = (hash * 397) ^ (this.z || 0);
  2866. return hash;
  2867. };
  2868. // Operators
  2869. /**
  2870. * Creates an array containing three elements : the coordinates of the Vector3
  2871. * @returns a new array of numbers
  2872. */
  2873. Vector3.prototype.asArray = function () {
  2874. var result = [];
  2875. this.toArray(result, 0);
  2876. return result;
  2877. };
  2878. /**
  2879. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2880. * @param array defines the destination array
  2881. * @param index defines the offset in the destination array
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.toArray = function (array, index) {
  2885. if (index === void 0) { index = 0; }
  2886. array[index] = this.x;
  2887. array[index + 1] = this.y;
  2888. array[index + 2] = this.z;
  2889. return this;
  2890. };
  2891. /**
  2892. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2893. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2894. */
  2895. Vector3.prototype.toQuaternion = function () {
  2896. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2897. };
  2898. /**
  2899. * Adds the given vector to the current Vector3
  2900. * @param otherVector defines the second operand
  2901. * @returns the current updated Vector3
  2902. */
  2903. Vector3.prototype.addInPlace = function (otherVector) {
  2904. this.x += otherVector.x;
  2905. this.y += otherVector.y;
  2906. this.z += otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2911. * @param otherVector defines the second operand
  2912. * @returns the resulting Vector3
  2913. */
  2914. Vector3.prototype.add = function (otherVector) {
  2915. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2916. };
  2917. /**
  2918. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.addToRef = function (otherVector, result) {
  2924. result.x = this.x + otherVector.x;
  2925. result.y = this.y + otherVector.y;
  2926. result.z = this.z + otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Subtract the given vector from the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.subtractInPlace = function (otherVector) {
  2935. this.x -= otherVector.x;
  2936. this.y -= otherVector.y;
  2937. this.z -= otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.subtract = function (otherVector) {
  2946. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2947. };
  2948. /**
  2949. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2955. result.x = this.x - otherVector.x;
  2956. result.y = this.y - otherVector.y;
  2957. result.z = this.z - otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2962. * @param x defines the x coordinate of the operand
  2963. * @param y defines the y coordinate of the operand
  2964. * @param z defines the z coordinate of the operand
  2965. * @returns the resulting Vector3
  2966. */
  2967. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2968. return new Vector3(this.x - x, this.y - y, this.z - z);
  2969. };
  2970. /**
  2971. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @param result defines the Vector3 object where to store the result
  2976. * @returns the current Vector3
  2977. */
  2978. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2979. result.x = this.x - x;
  2980. result.y = this.y - y;
  2981. result.z = this.z - z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2986. * @returns a new Vector3
  2987. */
  2988. Vector3.prototype.negate = function () {
  2989. return new Vector3(-this.x, -this.y, -this.z);
  2990. };
  2991. /**
  2992. * Multiplies the Vector3 coordinates by the float "scale"
  2993. * @param scale defines the multiplier factor
  2994. * @returns the current updated Vector3
  2995. */
  2996. Vector3.prototype.scaleInPlace = function (scale) {
  2997. this.x *= scale;
  2998. this.y *= scale;
  2999. this.z *= scale;
  3000. return this;
  3001. };
  3002. /**
  3003. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3004. * @param scale defines the multiplier factor
  3005. * @returns a new Vector3
  3006. */
  3007. Vector3.prototype.scale = function (scale) {
  3008. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3009. };
  3010. /**
  3011. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3012. * @param scale defines the multiplier factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the current Vector3
  3015. */
  3016. Vector3.prototype.scaleToRef = function (scale, result) {
  3017. result.x = this.x * scale;
  3018. result.y = this.y * scale;
  3019. result.z = this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3024. * @param scale defines the scale factor
  3025. * @param result defines the Vector3 object where to store the result
  3026. * @returns the unmodified current Vector3
  3027. */
  3028. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3029. result.x += this.x * scale;
  3030. result.y += this.y * scale;
  3031. result.z += this.z * scale;
  3032. return this;
  3033. };
  3034. /**
  3035. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3036. * @param otherVector defines the second operand
  3037. * @returns true if both vectors are equals
  3038. */
  3039. Vector3.prototype.equals = function (otherVector) {
  3040. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3041. };
  3042. /**
  3043. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3044. * @param otherVector defines the second operand
  3045. * @param epsilon defines the minimal distance to define values as equals
  3046. * @returns true if both vectors are distant less than epsilon
  3047. */
  3048. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3049. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3050. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3051. };
  3052. /**
  3053. * Returns true if the current Vector3 coordinates equals the given floats
  3054. * @param x defines the x coordinate of the operand
  3055. * @param y defines the y coordinate of the operand
  3056. * @param z defines the z coordinate of the operand
  3057. * @returns true if both vectors are equals
  3058. */
  3059. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3060. return this.x === x && this.y === y && this.z === z;
  3061. };
  3062. /**
  3063. * Multiplies the current Vector3 coordinates by the given ones
  3064. * @param otherVector defines the second operand
  3065. * @returns the current updated Vector3
  3066. */
  3067. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3068. this.x *= otherVector.x;
  3069. this.y *= otherVector.y;
  3070. this.z *= otherVector.z;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3075. * @param otherVector defines the second operand
  3076. * @returns the new Vector3
  3077. */
  3078. Vector3.prototype.multiply = function (otherVector) {
  3079. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3080. };
  3081. /**
  3082. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3083. * @param otherVector defines the second operand
  3084. * @param result defines the Vector3 object where to store the result
  3085. * @returns the current Vector3
  3086. */
  3087. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3088. result.x = this.x * otherVector.x;
  3089. result.y = this.y * otherVector.y;
  3090. result.z = this.z * otherVector.z;
  3091. return this;
  3092. };
  3093. /**
  3094. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3095. * @param x defines the x coordinate of the operand
  3096. * @param y defines the y coordinate of the operand
  3097. * @param z defines the z coordinate of the operand
  3098. * @returns the new Vector3
  3099. */
  3100. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3101. return new Vector3(this.x * x, this.y * y, this.z * z);
  3102. };
  3103. /**
  3104. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3105. * @param otherVector defines the second operand
  3106. * @returns the new Vector3
  3107. */
  3108. Vector3.prototype.divide = function (otherVector) {
  3109. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3113. * @param otherVector defines the second operand
  3114. * @param result defines the Vector3 object where to store the result
  3115. * @returns the current Vector3
  3116. */
  3117. Vector3.prototype.divideToRef = function (otherVector, result) {
  3118. result.x = this.x / otherVector.x;
  3119. result.y = this.y / otherVector.y;
  3120. result.z = this.z / otherVector.z;
  3121. return this;
  3122. };
  3123. /**
  3124. * Divides the current Vector3 coordinates by the given ones.
  3125. * @param otherVector defines the second operand
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.divideInPlace = function (otherVector) {
  3129. return this.divideToRef(otherVector, this);
  3130. };
  3131. /**
  3132. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3133. * @param other defines the second operand
  3134. * @returns the current updated Vector3
  3135. */
  3136. Vector3.prototype.minimizeInPlace = function (other) {
  3137. if (other.x < this.x)
  3138. this.x = other.x;
  3139. if (other.y < this.y)
  3140. this.y = other.y;
  3141. if (other.z < this.z)
  3142. this.z = other.z;
  3143. return this;
  3144. };
  3145. /**
  3146. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3147. * @param other defines the second operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.maximizeInPlace = function (other) {
  3151. if (other.x > this.x)
  3152. this.x = other.x;
  3153. if (other.y > this.y)
  3154. this.y = other.y;
  3155. if (other.z > this.z)
  3156. this.z = other.z;
  3157. return this;
  3158. };
  3159. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3160. /**
  3161. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3162. */
  3163. get: function () {
  3164. var absX = Math.abs(this.x);
  3165. var absY = Math.abs(this.y);
  3166. if (absX !== absY) {
  3167. return true;
  3168. }
  3169. var absZ = Math.abs(this.z);
  3170. if (absX !== absZ) {
  3171. return true;
  3172. }
  3173. if (absY !== absZ) {
  3174. return true;
  3175. }
  3176. return false;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. });
  3181. /**
  3182. * Gets a new Vector3 from current Vector3 floored values
  3183. * @returns a new Vector3
  3184. */
  3185. Vector3.prototype.floor = function () {
  3186. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3187. };
  3188. /**
  3189. * Gets a new Vector3 from current Vector3 floored values
  3190. * @returns a new Vector3
  3191. */
  3192. Vector3.prototype.fract = function () {
  3193. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3194. };
  3195. // Properties
  3196. /**
  3197. * Gets the length of the Vector3
  3198. * @returns the length of the Vecto3
  3199. */
  3200. Vector3.prototype.length = function () {
  3201. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3202. };
  3203. /**
  3204. * Gets the squared length of the Vector3
  3205. * @returns squared length of the Vector3
  3206. */
  3207. Vector3.prototype.lengthSquared = function () {
  3208. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3209. };
  3210. /**
  3211. * Normalize the current Vector3.
  3212. * Please note that this is an in place operation.
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.normalize = function () {
  3216. var len = this.length();
  3217. if (len === 0 || len === 1.0)
  3218. return this;
  3219. var num = 1.0 / len;
  3220. this.x *= num;
  3221. this.y *= num;
  3222. this.z *= num;
  3223. return this;
  3224. };
  3225. /**
  3226. * Normalize the current Vector3 to a new vector
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.prototype.normalizeToNew = function () {
  3230. var normalized = new Vector3(0, 0, 0);
  3231. this.normalizeToRef(normalized);
  3232. return normalized;
  3233. };
  3234. /**
  3235. * Normalize the current Vector3 to the reference
  3236. * @param reference define the Vector3 to update
  3237. * @returns the updated Vector3
  3238. */
  3239. Vector3.prototype.normalizeToRef = function (reference) {
  3240. var len = this.length();
  3241. if (len === 0 || len === 1.0) {
  3242. reference.set(this.x, this.y, this.z);
  3243. return reference;
  3244. }
  3245. var scale = 1.0 / len;
  3246. this.scaleToRef(scale, reference);
  3247. return reference;
  3248. };
  3249. /**
  3250. * Creates a new Vector3 copied from the current Vector3
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.prototype.clone = function () {
  3254. return new Vector3(this.x, this.y, this.z);
  3255. };
  3256. /**
  3257. * Copies the given vector coordinates to the current Vector3 ones
  3258. * @param source defines the source Vector3
  3259. * @returns the current updated Vector3
  3260. */
  3261. Vector3.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. return this;
  3266. };
  3267. /**
  3268. * Copies the given floats to the current Vector3 coordinates
  3269. * @param x defines the x coordinate of the operand
  3270. * @param y defines the y coordinate of the operand
  3271. * @param z defines the z coordinate of the operand
  3272. * @returns the current updated Vector3
  3273. */
  3274. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3275. this.x = x;
  3276. this.y = y;
  3277. this.z = z;
  3278. return this;
  3279. };
  3280. /**
  3281. * Copies the given floats to the current Vector3 coordinates
  3282. * @param x defines the x coordinate of the operand
  3283. * @param y defines the y coordinate of the operand
  3284. * @param z defines the z coordinate of the operand
  3285. * @returns the current updated Vector3
  3286. */
  3287. Vector3.prototype.set = function (x, y, z) {
  3288. return this.copyFromFloats(x, y, z);
  3289. };
  3290. // Statics
  3291. /**
  3292. * Get the clip factor between two vectors
  3293. * @param vector0 defines the first operand
  3294. * @param vector1 defines the second operand
  3295. * @param axis defines the axis to use
  3296. * @param size defines the size along the axis
  3297. * @returns the clip factor
  3298. */
  3299. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3300. var d0 = Vector3.Dot(vector0, axis) - size;
  3301. var d1 = Vector3.Dot(vector1, axis) - size;
  3302. var s = d0 / (d0 - d1);
  3303. return s;
  3304. };
  3305. /**
  3306. * Get angle between two vectors
  3307. * @param vector0 angle between vector0 and vector1
  3308. * @param vector1 angle between vector0 and vector1
  3309. * @param normal direction of the normal
  3310. * @return the angle between vector0 and vector1
  3311. */
  3312. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3313. var v0 = vector0.clone().normalize();
  3314. var v1 = vector1.clone().normalize();
  3315. var dot = Vector3.Dot(v0, v1);
  3316. var n = Vector3.Cross(v0, v1);
  3317. if (Vector3.Dot(n, normal) > 0) {
  3318. return Math.acos(dot);
  3319. }
  3320. return -Math.acos(dot);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given array
  3324. * @param array defines the source array
  3325. * @param offset defines the offset in the source array
  3326. * @returns the new Vector3
  3327. */
  3328. Vector3.FromArray = function (array, offset) {
  3329. if (!offset) {
  3330. offset = 0;
  3331. }
  3332. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3336. * This function is deprecated. Use FromArray instead
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.FromFloatArray = function (array, offset) {
  3342. return Vector3.FromArray(array, offset);
  3343. };
  3344. /**
  3345. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromArrayToRef = function (array, offset, result) {
  3351. result.x = array[offset];
  3352. result.y = array[offset + 1];
  3353. result.z = array[offset + 2];
  3354. };
  3355. /**
  3356. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3357. * This function is deprecated. Use FromArrayToRef instead.
  3358. * @param array defines the source array
  3359. * @param offset defines the offset in the source array
  3360. * @param result defines the Vector3 where to store the result
  3361. */
  3362. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3363. return Vector3.FromArrayToRef(array, offset, result);
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the given floats.
  3367. * @param x defines the x coordinate of the source
  3368. * @param y defines the y coordinate of the source
  3369. * @param z defines the z coordinate of the source
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3373. result.x = x;
  3374. result.y = y;
  3375. result.z = z;
  3376. };
  3377. /**
  3378. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3379. * @returns a new empty Vector3
  3380. */
  3381. Vector3.Zero = function () {
  3382. return new Vector3(0.0, 0.0, 0.0);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3386. * @returns a new unit Vector3
  3387. */
  3388. Vector3.One = function () {
  3389. return new Vector3(1.0, 1.0, 1.0);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3393. * @returns a new up Vector3
  3394. */
  3395. Vector3.Up = function () {
  3396. return new Vector3(0.0, 1.0, 0.0);
  3397. };
  3398. /**
  3399. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3400. * @returns a new down Vector3
  3401. */
  3402. Vector3.Down = function () {
  3403. return new Vector3(0.0, -1.0, 0.0);
  3404. };
  3405. /**
  3406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3407. * @returns a new forward Vector3
  3408. */
  3409. Vector3.Forward = function () {
  3410. return new Vector3(0.0, 0.0, 1.0);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3414. * @returns a new forward Vector3
  3415. */
  3416. Vector3.Backward = function () {
  3417. return new Vector3(0.0, 0.0, -1.0);
  3418. };
  3419. /**
  3420. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3421. * @returns a new right Vector3
  3422. */
  3423. Vector3.Right = function () {
  3424. return new Vector3(1.0, 0.0, 0.0);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3428. * @returns a new left Vector3
  3429. */
  3430. Vector3.Left = function () {
  3431. return new Vector3(-1.0, 0.0, 0.0);
  3432. };
  3433. /**
  3434. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3435. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3436. * @param vector defines the Vector3 to transform
  3437. * @param transformation defines the transformation matrix
  3438. * @returns the transformed Vector3
  3439. */
  3440. Vector3.TransformCoordinates = function (vector, transformation) {
  3441. var result = Vector3.Zero();
  3442. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3447. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3448. * @param vector defines the Vector3 to transform
  3449. * @param transformation defines the transformation matrix
  3450. * @param result defines the Vector3 where to store the result
  3451. */
  3452. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3456. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3457. result.x = x / w;
  3458. result.y = y / w;
  3459. result.z = z / w;
  3460. };
  3461. /**
  3462. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3463. * This method computes tranformed coordinates only, not transformed direction vectors
  3464. * @param x define the x coordinate of the source vector
  3465. * @param y define the y coordinate of the source vector
  3466. * @param z define the z coordinate of the source vector
  3467. * @param transformation defines the transformation matrix
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3471. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3472. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3473. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3474. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3475. result.x = rx / rw;
  3476. result.y = ry / rw;
  3477. result.z = rz / rw;
  3478. };
  3479. /**
  3480. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3481. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3482. * @param vector defines the Vector3 to transform
  3483. * @param transformation defines the transformation matrix
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.TransformNormal = function (vector, transformation) {
  3487. var result = Vector3.Zero();
  3488. Vector3.TransformNormalToRef(vector, transformation, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3493. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3494. * @param vector defines the Vector3 to transform
  3495. * @param transformation defines the transformation matrix
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3499. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3500. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3501. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3502. result.x = x;
  3503. result.y = y;
  3504. result.z = z;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param x define the x coordinate of the source vector
  3510. * @param y define the y coordinate of the source vector
  3511. * @param z define the z coordinate of the source vector
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3516. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3517. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3518. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3519. };
  3520. /**
  3521. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3522. * @param value1 defines the first control point
  3523. * @param value2 defines the second control point
  3524. * @param value3 defines the third control point
  3525. * @param value4 defines the fourth control point
  3526. * @param amount defines the amount on the spline to use
  3527. * @returns the new Vector3
  3528. */
  3529. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3530. var squared = amount * amount;
  3531. var cubed = amount * squared;
  3532. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3533. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3534. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3535. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3536. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3537. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3538. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3539. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3540. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3541. return new Vector3(x, y, z);
  3542. };
  3543. /**
  3544. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3545. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3546. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3547. * @param value defines the current value
  3548. * @param min defines the lower range value
  3549. * @param max defines the upper range value
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Clamp = function (value, min, max) {
  3553. var x = value.x;
  3554. x = (x > max.x) ? max.x : x;
  3555. x = (x < min.x) ? min.x : x;
  3556. var y = value.y;
  3557. y = (y > max.y) ? max.y : y;
  3558. y = (y < min.y) ? min.y : y;
  3559. var z = value.z;
  3560. z = (z > max.z) ? max.z : z;
  3561. z = (z < min.z) ? min.z : z;
  3562. return new Vector3(x, y, z);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3566. * @param value1 defines the first control point
  3567. * @param tangent1 defines the first tangent vector
  3568. * @param value2 defines the second control point
  3569. * @param tangent2 defines the second tangent vector
  3570. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3574. var squared = amount * amount;
  3575. var cubed = amount * squared;
  3576. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3577. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3578. var part3 = (cubed - (2.0 * squared)) + amount;
  3579. var part4 = cubed - squared;
  3580. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3581. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3582. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3583. return new Vector3(x, y, z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3587. * @param start defines the start value
  3588. * @param end defines the end value
  3589. * @param amount max defines amount between both (between 0 and 1)
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Lerp = function (start, end, amount) {
  3593. var result = new Vector3(0, 0, 0);
  3594. Vector3.LerpToRef(start, end, amount, result);
  3595. return result;
  3596. };
  3597. /**
  3598. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3599. * @param start defines the start value
  3600. * @param end defines the end value
  3601. * @param amount max defines amount between both (between 0 and 1)
  3602. * @param result defines the Vector3 where to store the result
  3603. */
  3604. Vector3.LerpToRef = function (start, end, amount, result) {
  3605. result.x = start.x + ((end.x - start.x) * amount);
  3606. result.y = start.y + ((end.y - start.y) * amount);
  3607. result.z = start.z + ((end.z - start.z) * amount);
  3608. };
  3609. /**
  3610. * Returns the dot product (float) between the vectors "left" and "right"
  3611. * @param left defines the left operand
  3612. * @param right defines the right operand
  3613. * @returns the dot product
  3614. */
  3615. Vector3.Dot = function (left, right) {
  3616. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3617. };
  3618. /**
  3619. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3620. * The cross product is then orthogonal to both "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @returns the cross product
  3624. */
  3625. Vector3.Cross = function (left, right) {
  3626. var result = Vector3.Zero();
  3627. Vector3.CrossToRef(left, right, result);
  3628. return result;
  3629. };
  3630. /**
  3631. * Sets the given vector "result" with the cross product of "left" and "right"
  3632. * The cross product is then orthogonal to both "left" and "right"
  3633. * @param left defines the left operand
  3634. * @param right defines the right operand
  3635. * @param result defines the Vector3 where to store the result
  3636. */
  3637. Vector3.CrossToRef = function (left, right, result) {
  3638. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3639. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3640. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3641. result.copyFrom(MathTmp.Vector3[0]);
  3642. };
  3643. /**
  3644. * Returns a new Vector3 as the normalization of the given vector
  3645. * @param vector defines the Vector3 to normalize
  3646. * @returns the new Vector3
  3647. */
  3648. Vector3.Normalize = function (vector) {
  3649. var result = Vector3.Zero();
  3650. Vector3.NormalizeToRef(vector, result);
  3651. return result;
  3652. };
  3653. /**
  3654. * Sets the given vector "result" with the normalization of the given first vector
  3655. * @param vector defines the Vector3 to normalize
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.NormalizeToRef = function (vector, result) {
  3659. result.copyFrom(vector);
  3660. result.normalize();
  3661. };
  3662. /**
  3663. * Project a Vector3 onto screen space
  3664. * @param vector defines the Vector3 to project
  3665. * @param world defines the world matrix to use
  3666. * @param transform defines the transform (view x projection) matrix to use
  3667. * @param viewport defines the screen viewport to use
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Project = function (vector, world, transform, viewport) {
  3671. var cw = viewport.width;
  3672. var ch = viewport.height;
  3673. var cx = viewport.x;
  3674. var cy = viewport.y;
  3675. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3676. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3677. var matrix = MathTmp.Matrix[0];
  3678. world.multiplyToRef(transform, matrix);
  3679. matrix.multiplyToRef(viewportMatrix, matrix);
  3680. return Vector3.TransformCoordinates(vector, matrix);
  3681. };
  3682. /**
  3683. * Unproject from screen space to object space
  3684. * @param source defines the screen space Vector3 to use
  3685. * @param viewportWidth defines the current width of the viewport
  3686. * @param viewportHeight defines the current height of the viewport
  3687. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3688. * @param transform defines the transform (view x projection) matrix to use
  3689. * @returns the new Vector3
  3690. */
  3691. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.invert();
  3695. source.x = source.x / viewportWidth * 2 - 1;
  3696. source.y = -(source.y / viewportHeight * 2 - 1);
  3697. var vector = Vector3.TransformCoordinates(source, matrix);
  3698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3699. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3700. vector = vector.scale(1.0 / num);
  3701. }
  3702. return vector;
  3703. };
  3704. /**
  3705. * Unproject from screen space to object space
  3706. * @param source defines the screen space Vector3 to use
  3707. * @param viewportWidth defines the current width of the viewport
  3708. * @param viewportHeight defines the current height of the viewport
  3709. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3710. * @param view defines the view matrix to use
  3711. * @param projection defines the projection matrix to use
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3715. var result = Vector3.Zero();
  3716. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3717. return result;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @param result defines the Vector3 where to store the result
  3728. */
  3729. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3730. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param sourceX defines the screen space x coordinate to use
  3735. * @param sourceY defines the screen space y coordinate to use
  3736. * @param sourceZ defines the screen space z coordinate to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. var matrix = MathTmp.Matrix[0];
  3746. world.multiplyToRef(view, matrix);
  3747. matrix.multiplyToRef(projection, matrix);
  3748. matrix.invert();
  3749. var screenSource = MathTmp.Vector3[0];
  3750. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3751. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3752. screenSource.z = 2 * sourceZ - 1.0;
  3753. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3754. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3756. result.scaleInPlace(1.0 / num);
  3757. }
  3758. };
  3759. /**
  3760. * Gets the minimal coordinate values between two Vector3
  3761. * @param left defines the first operand
  3762. * @param right defines the second operand
  3763. * @returns the new Vector3
  3764. */
  3765. Vector3.Minimize = function (left, right) {
  3766. var min = left.clone();
  3767. min.minimizeInPlace(right);
  3768. return min;
  3769. };
  3770. /**
  3771. * Gets the maximal coordinate values between two Vector3
  3772. * @param left defines the first operand
  3773. * @param right defines the second operand
  3774. * @returns the new Vector3
  3775. */
  3776. Vector3.Maximize = function (left, right) {
  3777. var max = left.clone();
  3778. max.maximizeInPlace(right);
  3779. return max;
  3780. };
  3781. /**
  3782. * Returns the distance between the vectors "value1" and "value2"
  3783. * @param value1 defines the first operand
  3784. * @param value2 defines the second operand
  3785. * @returns the distance
  3786. */
  3787. Vector3.Distance = function (value1, value2) {
  3788. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3789. };
  3790. /**
  3791. * Returns the squared distance between the vectors "value1" and "value2"
  3792. * @param value1 defines the first operand
  3793. * @param value2 defines the second operand
  3794. * @returns the squared distance
  3795. */
  3796. Vector3.DistanceSquared = function (value1, value2) {
  3797. var x = value1.x - value2.x;
  3798. var y = value1.y - value2.y;
  3799. var z = value1.z - value2.z;
  3800. return (x * x) + (y * y) + (z * z);
  3801. };
  3802. /**
  3803. * Returns a new Vector3 located at the center between "value1" and "value2"
  3804. * @param value1 defines the first operand
  3805. * @param value2 defines the second operand
  3806. * @returns the new Vector3
  3807. */
  3808. Vector3.Center = function (value1, value2) {
  3809. var center = value1.add(value2);
  3810. center.scaleInPlace(0.5);
  3811. return center;
  3812. };
  3813. /**
  3814. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3815. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3816. * to something in order to rotate it from its local system to the given target system
  3817. * Note: axis1, axis2 and axis3 are normalized during this operation
  3818. * @param axis1 defines the first axis
  3819. * @param axis2 defines the second axis
  3820. * @param axis3 defines the third axis
  3821. * @returns a new Vector3
  3822. */
  3823. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3824. var rotation = Vector3.Zero();
  3825. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3826. return rotation;
  3827. };
  3828. /**
  3829. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3830. * @param axis1 defines the first axis
  3831. * @param axis2 defines the second axis
  3832. * @param axis3 defines the third axis
  3833. * @param ref defines the Vector3 where to store the result
  3834. */
  3835. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3836. var quat = MathTmp.Quaternion[0];
  3837. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3838. quat.toEulerAnglesToRef(ref);
  3839. };
  3840. return Vector3;
  3841. }());
  3842. BABYLON.Vector3 = Vector3;
  3843. //Vector4 class created for EulerAngle class conversion to Quaternion
  3844. var Vector4 = /** @class */ (function () {
  3845. /**
  3846. * Creates a Vector4 object from the given floats.
  3847. */
  3848. function Vector4(x, y, z, w) {
  3849. this.x = x;
  3850. this.y = y;
  3851. this.z = z;
  3852. this.w = w;
  3853. }
  3854. /**
  3855. * Returns the string with the Vector4 coordinates.
  3856. */
  3857. Vector4.prototype.toString = function () {
  3858. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3859. };
  3860. /**
  3861. * Returns the string "Vector4".
  3862. */
  3863. Vector4.prototype.getClassName = function () {
  3864. return "Vector4";
  3865. };
  3866. /**
  3867. * Returns the Vector4 hash code.
  3868. */
  3869. Vector4.prototype.getHashCode = function () {
  3870. var hash = this.x || 0;
  3871. hash = (hash * 397) ^ (this.y || 0);
  3872. hash = (hash * 397) ^ (this.z || 0);
  3873. hash = (hash * 397) ^ (this.w || 0);
  3874. return hash;
  3875. };
  3876. // Operators
  3877. /**
  3878. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3879. */
  3880. Vector4.prototype.asArray = function () {
  3881. var result = new Array();
  3882. this.toArray(result, 0);
  3883. return result;
  3884. };
  3885. /**
  3886. * Populates the given array from the given index with the Vector4 coordinates.
  3887. * Returns the Vector4.
  3888. */
  3889. Vector4.prototype.toArray = function (array, index) {
  3890. if (index === undefined) {
  3891. index = 0;
  3892. }
  3893. array[index] = this.x;
  3894. array[index + 1] = this.y;
  3895. array[index + 2] = this.z;
  3896. array[index + 3] = this.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Adds the given vector to the current Vector4.
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.addInPlace = function (otherVector) {
  3904. this.x += otherVector.x;
  3905. this.y += otherVector.y;
  3906. this.z += otherVector.z;
  3907. this.w += otherVector.w;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3912. */
  3913. Vector4.prototype.add = function (otherVector) {
  3914. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3915. };
  3916. /**
  3917. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.addToRef = function (otherVector, result) {
  3921. result.x = this.x + otherVector.x;
  3922. result.y = this.y + otherVector.y;
  3923. result.z = this.z + otherVector.z;
  3924. result.w = this.w + otherVector.w;
  3925. return this;
  3926. };
  3927. /**
  3928. * Subtract in place the given vector from the current Vector4.
  3929. * Returns the updated Vector4.
  3930. */
  3931. Vector4.prototype.subtractInPlace = function (otherVector) {
  3932. this.x -= otherVector.x;
  3933. this.y -= otherVector.y;
  3934. this.z -= otherVector.z;
  3935. this.w -= otherVector.w;
  3936. return this;
  3937. };
  3938. /**
  3939. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3940. */
  3941. Vector4.prototype.subtract = function (otherVector) {
  3942. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3943. };
  3944. /**
  3945. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3946. * Returns the current Vector4.
  3947. */
  3948. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3949. result.x = this.x - otherVector.x;
  3950. result.y = this.y - otherVector.y;
  3951. result.z = this.z - otherVector.z;
  3952. result.w = this.w - otherVector.w;
  3953. return this;
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3957. */
  3958. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3959. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3960. };
  3961. /**
  3962. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3963. * Returns the current Vector4.
  3964. */
  3965. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3966. result.x = this.x - x;
  3967. result.y = this.y - y;
  3968. result.z = this.z - z;
  3969. result.w = this.w - w;
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3974. */
  3975. Vector4.prototype.negate = function () {
  3976. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3977. };
  3978. /**
  3979. * Multiplies the current Vector4 coordinates by scale (float).
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.scaleInPlace = function (scale) {
  3983. this.x *= scale;
  3984. this.y *= scale;
  3985. this.z *= scale;
  3986. this.w *= scale;
  3987. return this;
  3988. };
  3989. /**
  3990. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3991. */
  3992. Vector4.prototype.scale = function (scale) {
  3993. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3994. };
  3995. /**
  3996. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3997. * Returns the current Vector4.
  3998. */
  3999. Vector4.prototype.scaleToRef = function (scale, result) {
  4000. result.x = this.x * scale;
  4001. result.y = this.y * scale;
  4002. result.z = this.z * scale;
  4003. result.w = this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4008. * @param scale defines the scale factor
  4009. * @param result defines the Vector4 object where to store the result
  4010. * @returns the unmodified current Vector4
  4011. */
  4012. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4013. result.x += this.x * scale;
  4014. result.y += this.y * scale;
  4015. result.z += this.z * scale;
  4016. result.w += this.w * scale;
  4017. return this;
  4018. };
  4019. /**
  4020. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4021. */
  4022. Vector4.prototype.equals = function (otherVector) {
  4023. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4024. };
  4025. /**
  4026. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4027. */
  4028. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4029. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4030. return otherVector
  4031. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4032. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4033. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4034. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4035. };
  4036. /**
  4037. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4038. */
  4039. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4040. return this.x === x && this.y === y && this.z === z && this.w === w;
  4041. };
  4042. /**
  4043. * Multiplies in place the current Vector4 by the given one.
  4044. * Returns the updated Vector4.
  4045. */
  4046. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4047. this.x *= otherVector.x;
  4048. this.y *= otherVector.y;
  4049. this.z *= otherVector.z;
  4050. this.w *= otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4055. */
  4056. Vector4.prototype.multiply = function (otherVector) {
  4057. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4058. };
  4059. /**
  4060. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4061. * Returns the current Vector4.
  4062. */
  4063. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4064. result.x = this.x * otherVector.x;
  4065. result.y = this.y * otherVector.y;
  4066. result.z = this.z * otherVector.z;
  4067. result.w = this.w * otherVector.w;
  4068. return this;
  4069. };
  4070. /**
  4071. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4072. */
  4073. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4074. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4075. };
  4076. /**
  4077. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4078. */
  4079. Vector4.prototype.divide = function (otherVector) {
  4080. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4081. };
  4082. /**
  4083. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4084. * Returns the current Vector4.
  4085. */
  4086. Vector4.prototype.divideToRef = function (otherVector, result) {
  4087. result.x = this.x / otherVector.x;
  4088. result.y = this.y / otherVector.y;
  4089. result.z = this.z / otherVector.z;
  4090. result.w = this.w / otherVector.w;
  4091. return this;
  4092. };
  4093. /**
  4094. * Divides the current Vector3 coordinates by the given ones.
  4095. * @returns the updated Vector3.
  4096. */
  4097. Vector4.prototype.divideInPlace = function (otherVector) {
  4098. return this.divideToRef(otherVector, this);
  4099. };
  4100. /**
  4101. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4102. * @param other defines the second operand
  4103. * @returns the current updated Vector4
  4104. */
  4105. Vector4.prototype.minimizeInPlace = function (other) {
  4106. if (other.x < this.x)
  4107. this.x = other.x;
  4108. if (other.y < this.y)
  4109. this.y = other.y;
  4110. if (other.z < this.z)
  4111. this.z = other.z;
  4112. if (other.w < this.w)
  4113. this.w = other.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4118. * @param other defines the second operand
  4119. * @returns the current updated Vector4
  4120. */
  4121. Vector4.prototype.maximizeInPlace = function (other) {
  4122. if (other.x > this.x)
  4123. this.x = other.x;
  4124. if (other.y > this.y)
  4125. this.y = other.y;
  4126. if (other.z > this.z)
  4127. this.z = other.z;
  4128. if (other.w > this.w)
  4129. this.w = other.w;
  4130. return this;
  4131. };
  4132. /**
  4133. * Gets a new Vector4 from current Vector4 floored values
  4134. * @returns a new Vector4
  4135. */
  4136. Vector4.prototype.floor = function () {
  4137. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4138. };
  4139. /**
  4140. * Gets a new Vector4 from current Vector3 floored values
  4141. * @returns a new Vector4
  4142. */
  4143. Vector4.prototype.fract = function () {
  4144. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4145. };
  4146. // Properties
  4147. /**
  4148. * Returns the Vector4 length (float).
  4149. */
  4150. Vector4.prototype.length = function () {
  4151. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4152. };
  4153. /**
  4154. * Returns the Vector4 squared length (float).
  4155. */
  4156. Vector4.prototype.lengthSquared = function () {
  4157. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4158. };
  4159. // Methods
  4160. /**
  4161. * Normalizes in place the Vector4.
  4162. * Returns the updated Vector4.
  4163. */
  4164. Vector4.prototype.normalize = function () {
  4165. var len = this.length();
  4166. if (len === 0)
  4167. return this;
  4168. var num = 1.0 / len;
  4169. this.x *= num;
  4170. this.y *= num;
  4171. this.z *= num;
  4172. this.w *= num;
  4173. return this;
  4174. };
  4175. /**
  4176. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4177. */
  4178. Vector4.prototype.toVector3 = function () {
  4179. return new Vector3(this.x, this.y, this.z);
  4180. };
  4181. /**
  4182. * Returns a new Vector4 copied from the current one.
  4183. */
  4184. Vector4.prototype.clone = function () {
  4185. return new Vector4(this.x, this.y, this.z, this.w);
  4186. };
  4187. /**
  4188. * Updates the current Vector4 with the given one coordinates.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFrom = function (source) {
  4192. this.x = source.x;
  4193. this.y = source.y;
  4194. this.z = source.z;
  4195. this.w = source.w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4203. this.x = x;
  4204. this.y = y;
  4205. this.z = z;
  4206. this.w = w;
  4207. return this;
  4208. };
  4209. /**
  4210. * Updates the current Vector4 coordinates with the given floats.
  4211. * Returns the updated Vector4.
  4212. */
  4213. Vector4.prototype.set = function (x, y, z, w) {
  4214. return this.copyFromFloats(x, y, z, w);
  4215. };
  4216. // Statics
  4217. /**
  4218. * Returns a new Vector4 set from the starting index of the given array.
  4219. */
  4220. Vector4.FromArray = function (array, offset) {
  4221. if (!offset) {
  4222. offset = 0;
  4223. }
  4224. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4225. };
  4226. /**
  4227. * Updates the given vector "result" from the starting index of the given array.
  4228. */
  4229. Vector4.FromArrayToRef = function (array, offset, result) {
  4230. result.x = array[offset];
  4231. result.y = array[offset + 1];
  4232. result.z = array[offset + 2];
  4233. result.w = array[offset + 3];
  4234. };
  4235. /**
  4236. * Updates the given vector "result" from the starting index of the given Float32Array.
  4237. */
  4238. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4239. Vector4.FromArrayToRef(array, offset, result);
  4240. };
  4241. /**
  4242. * Updates the given vector "result" coordinates from the given floats.
  4243. */
  4244. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4245. result.x = x;
  4246. result.y = y;
  4247. result.z = z;
  4248. result.w = w;
  4249. };
  4250. /**
  4251. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4252. */
  4253. Vector4.Zero = function () {
  4254. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4255. };
  4256. /**
  4257. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4258. */
  4259. Vector4.One = function () {
  4260. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4261. };
  4262. /**
  4263. * Returns a new normalized Vector4 from the given one.
  4264. */
  4265. Vector4.Normalize = function (vector) {
  4266. var result = Vector4.Zero();
  4267. Vector4.NormalizeToRef(vector, result);
  4268. return result;
  4269. };
  4270. /**
  4271. * Updates the given vector "result" from the normalization of the given one.
  4272. */
  4273. Vector4.NormalizeToRef = function (vector, result) {
  4274. result.copyFrom(vector);
  4275. result.normalize();
  4276. };
  4277. Vector4.Minimize = function (left, right) {
  4278. var min = left.clone();
  4279. min.minimizeInPlace(right);
  4280. return min;
  4281. };
  4282. Vector4.Maximize = function (left, right) {
  4283. var max = left.clone();
  4284. max.maximizeInPlace(right);
  4285. return max;
  4286. };
  4287. /**
  4288. * Returns the distance (float) between the vectors "value1" and "value2".
  4289. */
  4290. Vector4.Distance = function (value1, value2) {
  4291. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4292. };
  4293. /**
  4294. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4295. */
  4296. Vector4.DistanceSquared = function (value1, value2) {
  4297. var x = value1.x - value2.x;
  4298. var y = value1.y - value2.y;
  4299. var z = value1.z - value2.z;
  4300. var w = value1.w - value2.w;
  4301. return (x * x) + (y * y) + (z * z) + (w * w);
  4302. };
  4303. /**
  4304. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4305. */
  4306. Vector4.Center = function (value1, value2) {
  4307. var center = value1.add(value2);
  4308. center.scaleInPlace(0.5);
  4309. return center;
  4310. };
  4311. /**
  4312. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4313. * This methods computes transformed normalized direction vectors only.
  4314. */
  4315. Vector4.TransformNormal = function (vector, transformation) {
  4316. var result = Vector4.Zero();
  4317. Vector4.TransformNormalToRef(vector, transformation, result);
  4318. return result;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4325. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4326. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4327. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4328. result.x = x;
  4329. result.y = y;
  4330. result.z = z;
  4331. result.w = vector.w;
  4332. };
  4333. /**
  4334. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4335. * This methods computes transformed normalized direction vectors only.
  4336. */
  4337. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4338. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4339. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4340. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4341. result.w = w;
  4342. };
  4343. return Vector4;
  4344. }());
  4345. BABYLON.Vector4 = Vector4;
  4346. var Size = /** @class */ (function () {
  4347. /**
  4348. * Creates a Size object from the given width and height (floats).
  4349. */
  4350. function Size(width, height) {
  4351. this.width = width;
  4352. this.height = height;
  4353. }
  4354. // Returns a string with the Size width and height.
  4355. Size.prototype.toString = function () {
  4356. return "{W: " + this.width + ", H: " + this.height + "}";
  4357. };
  4358. /**
  4359. * Returns the string "Size"
  4360. */
  4361. Size.prototype.getClassName = function () {
  4362. return "Size";
  4363. };
  4364. /**
  4365. * Returns the Size hash code.
  4366. */
  4367. Size.prototype.getHashCode = function () {
  4368. var hash = this.width || 0;
  4369. hash = (hash * 397) ^ (this.height || 0);
  4370. return hash;
  4371. };
  4372. /**
  4373. * Updates the current size from the given one.
  4374. * Returns the updated Size.
  4375. */
  4376. Size.prototype.copyFrom = function (src) {
  4377. this.width = src.width;
  4378. this.height = src.height;
  4379. };
  4380. /**
  4381. * Updates in place the current Size from the given floats.
  4382. * Returns the updated Size.
  4383. */
  4384. Size.prototype.copyFromFloats = function (width, height) {
  4385. this.width = width;
  4386. this.height = height;
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates in place the current Size from the given floats.
  4391. * Returns the updated Size.
  4392. */
  4393. Size.prototype.set = function (width, height) {
  4394. return this.copyFromFloats(width, height);
  4395. };
  4396. /**
  4397. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4398. */
  4399. Size.prototype.multiplyByFloats = function (w, h) {
  4400. return new Size(this.width * w, this.height * h);
  4401. };
  4402. /**
  4403. * Returns a new Size copied from the given one.
  4404. */
  4405. Size.prototype.clone = function () {
  4406. return new Size(this.width, this.height);
  4407. };
  4408. /**
  4409. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4410. */
  4411. Size.prototype.equals = function (other) {
  4412. if (!other) {
  4413. return false;
  4414. }
  4415. return (this.width === other.width) && (this.height === other.height);
  4416. };
  4417. Object.defineProperty(Size.prototype, "surface", {
  4418. /**
  4419. * Returns the surface of the Size : width * height (float).
  4420. */
  4421. get: function () {
  4422. return this.width * this.height;
  4423. },
  4424. enumerable: true,
  4425. configurable: true
  4426. });
  4427. /**
  4428. * Returns a new Size set to (0.0, 0.0)
  4429. */
  4430. Size.Zero = function () {
  4431. return new Size(0.0, 0.0);
  4432. };
  4433. /**
  4434. * Returns a new Size set as the addition result of the current Size and the given one.
  4435. */
  4436. Size.prototype.add = function (otherSize) {
  4437. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4438. return r;
  4439. };
  4440. /**
  4441. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4442. */
  4443. Size.prototype.subtract = function (otherSize) {
  4444. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4445. return r;
  4446. };
  4447. /**
  4448. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4449. */
  4450. Size.Lerp = function (start, end, amount) {
  4451. var w = start.width + ((end.width - start.width) * amount);
  4452. var h = start.height + ((end.height - start.height) * amount);
  4453. return new Size(w, h);
  4454. };
  4455. return Size;
  4456. }());
  4457. BABYLON.Size = Size;
  4458. /**
  4459. * Class used to store quaternion data
  4460. * @see https://en.wikipedia.org/wiki/Quaternion
  4461. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4462. */
  4463. var Quaternion = /** @class */ (function () {
  4464. /**
  4465. * Creates a new Quaternion from the given floats
  4466. * @param x defines the first component (0 by default)
  4467. * @param y defines the second component (0 by default)
  4468. * @param z defines the third component (0 by default)
  4469. * @param w defines the fourth component (1.0 by default)
  4470. */
  4471. function Quaternion(
  4472. /** defines the first component (0 by default) */
  4473. x,
  4474. /** defines the second component (0 by default) */
  4475. y,
  4476. /** defines the third component (0 by default) */
  4477. z,
  4478. /** defines the fourth component (1.0 by default) */
  4479. w) {
  4480. if (x === void 0) { x = 0.0; }
  4481. if (y === void 0) { y = 0.0; }
  4482. if (z === void 0) { z = 0.0; }
  4483. if (w === void 0) { w = 1.0; }
  4484. this.x = x;
  4485. this.y = y;
  4486. this.z = z;
  4487. this.w = w;
  4488. }
  4489. /**
  4490. * Gets a string representation for the current quaternion
  4491. * @returns a string with the Quaternion coordinates
  4492. */
  4493. Quaternion.prototype.toString = function () {
  4494. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4495. };
  4496. /**
  4497. * Gets the class name of the quaternion
  4498. * @returns the string "Quaternion"
  4499. */
  4500. Quaternion.prototype.getClassName = function () {
  4501. return "Quaternion";
  4502. };
  4503. /**
  4504. * Gets a hash code for this quaternion
  4505. * @returns the quaternion hash code
  4506. */
  4507. Quaternion.prototype.getHashCode = function () {
  4508. var hash = this.x || 0;
  4509. hash = (hash * 397) ^ (this.y || 0);
  4510. hash = (hash * 397) ^ (this.z || 0);
  4511. hash = (hash * 397) ^ (this.w || 0);
  4512. return hash;
  4513. };
  4514. /**
  4515. * Copy the quaternion to an array
  4516. * @returns a new array populated with 4 elements from the quaternion coordinates
  4517. */
  4518. Quaternion.prototype.asArray = function () {
  4519. return [this.x, this.y, this.z, this.w];
  4520. };
  4521. /**
  4522. * Check if two quaternions are equals
  4523. * @param otherQuaternion defines the second operand
  4524. * @return true if the current quaternion and the given one coordinates are strictly equals
  4525. */
  4526. Quaternion.prototype.equals = function (otherQuaternion) {
  4527. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4528. };
  4529. /**
  4530. * Clone the current quaternion
  4531. * @returns a new quaternion copied from the current one
  4532. */
  4533. Quaternion.prototype.clone = function () {
  4534. return new Quaternion(this.x, this.y, this.z, this.w);
  4535. };
  4536. /**
  4537. * Copy a quaternion to the current one
  4538. * @param other defines the other quaternion
  4539. * @returns the updated current quaternion
  4540. */
  4541. Quaternion.prototype.copyFrom = function (other) {
  4542. this.x = other.x;
  4543. this.y = other.y;
  4544. this.z = other.z;
  4545. this.w = other.w;
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the given float coordinates
  4550. * @param x defines the x coordinate
  4551. * @param y defines the y coordinate
  4552. * @param z defines the z coordinate
  4553. * @param w defines the w coordinate
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4557. this.x = x;
  4558. this.y = y;
  4559. this.z = z;
  4560. this.w = w;
  4561. return this;
  4562. };
  4563. /**
  4564. * Updates the current quaternion from the given float coordinates
  4565. * @param x defines the x coordinate
  4566. * @param y defines the y coordinate
  4567. * @param z defines the z coordinate
  4568. * @param w defines the w coordinate
  4569. * @returns the updated current quaternion
  4570. */
  4571. Quaternion.prototype.set = function (x, y, z, w) {
  4572. return this.copyFromFloats(x, y, z, w);
  4573. };
  4574. /**
  4575. * Adds two quaternions
  4576. * @param other defines the second operand
  4577. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4578. */
  4579. Quaternion.prototype.add = function (other) {
  4580. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4581. };
  4582. /**
  4583. * Add a quaternion to the current one
  4584. * @param other defines the quaternion to add
  4585. * @returns the current quaternion
  4586. */
  4587. Quaternion.prototype.addInPlace = function (other) {
  4588. this.x += other.x;
  4589. this.y += other.y;
  4590. this.z += other.z;
  4591. this.w += other.w;
  4592. return this;
  4593. };
  4594. /**
  4595. * Subtract two quaternions
  4596. * @param other defines the second operand
  4597. * @returns a new quaternion as the subtraction result of the given one from the current one
  4598. */
  4599. Quaternion.prototype.subtract = function (other) {
  4600. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4601. };
  4602. /**
  4603. * Multiplies the current quaternion by a scale factor
  4604. * @param value defines the scale factor
  4605. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4606. */
  4607. Quaternion.prototype.scale = function (value) {
  4608. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4609. };
  4610. /**
  4611. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4612. * @param scale defines the scale factor
  4613. * @param result defines the Quaternion object where to store the result
  4614. * @returns the unmodified current quaternion
  4615. */
  4616. Quaternion.prototype.scaleToRef = function (scale, result) {
  4617. result.x = this.x * scale;
  4618. result.y = this.y * scale;
  4619. result.z = this.z * scale;
  4620. result.w = this.w * scale;
  4621. return this;
  4622. };
  4623. /**
  4624. * Multiplies in place the current quaternion by a scale factor
  4625. * @param value defines the scale factor
  4626. * @returns the current modified quaternion
  4627. */
  4628. Quaternion.prototype.scaleInPlace = function (value) {
  4629. this.x *= value;
  4630. this.y *= value;
  4631. this.z *= value;
  4632. this.w *= value;
  4633. return this;
  4634. };
  4635. /**
  4636. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4637. * @param scale defines the scale factor
  4638. * @param result defines the Quaternion object where to store the result
  4639. * @returns the unmodified current quaternion
  4640. */
  4641. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4642. result.x += this.x * scale;
  4643. result.y += this.y * scale;
  4644. result.z += this.z * scale;
  4645. result.w += this.w * scale;
  4646. return this;
  4647. };
  4648. /**
  4649. * Multiplies two quaternions
  4650. * @param q1 defines the second operand
  4651. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4652. */
  4653. Quaternion.prototype.multiply = function (q1) {
  4654. var result = new Quaternion(0, 0, 0, 1.0);
  4655. this.multiplyToRef(q1, result);
  4656. return result;
  4657. };
  4658. /**
  4659. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4660. * @param q1 defines the second operand
  4661. * @param result defines the target quaternion
  4662. * @returns the current quaternion
  4663. */
  4664. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4665. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4666. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4667. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4668. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4669. result.copyFromFloats(x, y, z, w);
  4670. return this;
  4671. };
  4672. /**
  4673. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4674. * @param q1 defines the second operand
  4675. * @returns the currentupdated quaternion
  4676. */
  4677. Quaternion.prototype.multiplyInPlace = function (q1) {
  4678. this.multiplyToRef(q1, this);
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4683. * @param ref defines the target quaternion
  4684. * @returns the current quaternion
  4685. */
  4686. Quaternion.prototype.conjugateToRef = function (ref) {
  4687. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4688. return this;
  4689. };
  4690. /**
  4691. * Conjugates in place (1-q) the current quaternion
  4692. * @returns the current updated quaternion
  4693. */
  4694. Quaternion.prototype.conjugateInPlace = function () {
  4695. this.x *= -1;
  4696. this.y *= -1;
  4697. this.z *= -1;
  4698. return this;
  4699. };
  4700. /**
  4701. * Conjugates in place (1-q) the current quaternion
  4702. * @returns a new quaternion
  4703. */
  4704. Quaternion.prototype.conjugate = function () {
  4705. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4706. return result;
  4707. };
  4708. /**
  4709. * Gets length of current quaternion
  4710. * @returns the quaternion length (float)
  4711. */
  4712. Quaternion.prototype.length = function () {
  4713. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4714. };
  4715. /**
  4716. * Normalize in place the current quaternion
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.normalize = function () {
  4720. var length = 1.0 / this.length();
  4721. this.x *= length;
  4722. this.y *= length;
  4723. this.z *= length;
  4724. this.w *= length;
  4725. return this;
  4726. };
  4727. /**
  4728. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4729. * @param order is a reserved parameter and is ignore for now
  4730. * @returns a new Vector3 containing the Euler angles
  4731. */
  4732. Quaternion.prototype.toEulerAngles = function (order) {
  4733. if (order === void 0) { order = "YZX"; }
  4734. var result = Vector3.Zero();
  4735. this.toEulerAnglesToRef(result, order);
  4736. return result;
  4737. };
  4738. /**
  4739. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4740. * @param result defines the vector which will be filled with the Euler angles
  4741. * @param order is a reserved parameter and is ignore for now
  4742. * @returns the current unchanged quaternion
  4743. */
  4744. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4745. if (order === void 0) { order = "YZX"; }
  4746. var qz = this.z;
  4747. var qx = this.x;
  4748. var qy = this.y;
  4749. var qw = this.w;
  4750. var sqw = qw * qw;
  4751. var sqz = qz * qz;
  4752. var sqx = qx * qx;
  4753. var sqy = qy * qy;
  4754. var zAxisY = qy * qz - qx * qw;
  4755. var limit = .4999999;
  4756. if (zAxisY < -limit) {
  4757. result.y = 2 * Math.atan2(qy, qw);
  4758. result.x = Math.PI / 2;
  4759. result.z = 0;
  4760. }
  4761. else if (zAxisY > limit) {
  4762. result.y = 2 * Math.atan2(qy, qw);
  4763. result.x = -Math.PI / 2;
  4764. result.z = 0;
  4765. }
  4766. else {
  4767. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4768. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4769. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4770. }
  4771. return this;
  4772. };
  4773. /**
  4774. * Updates the given rotation matrix with the current quaternion values
  4775. * @param result defines the target matrix
  4776. * @returns the current unchanged quaternion
  4777. */
  4778. Quaternion.prototype.toRotationMatrix = function (result) {
  4779. var xx = this.x * this.x;
  4780. var yy = this.y * this.y;
  4781. var zz = this.z * this.z;
  4782. var xy = this.x * this.y;
  4783. var zw = this.z * this.w;
  4784. var zx = this.z * this.x;
  4785. var yw = this.y * this.w;
  4786. var yz = this.y * this.z;
  4787. var xw = this.x * this.w;
  4788. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4789. result.m[1] = 2.0 * (xy + zw);
  4790. result.m[2] = 2.0 * (zx - yw);
  4791. result.m[3] = 0;
  4792. result.m[4] = 2.0 * (xy - zw);
  4793. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4794. result.m[6] = 2.0 * (yz + xw);
  4795. result.m[7] = 0;
  4796. result.m[8] = 2.0 * (zx + yw);
  4797. result.m[9] = 2.0 * (yz - xw);
  4798. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4799. result.m[11] = 0;
  4800. result.m[12] = 0;
  4801. result.m[13] = 0;
  4802. result.m[14] = 0;
  4803. result.m[15] = 1.0;
  4804. result._markAsUpdated();
  4805. return this;
  4806. };
  4807. /**
  4808. * Updates the current quaternion from the given rotation matrix values
  4809. * @param matrix defines the source matrix
  4810. * @returns the current updated quaternion
  4811. */
  4812. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4813. Quaternion.FromRotationMatrixToRef(matrix, this);
  4814. return this;
  4815. };
  4816. // Statics
  4817. /**
  4818. * Creates a new quaternion from a rotation matrix
  4819. * @param matrix defines the source matrix
  4820. * @returns a new quaternion created from the given rotation matrix values
  4821. */
  4822. Quaternion.FromRotationMatrix = function (matrix) {
  4823. var result = new Quaternion();
  4824. Quaternion.FromRotationMatrixToRef(matrix, result);
  4825. return result;
  4826. };
  4827. /**
  4828. * Updates the given quaternion with the given rotation matrix values
  4829. * @param matrix defines the source matrix
  4830. * @param result defines the target quaternion
  4831. */
  4832. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4833. var data = matrix.m;
  4834. var m11 = data[0], m12 = data[4], m13 = data[8];
  4835. var m21 = data[1], m22 = data[5], m23 = data[9];
  4836. var m31 = data[2], m32 = data[6], m33 = data[10];
  4837. var trace = m11 + m22 + m33;
  4838. var s;
  4839. if (trace > 0) {
  4840. s = 0.5 / Math.sqrt(trace + 1.0);
  4841. result.w = 0.25 / s;
  4842. result.x = (m32 - m23) * s;
  4843. result.y = (m13 - m31) * s;
  4844. result.z = (m21 - m12) * s;
  4845. }
  4846. else if (m11 > m22 && m11 > m33) {
  4847. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4848. result.w = (m32 - m23) / s;
  4849. result.x = 0.25 * s;
  4850. result.y = (m12 + m21) / s;
  4851. result.z = (m13 + m31) / s;
  4852. }
  4853. else if (m22 > m33) {
  4854. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4855. result.w = (m13 - m31) / s;
  4856. result.x = (m12 + m21) / s;
  4857. result.y = 0.25 * s;
  4858. result.z = (m23 + m32) / s;
  4859. }
  4860. else {
  4861. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4862. result.w = (m21 - m12) / s;
  4863. result.x = (m13 + m31) / s;
  4864. result.y = (m23 + m32) / s;
  4865. result.z = 0.25 * s;
  4866. }
  4867. };
  4868. /**
  4869. * Returns the dot product (float) between the quaternions "left" and "right"
  4870. * @param left defines the left operand
  4871. * @param right defines the right operand
  4872. * @returns the dot product
  4873. */
  4874. Quaternion.Dot = function (left, right) {
  4875. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4876. };
  4877. /**
  4878. * Checks if the two quaternions are close to each other
  4879. * @param quat0 defines the first quaternion to check
  4880. * @param quat1 defines the second quaternion to check
  4881. * @returns true if the two quaternions are close to each other
  4882. */
  4883. Quaternion.AreClose = function (quat0, quat1) {
  4884. var dot = Quaternion.Dot(quat0, quat1);
  4885. return dot >= 0;
  4886. };
  4887. /**
  4888. * Creates an empty quaternion
  4889. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4890. */
  4891. Quaternion.Zero = function () {
  4892. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4893. };
  4894. /**
  4895. * Inverse a given quaternion
  4896. * @param q defines the source quaternion
  4897. * @returns a new quaternion as the inverted current quaternion
  4898. */
  4899. Quaternion.Inverse = function (q) {
  4900. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4901. };
  4902. /**
  4903. * Creates an identity quaternion
  4904. * @returns the identity quaternion
  4905. */
  4906. Quaternion.Identity = function () {
  4907. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4908. };
  4909. /**
  4910. * Gets a boolean indicating if the given quaternion is identity
  4911. * @param quaternion defines the quaternion to check
  4912. * @returns true if the quaternion is identity
  4913. */
  4914. Quaternion.IsIdentity = function (quaternion) {
  4915. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4916. };
  4917. /**
  4918. * Creates a quaternion from a rotation around an axis
  4919. * @param axis defines the axis to use
  4920. * @param angle defines the angle to use
  4921. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4922. */
  4923. Quaternion.RotationAxis = function (axis, angle) {
  4924. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4925. };
  4926. /**
  4927. * Creates a rotation around an axis and stores it into the given quaternion
  4928. * @param axis defines the axis to use
  4929. * @param angle defines the angle to use
  4930. * @param result defines the target quaternion
  4931. * @returns the target quaternion
  4932. */
  4933. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4934. var sin = Math.sin(angle / 2);
  4935. axis.normalize();
  4936. result.w = Math.cos(angle / 2);
  4937. result.x = axis.x * sin;
  4938. result.y = axis.y * sin;
  4939. result.z = axis.z * sin;
  4940. return result;
  4941. };
  4942. /**
  4943. * Creates a new quaternion from data stored into an array
  4944. * @param array defines the data source
  4945. * @param offset defines the offset in the source array where the data starts
  4946. * @returns a new quaternion
  4947. */
  4948. Quaternion.FromArray = function (array, offset) {
  4949. if (!offset) {
  4950. offset = 0;
  4951. }
  4952. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4953. };
  4954. /**
  4955. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4956. * @param yaw defines the rotation around Y axis
  4957. * @param pitch defines the rotation around X axis
  4958. * @param roll defines the rotation around Z axis
  4959. * @returns the new quaternion
  4960. */
  4961. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4962. var q = new Quaternion();
  4963. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4964. return q;
  4965. };
  4966. /**
  4967. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4968. * @param yaw defines the rotation around Y axis
  4969. * @param pitch defines the rotation around X axis
  4970. * @param roll defines the rotation around Z axis
  4971. * @param result defines the target quaternion
  4972. */
  4973. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4974. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4975. var halfRoll = roll * 0.5;
  4976. var halfPitch = pitch * 0.5;
  4977. var halfYaw = yaw * 0.5;
  4978. var sinRoll = Math.sin(halfRoll);
  4979. var cosRoll = Math.cos(halfRoll);
  4980. var sinPitch = Math.sin(halfPitch);
  4981. var cosPitch = Math.cos(halfPitch);
  4982. var sinYaw = Math.sin(halfYaw);
  4983. var cosYaw = Math.cos(halfYaw);
  4984. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4985. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4986. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4987. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4988. };
  4989. /**
  4990. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4991. * @param alpha defines the rotation around first axis
  4992. * @param beta defines the rotation around second axis
  4993. * @param gamma defines the rotation around third axis
  4994. * @returns the new quaternion
  4995. */
  4996. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4997. var result = new Quaternion();
  4998. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4999. return result;
  5000. };
  5001. /**
  5002. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5003. * @param alpha defines the rotation around first axis
  5004. * @param beta defines the rotation around second axis
  5005. * @param gamma defines the rotation around third axis
  5006. * @param result defines the target quaternion
  5007. */
  5008. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5009. // Produces a quaternion from Euler angles in the z-x-z orientation
  5010. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5011. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5012. var halfBeta = beta * 0.5;
  5013. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5014. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5016. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. };
  5018. /**
  5019. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5020. * @param axis1 defines the first axis
  5021. * @param axis2 defines the second axis
  5022. * @param axis3 defines the third axis
  5023. * @returns the new quaternion
  5024. */
  5025. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5026. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5027. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5028. return quat;
  5029. };
  5030. /**
  5031. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5032. * @param axis1 defines the first axis
  5033. * @param axis2 defines the second axis
  5034. * @param axis3 defines the third axis
  5035. * @param ref defines the target quaternion
  5036. */
  5037. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5038. var rotMat = MathTmp.Matrix[0];
  5039. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5040. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5041. };
  5042. /**
  5043. * Interpolates between two quaternions
  5044. * @param left defines first quaternion
  5045. * @param right defines second quaternion
  5046. * @param amount defines the gradient to use
  5047. * @returns the new interpolated quaternion
  5048. */
  5049. Quaternion.Slerp = function (left, right, amount) {
  5050. var result = Quaternion.Identity();
  5051. Quaternion.SlerpToRef(left, right, amount, result);
  5052. return result;
  5053. };
  5054. /**
  5055. * Interpolates between two quaternions and stores it into a target quaternion
  5056. * @param left defines first quaternion
  5057. * @param right defines second quaternion
  5058. * @param amount defines the gradient to use
  5059. * @param result defines the target quaternion
  5060. */
  5061. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5062. var num2;
  5063. var num3;
  5064. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5065. var flag = false;
  5066. if (num4 < 0) {
  5067. flag = true;
  5068. num4 = -num4;
  5069. }
  5070. if (num4 > 0.999999) {
  5071. num3 = 1 - amount;
  5072. num2 = flag ? -amount : amount;
  5073. }
  5074. else {
  5075. var num5 = Math.acos(num4);
  5076. var num6 = (1.0 / Math.sin(num5));
  5077. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5078. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5079. }
  5080. result.x = (num3 * left.x) + (num2 * right.x);
  5081. result.y = (num3 * left.y) + (num2 * right.y);
  5082. result.z = (num3 * left.z) + (num2 * right.z);
  5083. result.w = (num3 * left.w) + (num2 * right.w);
  5084. };
  5085. /**
  5086. * Interpolate between two quaternions using Hermite interpolation
  5087. * @param value1 defines first quaternion
  5088. * @param tangent1 defines the incoming tangent
  5089. * @param value2 defines second quaternion
  5090. * @param tangent2 defines the outgoing tangent
  5091. * @param amount defines the target quaternion
  5092. * @returns the new interpolated quaternion
  5093. */
  5094. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5095. var squared = amount * amount;
  5096. var cubed = amount * squared;
  5097. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5098. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5099. var part3 = (cubed - (2.0 * squared)) + amount;
  5100. var part4 = cubed - squared;
  5101. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5102. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5103. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5104. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5105. return new Quaternion(x, y, z, w);
  5106. };
  5107. return Quaternion;
  5108. }());
  5109. BABYLON.Quaternion = Quaternion;
  5110. /**
  5111. * Class used to store matrix data (4x4)
  5112. */
  5113. var Matrix = /** @class */ (function () {
  5114. /**
  5115. * Creates an empty matrix (filled with zeros)
  5116. */
  5117. function Matrix() {
  5118. this._isIdentity = false;
  5119. this._isIdentityDirty = true;
  5120. /**
  5121. * Gets or sets the internal data of the matrix
  5122. */
  5123. this.m = new Float32Array(16);
  5124. this._markAsUpdated();
  5125. }
  5126. /** @hidden */
  5127. Matrix.prototype._markAsUpdated = function () {
  5128. this.updateFlag = Matrix._updateFlagSeed++;
  5129. this._isIdentityDirty = true;
  5130. };
  5131. // Properties
  5132. /**
  5133. * Check if the current matrix is indentity
  5134. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5135. * @returns true is the matrix is the identity matrix
  5136. */
  5137. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5138. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5139. if (this._isIdentityDirty) {
  5140. this._isIdentityDirty = false;
  5141. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5142. this._isIdentity = false;
  5143. }
  5144. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5145. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5146. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5147. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5148. this._isIdentity = false;
  5149. }
  5150. else {
  5151. this._isIdentity = true;
  5152. }
  5153. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5154. this._isIdentity = false;
  5155. }
  5156. }
  5157. return this._isIdentity;
  5158. };
  5159. /**
  5160. * Gets the determinant of the matrix
  5161. * @returns the matrix determinant
  5162. */
  5163. Matrix.prototype.determinant = function () {
  5164. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5165. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5166. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5167. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5168. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5169. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5170. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5171. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5172. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5173. };
  5174. // Methods
  5175. /**
  5176. * Returns the matrix as a Float32Array
  5177. * @returns the matrix underlying array
  5178. */
  5179. Matrix.prototype.toArray = function () {
  5180. return this.m;
  5181. };
  5182. /**
  5183. * Returns the matrix as a Float32Array
  5184. * @returns the matrix underlying array.
  5185. */
  5186. Matrix.prototype.asArray = function () {
  5187. return this.toArray();
  5188. };
  5189. /**
  5190. * Inverts the current matrix in place
  5191. * @returns the current inverted matrix
  5192. */
  5193. Matrix.prototype.invert = function () {
  5194. this.invertToRef(this);
  5195. return this;
  5196. };
  5197. /**
  5198. * Sets all the matrix elements to zero
  5199. * @returns the current matrix
  5200. */
  5201. Matrix.prototype.reset = function () {
  5202. for (var index = 0; index < 16; index++) {
  5203. this.m[index] = 0.0;
  5204. }
  5205. this._markAsUpdated();
  5206. return this;
  5207. };
  5208. /**
  5209. * Adds the current matrix with a second one
  5210. * @param other defines the matrix to add
  5211. * @returns a new matrix as the addition of the current matrix and the given one
  5212. */
  5213. Matrix.prototype.add = function (other) {
  5214. var result = new Matrix();
  5215. this.addToRef(other, result);
  5216. return result;
  5217. };
  5218. /**
  5219. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5220. * @param other defines the matrix to add
  5221. * @param result defines the target matrix
  5222. * @returns the current matrix
  5223. */
  5224. Matrix.prototype.addToRef = function (other, result) {
  5225. for (var index = 0; index < 16; index++) {
  5226. result.m[index] = this.m[index] + other.m[index];
  5227. }
  5228. result._markAsUpdated();
  5229. return this;
  5230. };
  5231. /**
  5232. * Adds in place the given matrix to the current matrix
  5233. * @param other defines the second operand
  5234. * @returns the current updated matrix
  5235. */
  5236. Matrix.prototype.addToSelf = function (other) {
  5237. for (var index = 0; index < 16; index++) {
  5238. this.m[index] += other.m[index];
  5239. }
  5240. this._markAsUpdated();
  5241. return this;
  5242. };
  5243. /**
  5244. * Sets the given matrix to the current inverted Matrix
  5245. * @param other defines the target matrix
  5246. * @returns the unmodified current matrix
  5247. */
  5248. Matrix.prototype.invertToRef = function (other) {
  5249. var l1 = this.m[0];
  5250. var l2 = this.m[1];
  5251. var l3 = this.m[2];
  5252. var l4 = this.m[3];
  5253. var l5 = this.m[4];
  5254. var l6 = this.m[5];
  5255. var l7 = this.m[6];
  5256. var l8 = this.m[7];
  5257. var l9 = this.m[8];
  5258. var l10 = this.m[9];
  5259. var l11 = this.m[10];
  5260. var l12 = this.m[11];
  5261. var l13 = this.m[12];
  5262. var l14 = this.m[13];
  5263. var l15 = this.m[14];
  5264. var l16 = this.m[15];
  5265. var l17 = (l11 * l16) - (l12 * l15);
  5266. var l18 = (l10 * l16) - (l12 * l14);
  5267. var l19 = (l10 * l15) - (l11 * l14);
  5268. var l20 = (l9 * l16) - (l12 * l13);
  5269. var l21 = (l9 * l15) - (l11 * l13);
  5270. var l22 = (l9 * l14) - (l10 * l13);
  5271. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5272. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5273. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5274. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5275. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5276. var l28 = (l7 * l16) - (l8 * l15);
  5277. var l29 = (l6 * l16) - (l8 * l14);
  5278. var l30 = (l6 * l15) - (l7 * l14);
  5279. var l31 = (l5 * l16) - (l8 * l13);
  5280. var l32 = (l5 * l15) - (l7 * l13);
  5281. var l33 = (l5 * l14) - (l6 * l13);
  5282. var l34 = (l7 * l12) - (l8 * l11);
  5283. var l35 = (l6 * l12) - (l8 * l10);
  5284. var l36 = (l6 * l11) - (l7 * l10);
  5285. var l37 = (l5 * l12) - (l8 * l9);
  5286. var l38 = (l5 * l11) - (l7 * l9);
  5287. var l39 = (l5 * l10) - (l6 * l9);
  5288. other.m[0] = l23 * l27;
  5289. other.m[4] = l24 * l27;
  5290. other.m[8] = l25 * l27;
  5291. other.m[12] = l26 * l27;
  5292. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5293. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5294. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5295. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5296. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5297. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5298. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5299. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5300. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5301. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5302. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5303. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5304. other._markAsUpdated();
  5305. return this;
  5306. };
  5307. /**
  5308. * Inserts the translation vector (using 3 floats) in the current matrix
  5309. * @param x defines the 1st component of the translation
  5310. * @param y defines the 2nd component of the translation
  5311. * @param z defines the 3rd component of the translation
  5312. * @returns the current updated matrix
  5313. */
  5314. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5315. this.m[12] = x;
  5316. this.m[13] = y;
  5317. this.m[14] = z;
  5318. this._markAsUpdated();
  5319. return this;
  5320. };
  5321. /**
  5322. * Inserts the translation vector in the current matrix
  5323. * @param vector3 defines the translation to insert
  5324. * @returns the current updated matrix
  5325. */
  5326. Matrix.prototype.setTranslation = function (vector3) {
  5327. this.m[12] = vector3.x;
  5328. this.m[13] = vector3.y;
  5329. this.m[14] = vector3.z;
  5330. this._markAsUpdated();
  5331. return this;
  5332. };
  5333. /**
  5334. * Gets the translation value of the current matrix
  5335. * @returns a new Vector3 as the extracted translation from the matrix
  5336. */
  5337. Matrix.prototype.getTranslation = function () {
  5338. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5339. };
  5340. /**
  5341. * Fill a Vector3 with the extracted translation from the matrix
  5342. * @param result defines the Vector3 where to store the translation
  5343. * @returns the current matrix
  5344. */
  5345. Matrix.prototype.getTranslationToRef = function (result) {
  5346. result.x = this.m[12];
  5347. result.y = this.m[13];
  5348. result.z = this.m[14];
  5349. return this;
  5350. };
  5351. /**
  5352. * Remove rotation and scaling part from the matrix
  5353. * @returns the updated matrix
  5354. */
  5355. Matrix.prototype.removeRotationAndScaling = function () {
  5356. this.setRowFromFloats(0, 1, 0, 0, 0);
  5357. this.setRowFromFloats(1, 0, 1, 0, 0);
  5358. this.setRowFromFloats(2, 0, 0, 1, 0);
  5359. return this;
  5360. };
  5361. /**
  5362. * Multiply two matrices
  5363. * @param other defines the second operand
  5364. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5365. */
  5366. Matrix.prototype.multiply = function (other) {
  5367. var result = new Matrix();
  5368. this.multiplyToRef(other, result);
  5369. return result;
  5370. };
  5371. /**
  5372. * Copy the current matrix from the given one
  5373. * @param other defines the source matrix
  5374. * @returns the current updated matrix
  5375. */
  5376. Matrix.prototype.copyFrom = function (other) {
  5377. for (var index = 0; index < 16; index++) {
  5378. this.m[index] = other.m[index];
  5379. }
  5380. this._markAsUpdated();
  5381. return this;
  5382. };
  5383. /**
  5384. * Populates the given array from the starting index with the current matrix values
  5385. * @param array defines the target array
  5386. * @param offset defines the offset in the target array where to start storing values
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.copyToArray = function (array, offset) {
  5390. if (offset === void 0) { offset = 0; }
  5391. for (var index = 0; index < 16; index++) {
  5392. array[offset + index] = this.m[index];
  5393. }
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the matrix where to store the multiplication
  5400. * @returns the current matrix
  5401. */
  5402. Matrix.prototype.multiplyToRef = function (other, result) {
  5403. this.multiplyToArray(other, result.m, 0);
  5404. result._markAsUpdated();
  5405. return this;
  5406. };
  5407. /**
  5408. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5409. * @param other defines the second operand
  5410. * @param result defines the array where to store the multiplication
  5411. * @param offset defines the offset in the target array where to start storing values
  5412. * @returns the current matrix
  5413. */
  5414. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5415. var tm0 = this.m[0];
  5416. var tm1 = this.m[1];
  5417. var tm2 = this.m[2];
  5418. var tm3 = this.m[3];
  5419. var tm4 = this.m[4];
  5420. var tm5 = this.m[5];
  5421. var tm6 = this.m[6];
  5422. var tm7 = this.m[7];
  5423. var tm8 = this.m[8];
  5424. var tm9 = this.m[9];
  5425. var tm10 = this.m[10];
  5426. var tm11 = this.m[11];
  5427. var tm12 = this.m[12];
  5428. var tm13 = this.m[13];
  5429. var tm14 = this.m[14];
  5430. var tm15 = this.m[15];
  5431. var om0 = other.m[0];
  5432. var om1 = other.m[1];
  5433. var om2 = other.m[2];
  5434. var om3 = other.m[3];
  5435. var om4 = other.m[4];
  5436. var om5 = other.m[5];
  5437. var om6 = other.m[6];
  5438. var om7 = other.m[7];
  5439. var om8 = other.m[8];
  5440. var om9 = other.m[9];
  5441. var om10 = other.m[10];
  5442. var om11 = other.m[11];
  5443. var om12 = other.m[12];
  5444. var om13 = other.m[13];
  5445. var om14 = other.m[14];
  5446. var om15 = other.m[15];
  5447. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5448. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5449. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5450. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5451. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5452. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5453. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5454. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5455. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5456. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5457. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5458. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5459. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5460. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5461. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5462. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5463. return this;
  5464. };
  5465. /**
  5466. * Check equality between this matrix and a second one
  5467. * @param value defines the second matrix to compare
  5468. * @returns true is the current matrix and the given one values are strictly equal
  5469. */
  5470. Matrix.prototype.equals = function (value) {
  5471. return value &&
  5472. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5473. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5474. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5475. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5476. };
  5477. /**
  5478. * Clone the current matrix
  5479. * @returns a new matrix from the current matrix
  5480. */
  5481. Matrix.prototype.clone = function () {
  5482. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5483. };
  5484. /**
  5485. * Returns the name of the current matrix class
  5486. * @returns the string "Matrix"
  5487. */
  5488. Matrix.prototype.getClassName = function () {
  5489. return "Matrix";
  5490. };
  5491. /**
  5492. * Gets the hash code of the current matrix
  5493. * @returns the hash code
  5494. */
  5495. Matrix.prototype.getHashCode = function () {
  5496. var hash = this.m[0] || 0;
  5497. for (var i = 1; i < 16; i++) {
  5498. hash = (hash * 397) ^ (this.m[i] || 0);
  5499. }
  5500. return hash;
  5501. };
  5502. /**
  5503. * Decomposes the current Matrix into a translation, rotation and scaling components
  5504. * @param scale defines the scale vector3 given as a reference to update
  5505. * @param rotation defines the rotation quaternion given as a reference to update
  5506. * @param translation defines the translation vector3 given as a reference to update
  5507. * @returns true if operation was successful
  5508. */
  5509. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5510. if (translation) {
  5511. translation.x = this.m[12];
  5512. translation.y = this.m[13];
  5513. translation.z = this.m[14];
  5514. }
  5515. scale = scale || MathTmp.Vector3[0];
  5516. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5517. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5518. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5519. if (this.determinant() <= 0) {
  5520. scale.y *= -1;
  5521. }
  5522. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5523. if (rotation) {
  5524. rotation.x = 0;
  5525. rotation.y = 0;
  5526. rotation.z = 0;
  5527. rotation.w = 1;
  5528. }
  5529. return false;
  5530. }
  5531. if (rotation) {
  5532. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5533. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5534. }
  5535. return true;
  5536. };
  5537. /**
  5538. * Gets specific row of the matrix
  5539. * @param index defines the number of the row to get
  5540. * @returns the index-th row of the current matrix as a new Vector4
  5541. */
  5542. Matrix.prototype.getRow = function (index) {
  5543. if (index < 0 || index > 3) {
  5544. return null;
  5545. }
  5546. var i = index * 4;
  5547. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5548. };
  5549. /**
  5550. * Sets the index-th row of the current matrix to the vector4 values
  5551. * @param index defines the number of the row to set
  5552. * @param row defines the target vector4
  5553. * @returns the updated current matrix
  5554. */
  5555. Matrix.prototype.setRow = function (index, row) {
  5556. if (index < 0 || index > 3) {
  5557. return this;
  5558. }
  5559. var i = index * 4;
  5560. this.m[i + 0] = row.x;
  5561. this.m[i + 1] = row.y;
  5562. this.m[i + 2] = row.z;
  5563. this.m[i + 3] = row.w;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Compute the transpose of the matrix
  5569. * @returns the new transposed matrix
  5570. */
  5571. Matrix.prototype.transpose = function () {
  5572. return Matrix.Transpose(this);
  5573. };
  5574. /**
  5575. * Compute the transpose of the matrix and store it in a given matrix
  5576. * @param result defines the target matrix
  5577. * @returns the current matrix
  5578. */
  5579. Matrix.prototype.transposeToRef = function (result) {
  5580. Matrix.TransposeToRef(this, result);
  5581. return this;
  5582. };
  5583. /**
  5584. * Sets the index-th row of the current matrix with the given 4 x float values
  5585. * @param index defines the row index
  5586. * @param x defines the x component to set
  5587. * @param y defines the y component to set
  5588. * @param z defines the z component to set
  5589. * @param w defines the w component to set
  5590. * @returns the updated current matrix
  5591. */
  5592. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5593. if (index < 0 || index > 3) {
  5594. return this;
  5595. }
  5596. var i = index * 4;
  5597. this.m[i + 0] = x;
  5598. this.m[i + 1] = y;
  5599. this.m[i + 2] = z;
  5600. this.m[i + 3] = w;
  5601. this._markAsUpdated();
  5602. return this;
  5603. };
  5604. /**
  5605. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5606. * @param scale defines the scale factor
  5607. * @returns a new matrix
  5608. */
  5609. Matrix.prototype.scale = function (scale) {
  5610. var result = new Matrix();
  5611. this.scaleToRef(scale, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor to a given result matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Scale the current matrix values by a factor and add the result to a given matrix
  5629. * @param scale defines the scale factor
  5630. * @param result defines the Matrix to store the result
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] += this.m[index] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. return this;
  5639. };
  5640. /**
  5641. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5642. * @param ref matrix to store the result
  5643. */
  5644. Matrix.prototype.toNormalMatrix = function (ref) {
  5645. this.invertToRef(ref);
  5646. ref.transpose();
  5647. var m = ref.m;
  5648. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5649. };
  5650. /**
  5651. * Gets only rotation part of the current matrix
  5652. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5653. */
  5654. Matrix.prototype.getRotationMatrix = function () {
  5655. var result = Matrix.Identity();
  5656. this.getRotationMatrixToRef(result);
  5657. return result;
  5658. };
  5659. /**
  5660. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5661. * @param result defines the target matrix to store data to
  5662. * @returns the current matrix
  5663. */
  5664. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5665. var m = this.m;
  5666. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5667. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5668. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5669. if (this.determinant() <= 0) {
  5670. sy *= -1;
  5671. }
  5672. if (sx === 0 || sy === 0 || sz === 0) {
  5673. Matrix.IdentityToRef(result);
  5674. }
  5675. else {
  5676. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5677. }
  5678. return this;
  5679. };
  5680. // Statics
  5681. /**
  5682. * Creates a matrix from an array
  5683. * @param array defines the source array
  5684. * @param offset defines an offset in the source array
  5685. * @returns a new Matrix set from the starting index of the given array
  5686. */
  5687. Matrix.FromArray = function (array, offset) {
  5688. var result = new Matrix();
  5689. if (!offset) {
  5690. offset = 0;
  5691. }
  5692. Matrix.FromArrayToRef(array, offset, result);
  5693. return result;
  5694. };
  5695. /**
  5696. * Copy the content of an array into a given matrix
  5697. * @param array defines the source array
  5698. * @param offset defines an offset in the source array
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromArrayToRef = function (array, offset, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset];
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores an array into a matrix after having multiplied each component by a given factor
  5709. * @param array defines the source array
  5710. * @param offset defines the offset in the source array
  5711. * @param scale defines the scaling factor
  5712. * @param result defines the target matrix
  5713. */
  5714. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5715. for (var index = 0; index < 16; index++) {
  5716. result.m[index] = array[index + offset] * scale;
  5717. }
  5718. result._markAsUpdated();
  5719. };
  5720. /**
  5721. * Stores a list of values (16) inside a given matrix
  5722. * @param initialM11 defines 1st value of 1st row
  5723. * @param initialM12 defines 2nd value of 1st row
  5724. * @param initialM13 defines 3rd value of 1st row
  5725. * @param initialM14 defines 4th value of 1st row
  5726. * @param initialM21 defines 1st value of 2nd row
  5727. * @param initialM22 defines 2nd value of 2nd row
  5728. * @param initialM23 defines 3rd value of 2nd row
  5729. * @param initialM24 defines 4th value of 2nd row
  5730. * @param initialM31 defines 1st value of 3rd row
  5731. * @param initialM32 defines 2nd value of 3rd row
  5732. * @param initialM33 defines 3rd value of 3rd row
  5733. * @param initialM34 defines 4th value of 3rd row
  5734. * @param initialM41 defines 1st value of 4th row
  5735. * @param initialM42 defines 2nd value of 4th row
  5736. * @param initialM43 defines 3rd value of 4th row
  5737. * @param initialM44 defines 4th value of 4th row
  5738. * @param result defines the target matrix
  5739. */
  5740. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5741. result.m[0] = initialM11;
  5742. result.m[1] = initialM12;
  5743. result.m[2] = initialM13;
  5744. result.m[3] = initialM14;
  5745. result.m[4] = initialM21;
  5746. result.m[5] = initialM22;
  5747. result.m[6] = initialM23;
  5748. result.m[7] = initialM24;
  5749. result.m[8] = initialM31;
  5750. result.m[9] = initialM32;
  5751. result.m[10] = initialM33;
  5752. result.m[11] = initialM34;
  5753. result.m[12] = initialM41;
  5754. result.m[13] = initialM42;
  5755. result.m[14] = initialM43;
  5756. result.m[15] = initialM44;
  5757. result._markAsUpdated();
  5758. };
  5759. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5760. /**
  5761. * Gets an identity matrix that must not be updated
  5762. */
  5763. get: function () {
  5764. return Matrix._identityReadOnly;
  5765. },
  5766. enumerable: true,
  5767. configurable: true
  5768. });
  5769. /**
  5770. * Creates new matrix from a list of values (16)
  5771. * @param initialM11 defines 1st value of 1st row
  5772. * @param initialM12 defines 2nd value of 1st row
  5773. * @param initialM13 defines 3rd value of 1st row
  5774. * @param initialM14 defines 4th value of 1st row
  5775. * @param initialM21 defines 1st value of 2nd row
  5776. * @param initialM22 defines 2nd value of 2nd row
  5777. * @param initialM23 defines 3rd value of 2nd row
  5778. * @param initialM24 defines 4th value of 2nd row
  5779. * @param initialM31 defines 1st value of 3rd row
  5780. * @param initialM32 defines 2nd value of 3rd row
  5781. * @param initialM33 defines 3rd value of 3rd row
  5782. * @param initialM34 defines 4th value of 3rd row
  5783. * @param initialM41 defines 1st value of 4th row
  5784. * @param initialM42 defines 2nd value of 4th row
  5785. * @param initialM43 defines 3rd value of 4th row
  5786. * @param initialM44 defines 4th value of 4th row
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5790. var result = new Matrix();
  5791. result.m[0] = initialM11;
  5792. result.m[1] = initialM12;
  5793. result.m[2] = initialM13;
  5794. result.m[3] = initialM14;
  5795. result.m[4] = initialM21;
  5796. result.m[5] = initialM22;
  5797. result.m[6] = initialM23;
  5798. result.m[7] = initialM24;
  5799. result.m[8] = initialM31;
  5800. result.m[9] = initialM32;
  5801. result.m[10] = initialM33;
  5802. result.m[11] = initialM34;
  5803. result.m[12] = initialM41;
  5804. result.m[13] = initialM42;
  5805. result.m[14] = initialM43;
  5806. result.m[15] = initialM44;
  5807. return result;
  5808. };
  5809. /**
  5810. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5811. * @param scale defines the scale vector3
  5812. * @param rotation defines the rotation quaternion
  5813. * @param translation defines the translation vector3
  5814. * @returns a new matrix
  5815. */
  5816. Matrix.Compose = function (scale, rotation, translation) {
  5817. var result = Matrix.Identity();
  5818. Matrix.ComposeToRef(scale, rotation, translation, result);
  5819. return result;
  5820. };
  5821. /**
  5822. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5823. * @param scale defines the scale vector3
  5824. * @param rotation defines the rotation quaternion
  5825. * @param translation defines the translation vector3
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5829. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5830. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5831. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5832. result.setTranslation(translation);
  5833. };
  5834. /**
  5835. * Creates a new identity matrix
  5836. * @returns a new identity matrix
  5837. */
  5838. Matrix.Identity = function () {
  5839. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5840. };
  5841. /**
  5842. * Creates a new identity matrix and stores the result in a given matrix
  5843. * @param result defines the target matrix
  5844. */
  5845. Matrix.IdentityToRef = function (result) {
  5846. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5847. };
  5848. /**
  5849. * Creates a new zero matrix
  5850. * @returns a new zero matrix
  5851. */
  5852. Matrix.Zero = function () {
  5853. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5854. };
  5855. /**
  5856. * Creates a new rotation matrix for "angle" radians around the X axis
  5857. * @param angle defines the angle (in radians) to use
  5858. * @return the new matrix
  5859. */
  5860. Matrix.RotationX = function (angle) {
  5861. var result = new Matrix();
  5862. Matrix.RotationXToRef(angle, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Creates a new matrix as the invert of a given matrix
  5867. * @param source defines the source matrix
  5868. * @returns the new matrix
  5869. */
  5870. Matrix.Invert = function (source) {
  5871. var result = new Matrix();
  5872. source.invertToRef(result);
  5873. return result;
  5874. };
  5875. /**
  5876. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5877. * @param angle defines the angle (in radians) to use
  5878. * @param result defines the target matrix
  5879. */
  5880. Matrix.RotationXToRef = function (angle, result) {
  5881. var s = Math.sin(angle);
  5882. var c = Math.cos(angle);
  5883. result.m[0] = 1.0;
  5884. result.m[15] = 1.0;
  5885. result.m[5] = c;
  5886. result.m[10] = c;
  5887. result.m[9] = -s;
  5888. result.m[6] = s;
  5889. result.m[1] = 0.0;
  5890. result.m[2] = 0.0;
  5891. result.m[3] = 0.0;
  5892. result.m[4] = 0.0;
  5893. result.m[7] = 0.0;
  5894. result.m[8] = 0.0;
  5895. result.m[11] = 0.0;
  5896. result.m[12] = 0.0;
  5897. result.m[13] = 0.0;
  5898. result.m[14] = 0.0;
  5899. result._markAsUpdated();
  5900. };
  5901. /**
  5902. * Creates a new rotation matrix for "angle" radians around the Y axis
  5903. * @param angle defines the angle (in radians) to use
  5904. * @return the new matrix
  5905. */
  5906. Matrix.RotationY = function (angle) {
  5907. var result = new Matrix();
  5908. Matrix.RotationYToRef(angle, result);
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5913. * @param angle defines the angle (in radians) to use
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationYToRef = function (angle, result) {
  5917. var s = Math.sin(angle);
  5918. var c = Math.cos(angle);
  5919. result.m[5] = 1.0;
  5920. result.m[15] = 1.0;
  5921. result.m[0] = c;
  5922. result.m[2] = -s;
  5923. result.m[8] = s;
  5924. result.m[10] = c;
  5925. result.m[1] = 0.0;
  5926. result.m[3] = 0.0;
  5927. result.m[4] = 0.0;
  5928. result.m[6] = 0.0;
  5929. result.m[7] = 0.0;
  5930. result.m[9] = 0.0;
  5931. result.m[11] = 0.0;
  5932. result.m[12] = 0.0;
  5933. result.m[13] = 0.0;
  5934. result.m[14] = 0.0;
  5935. result._markAsUpdated();
  5936. };
  5937. /**
  5938. * Creates a new rotation matrix for "angle" radians around the Z axis
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationZ = function (angle) {
  5943. var result = new Matrix();
  5944. Matrix.RotationZToRef(angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5949. * @param angle defines the angle (in radians) to use
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.RotationZToRef = function (angle, result) {
  5953. var s = Math.sin(angle);
  5954. var c = Math.cos(angle);
  5955. result.m[10] = 1.0;
  5956. result.m[15] = 1.0;
  5957. result.m[0] = c;
  5958. result.m[1] = s;
  5959. result.m[4] = -s;
  5960. result.m[5] = c;
  5961. result.m[2] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[6] = 0.0;
  5964. result.m[7] = 0.0;
  5965. result.m[8] = 0.0;
  5966. result.m[9] = 0.0;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @return the new matrix
  5978. */
  5979. Matrix.RotationAxis = function (axis, angle) {
  5980. var result = Matrix.Zero();
  5981. Matrix.RotationAxisToRef(axis, angle, result);
  5982. return result;
  5983. };
  5984. /**
  5985. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5986. * @param axis defines the axis to use
  5987. * @param angle defines the angle (in radians) to use
  5988. * @param result defines the target matrix
  5989. */
  5990. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5991. var s = Math.sin(-angle);
  5992. var c = Math.cos(-angle);
  5993. var c1 = 1 - c;
  5994. axis.normalize();
  5995. result.m[0] = (axis.x * axis.x) * c1 + c;
  5996. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5997. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5998. result.m[3] = 0.0;
  5999. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6000. result.m[5] = (axis.y * axis.y) * c1 + c;
  6001. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6002. result.m[7] = 0.0;
  6003. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6004. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6005. result.m[10] = (axis.z * axis.z) * c1 + c;
  6006. result.m[11] = 0.0;
  6007. result.m[15] = 1.0;
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Creates a rotation matrix
  6012. * @param yaw defines the yaw angle in radians (Y axis)
  6013. * @param pitch defines the pitch angle in radians (X axis)
  6014. * @param roll defines the roll angle in radians (X axis)
  6015. * @returns the new rotation matrix
  6016. */
  6017. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6018. var result = new Matrix();
  6019. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6020. return result;
  6021. };
  6022. /**
  6023. * Creates a rotation matrix and stores it in a given matrix
  6024. * @param yaw defines the yaw angle in radians (Y axis)
  6025. * @param pitch defines the pitch angle in radians (X axis)
  6026. * @param roll defines the roll angle in radians (X axis)
  6027. * @param result defines the target matrix
  6028. */
  6029. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6030. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6031. this._tempQuaternion.toRotationMatrix(result);
  6032. };
  6033. /**
  6034. * Creates a scaling matrix
  6035. * @param x defines the scale factor on X axis
  6036. * @param y defines the scale factor on Y axis
  6037. * @param z defines the scale factor on Z axis
  6038. * @returns the new matrix
  6039. */
  6040. Matrix.Scaling = function (x, y, z) {
  6041. var result = Matrix.Zero();
  6042. Matrix.ScalingToRef(x, y, z, result);
  6043. return result;
  6044. };
  6045. /**
  6046. * Creates a scaling matrix and stores it in a given matrix
  6047. * @param x defines the scale factor on X axis
  6048. * @param y defines the scale factor on Y axis
  6049. * @param z defines the scale factor on Z axis
  6050. * @param result defines the target matrix
  6051. */
  6052. Matrix.ScalingToRef = function (x, y, z, result) {
  6053. result.m[0] = x;
  6054. result.m[1] = 0.0;
  6055. result.m[2] = 0.0;
  6056. result.m[3] = 0.0;
  6057. result.m[4] = 0.0;
  6058. result.m[5] = y;
  6059. result.m[6] = 0.0;
  6060. result.m[7] = 0.0;
  6061. result.m[8] = 0.0;
  6062. result.m[9] = 0.0;
  6063. result.m[10] = z;
  6064. result.m[11] = 0.0;
  6065. result.m[12] = 0.0;
  6066. result.m[13] = 0.0;
  6067. result.m[14] = 0.0;
  6068. result.m[15] = 1.0;
  6069. result._markAsUpdated();
  6070. };
  6071. /**
  6072. * Creates a translation matrix
  6073. * @param x defines the translation on X axis
  6074. * @param y defines the translation on Y axis
  6075. * @param z defines the translationon Z axis
  6076. * @returns the new matrix
  6077. */
  6078. Matrix.Translation = function (x, y, z) {
  6079. var result = Matrix.Identity();
  6080. Matrix.TranslationToRef(x, y, z, result);
  6081. return result;
  6082. };
  6083. /**
  6084. * Creates a translation matrix and stores it in a given matrix
  6085. * @param x defines the translation on X axis
  6086. * @param y defines the translation on Y axis
  6087. * @param z defines the translationon Z axis
  6088. * @param result defines the target matrix
  6089. */
  6090. Matrix.TranslationToRef = function (x, y, z, result) {
  6091. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6092. };
  6093. /**
  6094. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6095. * @param startValue defines the start value
  6096. * @param endValue defines the end value
  6097. * @param gradient defines the gradient factor
  6098. * @returns the new matrix
  6099. */
  6100. Matrix.Lerp = function (startValue, endValue, gradient) {
  6101. var result = Matrix.Zero();
  6102. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6103. return result;
  6104. };
  6105. /**
  6106. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6107. * @param startValue defines the start value
  6108. * @param endValue defines the end value
  6109. * @param gradient defines the gradient factor
  6110. * @param result defines the Matrix object where to store data
  6111. */
  6112. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6113. for (var index = 0; index < 16; index++) {
  6114. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6115. }
  6116. result._markAsUpdated();
  6117. };
  6118. /**
  6119. * Builds a new matrix whose values are computed by:
  6120. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6121. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6122. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6123. * @param startValue defines the first matrix
  6124. * @param endValue defines the second matrix
  6125. * @param gradient defines the gradient between the two matrices
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6129. var result = Matrix.Zero();
  6130. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * Update a matrix to values which are computed by:
  6135. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6136. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6137. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6138. * @param startValue defines the first matrix
  6139. * @param endValue defines the second matrix
  6140. * @param gradient defines the gradient between the two matrices
  6141. * @param result defines the target matrix
  6142. */
  6143. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6144. var startScale = MathTmp.Vector3[0];
  6145. var startRotation = MathTmp.Quaternion[0];
  6146. var startTranslation = MathTmp.Vector3[1];
  6147. startValue.decompose(startScale, startRotation, startTranslation);
  6148. var endScale = MathTmp.Vector3[2];
  6149. var endRotation = MathTmp.Quaternion[1];
  6150. var endTranslation = MathTmp.Vector3[3];
  6151. endValue.decompose(endScale, endRotation, endTranslation);
  6152. var resultScale = MathTmp.Vector3[4];
  6153. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6154. var resultRotation = MathTmp.Quaternion[2];
  6155. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6156. var resultTranslation = MathTmp.Vector3[5];
  6157. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6158. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6159. };
  6160. /**
  6161. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @returns the new matrix
  6167. */
  6168. Matrix.LookAtLH = function (eye, target, up) {
  6169. var result = Matrix.Zero();
  6170. Matrix.LookAtLHToRef(eye, target, up, result);
  6171. return result;
  6172. };
  6173. /**
  6174. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6175. * This function works in left handed mode
  6176. * @param eye defines the final position of the entity
  6177. * @param target defines where the entity should look at
  6178. * @param up defines the up vector for the entity
  6179. * @param result defines the target matrix
  6180. */
  6181. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6182. // Z axis
  6183. target.subtractToRef(eye, this._zAxis);
  6184. this._zAxis.normalize();
  6185. // X axis
  6186. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6187. if (this._xAxis.lengthSquared() === 0) {
  6188. this._xAxis.x = 1.0;
  6189. }
  6190. else {
  6191. this._xAxis.normalize();
  6192. }
  6193. // Y axis
  6194. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6195. this._yAxis.normalize();
  6196. // Eye angles
  6197. var ex = -Vector3.Dot(this._xAxis, eye);
  6198. var ey = -Vector3.Dot(this._yAxis, eye);
  6199. var ez = -Vector3.Dot(this._zAxis, eye);
  6200. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6201. };
  6202. /**
  6203. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @returns the new matrix
  6209. */
  6210. Matrix.LookAtRH = function (eye, target, up) {
  6211. var result = Matrix.Zero();
  6212. Matrix.LookAtRHToRef(eye, target, up, result);
  6213. return result;
  6214. };
  6215. /**
  6216. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6217. * This function works in right handed mode
  6218. * @param eye defines the final position of the entity
  6219. * @param target defines where the entity should look at
  6220. * @param up defines the up vector for the entity
  6221. * @param result defines the target matrix
  6222. */
  6223. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6224. // Z axis
  6225. eye.subtractToRef(target, this._zAxis);
  6226. this._zAxis.normalize();
  6227. // X axis
  6228. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6229. if (this._xAxis.lengthSquared() === 0) {
  6230. this._xAxis.x = 1.0;
  6231. }
  6232. else {
  6233. this._xAxis.normalize();
  6234. }
  6235. // Y axis
  6236. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6237. this._yAxis.normalize();
  6238. // Eye angles
  6239. var ex = -Vector3.Dot(this._xAxis, eye);
  6240. var ey = -Vector3.Dot(this._yAxis, eye);
  6241. var ez = -Vector3.Dot(this._zAxis, eye);
  6242. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6243. };
  6244. /**
  6245. * Create a left-handed orthographic projection matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @returns a new matrix as a left-handed orthographic projection matrix
  6251. */
  6252. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6253. var matrix = Matrix.Zero();
  6254. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6255. return matrix;
  6256. };
  6257. /**
  6258. * Store a left-handed orthographic projection to a given matrix
  6259. * @param width defines the viewport width
  6260. * @param height defines the viewport height
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @param result defines the target matrix
  6264. */
  6265. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6266. var n = znear;
  6267. var f = zfar;
  6268. var a = 2.0 / width;
  6269. var b = 2.0 / height;
  6270. var c = 2.0 / (f - n);
  6271. var d = -(f + n) / (f - n);
  6272. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6273. };
  6274. /**
  6275. * Create a left-handed orthographic projection matrix
  6276. * @param left defines the viewport left coordinate
  6277. * @param right defines the viewport right coordinate
  6278. * @param bottom defines the viewport bottom coordinate
  6279. * @param top defines the viewport top coordinate
  6280. * @param znear defines the near clip plane
  6281. * @param zfar defines the far clip plane
  6282. * @returns a new matrix as a left-handed orthographic projection matrix
  6283. */
  6284. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6285. var matrix = Matrix.Zero();
  6286. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6287. return matrix;
  6288. };
  6289. /**
  6290. * Stores a left-handed orthographic projection into a given matrix
  6291. * @param left defines the viewport left coordinate
  6292. * @param right defines the viewport right coordinate
  6293. * @param bottom defines the viewport bottom coordinate
  6294. * @param top defines the viewport top coordinate
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @param result defines the target matrix
  6298. */
  6299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6300. var n = znear;
  6301. var f = zfar;
  6302. var a = 2.0 / (right - left);
  6303. var b = 2.0 / (top - bottom);
  6304. var c = 2.0 / (f - n);
  6305. var d = -(f + n) / (f - n);
  6306. var i0 = (left + right) / (left - right);
  6307. var i1 = (top + bottom) / (bottom - top);
  6308. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6309. };
  6310. /**
  6311. * Creates a right-handed orthographic projection matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @returns a new matrix as a right-handed orthographic projection matrix
  6319. */
  6320. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6321. var matrix = Matrix.Zero();
  6322. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6323. return matrix;
  6324. };
  6325. /**
  6326. * Stores a right-handed orthographic projection into a given matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6336. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6337. result.m[10] *= -1.0;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param width defines the viewport width
  6342. * @param height defines the viewport height
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed perspective projection matrix
  6346. */
  6347. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. var n = znear;
  6350. var f = zfar;
  6351. var a = 2.0 * n / width;
  6352. var b = 2.0 * n / height;
  6353. var c = (f + n) / (f - n);
  6354. var d = -2.0 * f * n / (f - n);
  6355. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Creates a left-handed perspective projection matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @returns a new matrix as a left-handed perspective projection matrix
  6365. */
  6366. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6367. var matrix = Matrix.Zero();
  6368. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6369. return matrix;
  6370. };
  6371. /**
  6372. * Stores a left-handed perspective projection into a given matrix
  6373. * @param fov defines the horizontal field of view
  6374. * @param aspect defines the aspect ratio
  6375. * @param znear defines the near clip plane
  6376. * @param zfar defines the far clip plane
  6377. * @param result defines the target matrix
  6378. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6379. */
  6380. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6382. var n = znear;
  6383. var f = zfar;
  6384. var t = 1.0 / (Math.tan(fov * 0.5));
  6385. var a = isVerticalFovFixed ? (t / aspect) : t;
  6386. var b = isVerticalFovFixed ? t : (t * aspect);
  6387. var c = (f + n) / (f - n);
  6388. var d = -2.0 * f * n / (f - n);
  6389. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6390. };
  6391. /**
  6392. * Creates a right-handed perspective projection matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @returns a new matrix as a right-handed perspective projection matrix
  6398. */
  6399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6400. var matrix = Matrix.Zero();
  6401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6402. return matrix;
  6403. };
  6404. /**
  6405. * Stores a right-handed perspective projection into a given matrix
  6406. * @param fov defines the horizontal field of view
  6407. * @param aspect defines the aspect ratio
  6408. * @param znear defines the near clip plane
  6409. * @param zfar defines the far clip plane
  6410. * @param result defines the target matrix
  6411. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6412. */
  6413. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6414. //alternatively this could be expressed as:
  6415. // m = PerspectiveFovLHToRef
  6416. // m[10] *= -1.0;
  6417. // m[11] *= -1.0;
  6418. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6419. var n = znear;
  6420. var f = zfar;
  6421. var t = 1.0 / (Math.tan(fov * 0.5));
  6422. var a = isVerticalFovFixed ? (t / aspect) : t;
  6423. var b = isVerticalFovFixed ? t : (t * aspect);
  6424. var c = -(f + n) / (f - n);
  6425. var d = -2 * f * n / (f - n);
  6426. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6427. };
  6428. /**
  6429. * Stores a perspective projection for WebVR info a given matrix
  6430. * @param fov defines the field of view
  6431. * @param znear defines the near clip plane
  6432. * @param zfar defines the far clip plane
  6433. * @param result defines the target matrix
  6434. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6435. */
  6436. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6437. if (rightHanded === void 0) { rightHanded = false; }
  6438. var rightHandedFactor = rightHanded ? -1 : 1;
  6439. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6440. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6441. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6442. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6443. var xScale = 2.0 / (leftTan + rightTan);
  6444. var yScale = 2.0 / (upTan + downTan);
  6445. result.m[0] = xScale;
  6446. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6447. result.m[5] = yScale;
  6448. result.m[6] = result.m[7] = 0.0;
  6449. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6450. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6451. result.m[10] = -zfar / (znear - zfar);
  6452. result.m[11] = 1.0 * rightHandedFactor;
  6453. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6454. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6455. result._markAsUpdated();
  6456. };
  6457. /**
  6458. * Computes a complete transformation matrix
  6459. * @param viewport defines the viewport to use
  6460. * @param world defines the world matrix
  6461. * @param view defines the view matrix
  6462. * @param projection defines the projection matrix
  6463. * @param zmin defines the near clip plane
  6464. * @param zmax defines the far clip plane
  6465. * @returns the transformation matrix
  6466. */
  6467. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6468. var cw = viewport.width;
  6469. var ch = viewport.height;
  6470. var cx = viewport.x;
  6471. var cy = viewport.y;
  6472. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6473. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6474. };
  6475. /**
  6476. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix2x2 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1],
  6483. matrix.m[4], matrix.m[5]
  6484. ]);
  6485. };
  6486. /**
  6487. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6488. * @param matrix defines the matrix to use
  6489. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6490. */
  6491. Matrix.GetAsMatrix3x3 = function (matrix) {
  6492. return new Float32Array([
  6493. matrix.m[0], matrix.m[1], matrix.m[2],
  6494. matrix.m[4], matrix.m[5], matrix.m[6],
  6495. matrix.m[8], matrix.m[9], matrix.m[10]
  6496. ]);
  6497. };
  6498. /**
  6499. * Compute the transpose of a given matrix
  6500. * @param matrix defines the matrix to transpose
  6501. * @returns the new matrix
  6502. */
  6503. Matrix.Transpose = function (matrix) {
  6504. var result = new Matrix();
  6505. Matrix.TransposeToRef(matrix, result);
  6506. return result;
  6507. };
  6508. /**
  6509. * Compute the transpose of a matrix and store it in a target matrix
  6510. * @param matrix defines the matrix to transpose
  6511. * @param result defines the target matrix
  6512. */
  6513. Matrix.TransposeToRef = function (matrix, result) {
  6514. result.m[0] = matrix.m[0];
  6515. result.m[1] = matrix.m[4];
  6516. result.m[2] = matrix.m[8];
  6517. result.m[3] = matrix.m[12];
  6518. result.m[4] = matrix.m[1];
  6519. result.m[5] = matrix.m[5];
  6520. result.m[6] = matrix.m[9];
  6521. result.m[7] = matrix.m[13];
  6522. result.m[8] = matrix.m[2];
  6523. result.m[9] = matrix.m[6];
  6524. result.m[10] = matrix.m[10];
  6525. result.m[11] = matrix.m[14];
  6526. result.m[12] = matrix.m[3];
  6527. result.m[13] = matrix.m[7];
  6528. result.m[14] = matrix.m[11];
  6529. result.m[15] = matrix.m[15];
  6530. };
  6531. /**
  6532. * Computes a reflection matrix from a plane
  6533. * @param plane defines the reflection plane
  6534. * @returns a new matrix
  6535. */
  6536. Matrix.Reflection = function (plane) {
  6537. var matrix = new Matrix();
  6538. Matrix.ReflectionToRef(plane, matrix);
  6539. return matrix;
  6540. };
  6541. /**
  6542. * Computes a reflection matrix from a plane
  6543. * @param plane defines the reflection plane
  6544. * @param result defines the target matrix
  6545. */
  6546. Matrix.ReflectionToRef = function (plane, result) {
  6547. plane.normalize();
  6548. var x = plane.normal.x;
  6549. var y = plane.normal.y;
  6550. var z = plane.normal.z;
  6551. var temp = -2 * x;
  6552. var temp2 = -2 * y;
  6553. var temp3 = -2 * z;
  6554. result.m[0] = (temp * x) + 1;
  6555. result.m[1] = temp2 * x;
  6556. result.m[2] = temp3 * x;
  6557. result.m[3] = 0.0;
  6558. result.m[4] = temp * y;
  6559. result.m[5] = (temp2 * y) + 1;
  6560. result.m[6] = temp3 * y;
  6561. result.m[7] = 0.0;
  6562. result.m[8] = temp * z;
  6563. result.m[9] = temp2 * z;
  6564. result.m[10] = (temp3 * z) + 1;
  6565. result.m[11] = 0.0;
  6566. result.m[12] = temp * plane.d;
  6567. result.m[13] = temp2 * plane.d;
  6568. result.m[14] = temp3 * plane.d;
  6569. result.m[15] = 1.0;
  6570. result._markAsUpdated();
  6571. };
  6572. /**
  6573. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6574. * @param xaxis defines the value of the 1st axis
  6575. * @param yaxis defines the value of the 2nd axis
  6576. * @param zaxis defines the value of the 3rd axis
  6577. * @param result defines the target matrix
  6578. */
  6579. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6580. result.m[0] = xaxis.x;
  6581. result.m[1] = xaxis.y;
  6582. result.m[2] = xaxis.z;
  6583. result.m[3] = 0.0;
  6584. result.m[4] = yaxis.x;
  6585. result.m[5] = yaxis.y;
  6586. result.m[6] = yaxis.z;
  6587. result.m[7] = 0.0;
  6588. result.m[8] = zaxis.x;
  6589. result.m[9] = zaxis.y;
  6590. result.m[10] = zaxis.z;
  6591. result.m[11] = 0.0;
  6592. result.m[12] = 0.0;
  6593. result.m[13] = 0.0;
  6594. result.m[14] = 0.0;
  6595. result.m[15] = 1.0;
  6596. result._markAsUpdated();
  6597. };
  6598. /**
  6599. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6600. * @param quat defines the quaternion to use
  6601. * @param result defines the target matrix
  6602. */
  6603. Matrix.FromQuaternionToRef = function (quat, result) {
  6604. var xx = quat.x * quat.x;
  6605. var yy = quat.y * quat.y;
  6606. var zz = quat.z * quat.z;
  6607. var xy = quat.x * quat.y;
  6608. var zw = quat.z * quat.w;
  6609. var zx = quat.z * quat.x;
  6610. var yw = quat.y * quat.w;
  6611. var yz = quat.y * quat.z;
  6612. var xw = quat.x * quat.w;
  6613. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6614. result.m[1] = 2.0 * (xy + zw);
  6615. result.m[2] = 2.0 * (zx - yw);
  6616. result.m[3] = 0.0;
  6617. result.m[4] = 2.0 * (xy - zw);
  6618. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6619. result.m[6] = 2.0 * (yz + xw);
  6620. result.m[7] = 0.0;
  6621. result.m[8] = 2.0 * (zx + yw);
  6622. result.m[9] = 2.0 * (yz - xw);
  6623. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6624. result.m[11] = 0.0;
  6625. result.m[12] = 0.0;
  6626. result.m[13] = 0.0;
  6627. result.m[14] = 0.0;
  6628. result.m[15] = 1.0;
  6629. result._markAsUpdated();
  6630. };
  6631. Matrix._tempQuaternion = new Quaternion();
  6632. Matrix._xAxis = Vector3.Zero();
  6633. Matrix._yAxis = Vector3.Zero();
  6634. Matrix._zAxis = Vector3.Zero();
  6635. Matrix._updateFlagSeed = 0;
  6636. Matrix._identityReadOnly = Matrix.Identity();
  6637. return Matrix;
  6638. }());
  6639. BABYLON.Matrix = Matrix;
  6640. var Plane = /** @class */ (function () {
  6641. /**
  6642. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6643. */
  6644. function Plane(a, b, c, d) {
  6645. this.normal = new Vector3(a, b, c);
  6646. this.d = d;
  6647. }
  6648. /**
  6649. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6650. */
  6651. Plane.prototype.asArray = function () {
  6652. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6653. };
  6654. // Methods
  6655. /**
  6656. * Returns a new plane copied from the current Plane.
  6657. */
  6658. Plane.prototype.clone = function () {
  6659. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6660. };
  6661. /**
  6662. * Returns the string "Plane".
  6663. */
  6664. Plane.prototype.getClassName = function () {
  6665. return "Plane";
  6666. };
  6667. /**
  6668. * Returns the Plane hash code.
  6669. */
  6670. Plane.prototype.getHashCode = function () {
  6671. var hash = this.normal.getHashCode();
  6672. hash = (hash * 397) ^ (this.d || 0);
  6673. return hash;
  6674. };
  6675. /**
  6676. * Normalize the current Plane in place.
  6677. * Returns the updated Plane.
  6678. */
  6679. Plane.prototype.normalize = function () {
  6680. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6681. var magnitude = 0.0;
  6682. if (norm !== 0) {
  6683. magnitude = 1.0 / norm;
  6684. }
  6685. this.normal.x *= magnitude;
  6686. this.normal.y *= magnitude;
  6687. this.normal.z *= magnitude;
  6688. this.d *= magnitude;
  6689. return this;
  6690. };
  6691. /**
  6692. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6693. */
  6694. Plane.prototype.transform = function (transformation) {
  6695. var transposedMatrix = Matrix.Transpose(transformation);
  6696. var x = this.normal.x;
  6697. var y = this.normal.y;
  6698. var z = this.normal.z;
  6699. var d = this.d;
  6700. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6701. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6702. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6703. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6704. return new Plane(normalX, normalY, normalZ, finalD);
  6705. };
  6706. /**
  6707. * Returns the dot product (float) of the point coordinates and the plane normal.
  6708. */
  6709. Plane.prototype.dotCoordinate = function (point) {
  6710. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6711. };
  6712. /**
  6713. * Updates the current Plane from the plane defined by the three given points.
  6714. * Returns the updated Plane.
  6715. */
  6716. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6717. var x1 = point2.x - point1.x;
  6718. var y1 = point2.y - point1.y;
  6719. var z1 = point2.z - point1.z;
  6720. var x2 = point3.x - point1.x;
  6721. var y2 = point3.y - point1.y;
  6722. var z2 = point3.z - point1.z;
  6723. var yz = (y1 * z2) - (z1 * y2);
  6724. var xz = (z1 * x2) - (x1 * z2);
  6725. var xy = (x1 * y2) - (y1 * x2);
  6726. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6727. var invPyth;
  6728. if (pyth !== 0) {
  6729. invPyth = 1.0 / pyth;
  6730. }
  6731. else {
  6732. invPyth = 0.0;
  6733. }
  6734. this.normal.x = yz * invPyth;
  6735. this.normal.y = xz * invPyth;
  6736. this.normal.z = xy * invPyth;
  6737. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6738. return this;
  6739. };
  6740. /**
  6741. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6742. */
  6743. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6744. var dot = Vector3.Dot(this.normal, direction);
  6745. return (dot <= epsilon);
  6746. };
  6747. /**
  6748. * Returns the signed distance (float) from the given point to the Plane.
  6749. */
  6750. Plane.prototype.signedDistanceTo = function (point) {
  6751. return Vector3.Dot(point, this.normal) + this.d;
  6752. };
  6753. // Statics
  6754. /**
  6755. * Returns a new Plane from the given array.
  6756. */
  6757. Plane.FromArray = function (array) {
  6758. return new Plane(array[0], array[1], array[2], array[3]);
  6759. };
  6760. /**
  6761. * Returns a new Plane defined by the three given points.
  6762. */
  6763. Plane.FromPoints = function (point1, point2, point3) {
  6764. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6765. result.copyFromPoints(point1, point2, point3);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns a new Plane the normal vector to this plane at the given origin point.
  6770. * Note : the vector "normal" is updated because normalized.
  6771. */
  6772. Plane.FromPositionAndNormal = function (origin, normal) {
  6773. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6774. normal.normalize();
  6775. result.normal = normal;
  6776. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6777. return result;
  6778. };
  6779. /**
  6780. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6781. */
  6782. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6783. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6784. return Vector3.Dot(point, normal) + d;
  6785. };
  6786. return Plane;
  6787. }());
  6788. BABYLON.Plane = Plane;
  6789. /**
  6790. * Class used to represent a viewport on screen
  6791. */
  6792. var Viewport = /** @class */ (function () {
  6793. /**
  6794. * Creates a Viewport object located at (x, y) and sized (width, height)
  6795. * @param x defines viewport left coordinate
  6796. * @param y defines viewport top coordinate
  6797. * @param width defines the viewport width
  6798. * @param height defines the viewport height
  6799. */
  6800. function Viewport(
  6801. /** viewport left coordinate */
  6802. x,
  6803. /** viewport top coordinate */
  6804. y,
  6805. /**viewport width */
  6806. width,
  6807. /** viewport height */
  6808. height) {
  6809. this.x = x;
  6810. this.y = y;
  6811. this.width = width;
  6812. this.height = height;
  6813. }
  6814. /**
  6815. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6816. * @param renderWidthOrEngine defines either an engine or the rendering width
  6817. * @param renderHeight defines the rendering height
  6818. * @returns a new Viewport
  6819. */
  6820. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6821. if (renderWidthOrEngine.getRenderWidth) {
  6822. var engine = renderWidthOrEngine;
  6823. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6824. }
  6825. var renderWidth = renderWidthOrEngine;
  6826. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6827. };
  6828. /**
  6829. * Returns a new Viewport copied from the current one
  6830. * @returns a new Viewport
  6831. */
  6832. Viewport.prototype.clone = function () {
  6833. return new Viewport(this.x, this.y, this.width, this.height);
  6834. };
  6835. return Viewport;
  6836. }());
  6837. BABYLON.Viewport = Viewport;
  6838. var Frustum = /** @class */ (function () {
  6839. function Frustum() {
  6840. }
  6841. /**
  6842. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6843. */
  6844. Frustum.GetPlanes = function (transform) {
  6845. var frustumPlanes = [];
  6846. for (var index = 0; index < 6; index++) {
  6847. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6848. }
  6849. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6850. return frustumPlanes;
  6851. };
  6852. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6856. frustumPlane.d = transform.m[15] + transform.m[14];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6863. frustumPlane.d = transform.m[15] - transform.m[14];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6870. frustumPlane.d = transform.m[15] + transform.m[12];
  6871. frustumPlane.normalize();
  6872. };
  6873. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6874. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6875. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6876. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6877. frustumPlane.d = transform.m[15] - transform.m[12];
  6878. frustumPlane.normalize();
  6879. };
  6880. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6881. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6882. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6883. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6884. frustumPlane.d = transform.m[15] - transform.m[13];
  6885. frustumPlane.normalize();
  6886. };
  6887. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6888. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6889. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6890. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6891. frustumPlane.d = transform.m[15] + transform.m[13];
  6892. frustumPlane.normalize();
  6893. };
  6894. /**
  6895. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6896. */
  6897. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6898. // Near
  6899. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6900. // Far
  6901. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6902. // Left
  6903. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6904. // Right
  6905. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6906. // Top
  6907. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6908. // Bottom
  6909. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6910. };
  6911. return Frustum;
  6912. }());
  6913. BABYLON.Frustum = Frustum;
  6914. /** Defines supported spaces */
  6915. var Space;
  6916. (function (Space) {
  6917. /** Local (object) space */
  6918. Space[Space["LOCAL"] = 0] = "LOCAL";
  6919. /** World space */
  6920. Space[Space["WORLD"] = 1] = "WORLD";
  6921. /** Bone space */
  6922. Space[Space["BONE"] = 2] = "BONE";
  6923. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6924. /** Defines the 3 main axes */
  6925. var Axis = /** @class */ (function () {
  6926. function Axis() {
  6927. }
  6928. /** X axis */
  6929. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6930. /** Y axis */
  6931. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6932. /** Z axis */
  6933. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6934. return Axis;
  6935. }());
  6936. BABYLON.Axis = Axis;
  6937. ;
  6938. /** Class used to represent a Bezier curve */
  6939. var BezierCurve = /** @class */ (function () {
  6940. function BezierCurve() {
  6941. }
  6942. /**
  6943. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  6944. * @param t defines the time
  6945. * @param x1 defines the left coordinate on X axis
  6946. * @param y1 defines the left coordinate on Y axis
  6947. * @param x2 defines the right coordinate on X axis
  6948. * @param y2 defines the right coordinate on Y axis
  6949. * @returns the interpolated value
  6950. */
  6951. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  6952. // Extract X (which is equal to time here)
  6953. var f0 = 1 - 3 * x2 + 3 * x1;
  6954. var f1 = 3 * x2 - 6 * x1;
  6955. var f2 = 3 * x1;
  6956. var refinedT = t;
  6957. for (var i = 0; i < 5; i++) {
  6958. var refinedT2 = refinedT * refinedT;
  6959. var refinedT3 = refinedT2 * refinedT;
  6960. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6961. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6962. refinedT -= (x - t) * slope;
  6963. refinedT = Math.min(1, Math.max(0, refinedT));
  6964. }
  6965. // Resolve cubic bezier for the given x
  6966. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6967. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6968. Math.pow(refinedT, 3);
  6969. };
  6970. return BezierCurve;
  6971. }());
  6972. BABYLON.BezierCurve = BezierCurve;
  6973. /**
  6974. * Defines potential orientation for back face culling
  6975. */
  6976. var Orientation;
  6977. (function (Orientation) {
  6978. /**
  6979. * Clockwise
  6980. */
  6981. Orientation[Orientation["CW"] = 0] = "CW";
  6982. /** Counter clockwise */
  6983. Orientation[Orientation["CCW"] = 1] = "CCW";
  6984. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6985. /**
  6986. * Defines angle representation
  6987. */
  6988. var Angle = /** @class */ (function () {
  6989. /**
  6990. * Creates an Angle object of "radians" radians (float).
  6991. */
  6992. function Angle(radians) {
  6993. this._radians = radians;
  6994. if (this._radians < 0.0)
  6995. this._radians += (2.0 * Math.PI);
  6996. }
  6997. /**
  6998. * Get value in degrees
  6999. * @returns the Angle value in degrees (float)
  7000. */
  7001. Angle.prototype.degrees = function () {
  7002. return this._radians * 180.0 / Math.PI;
  7003. };
  7004. /**
  7005. * Get value in radians
  7006. * @returns the Angle value in radians (float)
  7007. */
  7008. Angle.prototype.radians = function () {
  7009. return this._radians;
  7010. };
  7011. /**
  7012. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7013. * @param a defines first vector
  7014. * @param b defines second vector
  7015. * @returns a new Angle
  7016. */
  7017. Angle.BetweenTwoPoints = function (a, b) {
  7018. var delta = b.subtract(a);
  7019. var theta = Math.atan2(delta.y, delta.x);
  7020. return new Angle(theta);
  7021. };
  7022. /**
  7023. * Gets a new Angle object from the given float in radians
  7024. * @param radians defines the angle value in radians
  7025. * @returns a new Angle
  7026. */
  7027. Angle.FromRadians = function (radians) {
  7028. return new Angle(radians);
  7029. };
  7030. /**
  7031. * Gets a new Angle object from the given float in degrees
  7032. * @param degrees defines the angle value in degrees
  7033. * @returns a new Angle
  7034. */
  7035. Angle.FromDegrees = function (degrees) {
  7036. return new Angle(degrees * Math.PI / 180.0);
  7037. };
  7038. return Angle;
  7039. }());
  7040. BABYLON.Angle = Angle;
  7041. /**
  7042. * This represents an arc in a 2d space.
  7043. */
  7044. var Arc2 = /** @class */ (function () {
  7045. /**
  7046. * Creates an Arc object from the three given points : start, middle and end.
  7047. * @param startPoint Defines the start point of the arc
  7048. * @param midPoint Defines the midlle point of the arc
  7049. * @param endPoint Defines the end point of the arc
  7050. */
  7051. function Arc2(
  7052. /** Defines the start point of the arc */
  7053. startPoint,
  7054. /** Defines the mid point of the arc */
  7055. midPoint,
  7056. /** Defines the end point of the arc */
  7057. endPoint) {
  7058. this.startPoint = startPoint;
  7059. this.midPoint = midPoint;
  7060. this.endPoint = endPoint;
  7061. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7062. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7063. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7064. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7065. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7066. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7067. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7068. var a1 = this.startAngle.degrees();
  7069. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7070. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7071. // angles correction
  7072. if (a2 - a1 > +180.0)
  7073. a2 -= 360.0;
  7074. if (a2 - a1 < -180.0)
  7075. a2 += 360.0;
  7076. if (a3 - a2 > +180.0)
  7077. a3 -= 360.0;
  7078. if (a3 - a2 < -180.0)
  7079. a3 += 360.0;
  7080. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7081. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7082. }
  7083. return Arc2;
  7084. }());
  7085. BABYLON.Arc2 = Arc2;
  7086. var Path2 = /** @class */ (function () {
  7087. /**
  7088. * Creates a Path2 object from the starting 2D coordinates x and y.
  7089. */
  7090. function Path2(x, y) {
  7091. this._points = new Array();
  7092. this._length = 0.0;
  7093. this.closed = false;
  7094. this._points.push(new Vector2(x, y));
  7095. }
  7096. /**
  7097. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7098. * Returns the updated Path2.
  7099. */
  7100. Path2.prototype.addLineTo = function (x, y) {
  7101. if (this.closed) {
  7102. return this;
  7103. }
  7104. var newPoint = new Vector2(x, y);
  7105. var previousPoint = this._points[this._points.length - 1];
  7106. this._points.push(newPoint);
  7107. this._length += newPoint.subtract(previousPoint).length();
  7108. return this;
  7109. };
  7110. /**
  7111. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7112. * Returns the updated Path2.
  7113. */
  7114. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7115. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7116. if (this.closed) {
  7117. return this;
  7118. }
  7119. var startPoint = this._points[this._points.length - 1];
  7120. var midPoint = new Vector2(midX, midY);
  7121. var endPoint = new Vector2(endX, endY);
  7122. var arc = new Arc2(startPoint, midPoint, endPoint);
  7123. var increment = arc.angle.radians() / numberOfSegments;
  7124. if (arc.orientation === Orientation.CW)
  7125. increment *= -1;
  7126. var currentAngle = arc.startAngle.radians() + increment;
  7127. for (var i = 0; i < numberOfSegments; i++) {
  7128. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7129. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7130. this.addLineTo(x, y);
  7131. currentAngle += increment;
  7132. }
  7133. return this;
  7134. };
  7135. /**
  7136. * Closes the Path2.
  7137. * Returns the Path2.
  7138. */
  7139. Path2.prototype.close = function () {
  7140. this.closed = true;
  7141. return this;
  7142. };
  7143. /**
  7144. * Returns the Path2 total length (float).
  7145. */
  7146. Path2.prototype.length = function () {
  7147. var result = this._length;
  7148. if (!this.closed) {
  7149. var lastPoint = this._points[this._points.length - 1];
  7150. var firstPoint = this._points[0];
  7151. result += (firstPoint.subtract(lastPoint).length());
  7152. }
  7153. return result;
  7154. };
  7155. /**
  7156. * Returns the Path2 internal array of points.
  7157. */
  7158. Path2.prototype.getPoints = function () {
  7159. return this._points;
  7160. };
  7161. /**
  7162. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7163. */
  7164. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7165. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7166. return Vector2.Zero();
  7167. }
  7168. var lengthPosition = normalizedLengthPosition * this.length();
  7169. var previousOffset = 0;
  7170. for (var i = 0; i < this._points.length; i++) {
  7171. var j = (i + 1) % this._points.length;
  7172. var a = this._points[i];
  7173. var b = this._points[j];
  7174. var bToA = b.subtract(a);
  7175. var nextOffset = (bToA.length() + previousOffset);
  7176. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7177. var dir = bToA.normalize();
  7178. var localOffset = lengthPosition - previousOffset;
  7179. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7180. }
  7181. previousOffset = nextOffset;
  7182. }
  7183. return Vector2.Zero();
  7184. };
  7185. /**
  7186. * Returns a new Path2 starting at the coordinates (x, y).
  7187. */
  7188. Path2.StartingAt = function (x, y) {
  7189. return new Path2(x, y);
  7190. };
  7191. return Path2;
  7192. }());
  7193. BABYLON.Path2 = Path2;
  7194. var Path3D = /** @class */ (function () {
  7195. /**
  7196. * new Path3D(path, normal, raw)
  7197. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7198. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7199. * path : an array of Vector3, the curve axis of the Path3D
  7200. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7201. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7202. */
  7203. function Path3D(path, firstNormal, raw) {
  7204. if (firstNormal === void 0) { firstNormal = null; }
  7205. this.path = path;
  7206. this._curve = new Array();
  7207. this._distances = new Array();
  7208. this._tangents = new Array();
  7209. this._normals = new Array();
  7210. this._binormals = new Array();
  7211. for (var p = 0; p < path.length; p++) {
  7212. this._curve[p] = path[p].clone(); // hard copy
  7213. }
  7214. this._raw = raw || false;
  7215. this._compute(firstNormal);
  7216. }
  7217. /**
  7218. * Returns the Path3D array of successive Vector3 designing its curve.
  7219. */
  7220. Path3D.prototype.getCurve = function () {
  7221. return this._curve;
  7222. };
  7223. /**
  7224. * Returns an array populated with tangent vectors on each Path3D curve point.
  7225. */
  7226. Path3D.prototype.getTangents = function () {
  7227. return this._tangents;
  7228. };
  7229. /**
  7230. * Returns an array populated with normal vectors on each Path3D curve point.
  7231. */
  7232. Path3D.prototype.getNormals = function () {
  7233. return this._normals;
  7234. };
  7235. /**
  7236. * Returns an array populated with binormal vectors on each Path3D curve point.
  7237. */
  7238. Path3D.prototype.getBinormals = function () {
  7239. return this._binormals;
  7240. };
  7241. /**
  7242. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7243. */
  7244. Path3D.prototype.getDistances = function () {
  7245. return this._distances;
  7246. };
  7247. /**
  7248. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7249. * Returns the same object updated.
  7250. */
  7251. Path3D.prototype.update = function (path, firstNormal) {
  7252. if (firstNormal === void 0) { firstNormal = null; }
  7253. for (var p = 0; p < path.length; p++) {
  7254. this._curve[p].x = path[p].x;
  7255. this._curve[p].y = path[p].y;
  7256. this._curve[p].z = path[p].z;
  7257. }
  7258. this._compute(firstNormal);
  7259. return this;
  7260. };
  7261. // private function compute() : computes tangents, normals and binormals
  7262. Path3D.prototype._compute = function (firstNormal) {
  7263. var l = this._curve.length;
  7264. // first and last tangents
  7265. this._tangents[0] = this._getFirstNonNullVector(0);
  7266. if (!this._raw) {
  7267. this._tangents[0].normalize();
  7268. }
  7269. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7270. if (!this._raw) {
  7271. this._tangents[l - 1].normalize();
  7272. }
  7273. // normals and binormals at first point : arbitrary vector with _normalVector()
  7274. var tg0 = this._tangents[0];
  7275. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7276. this._normals[0] = pp0;
  7277. if (!this._raw) {
  7278. this._normals[0].normalize();
  7279. }
  7280. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7281. if (!this._raw) {
  7282. this._binormals[0].normalize();
  7283. }
  7284. this._distances[0] = 0.0;
  7285. // normals and binormals : next points
  7286. var prev; // previous vector (segment)
  7287. var cur; // current vector (segment)
  7288. var curTang; // current tangent
  7289. // previous normal
  7290. var prevBinor; // previous binormal
  7291. for (var i = 1; i < l; i++) {
  7292. // tangents
  7293. prev = this._getLastNonNullVector(i);
  7294. if (i < l - 1) {
  7295. cur = this._getFirstNonNullVector(i);
  7296. this._tangents[i] = prev.add(cur);
  7297. this._tangents[i].normalize();
  7298. }
  7299. this._distances[i] = this._distances[i - 1] + prev.length();
  7300. // normals and binormals
  7301. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7302. curTang = this._tangents[i];
  7303. prevBinor = this._binormals[i - 1];
  7304. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7305. if (!this._raw) {
  7306. this._normals[i].normalize();
  7307. }
  7308. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7309. if (!this._raw) {
  7310. this._binormals[i].normalize();
  7311. }
  7312. }
  7313. };
  7314. // private function getFirstNonNullVector(index)
  7315. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7316. Path3D.prototype._getFirstNonNullVector = function (index) {
  7317. var i = 1;
  7318. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7319. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7320. i++;
  7321. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7322. }
  7323. return nNVector;
  7324. };
  7325. // private function getLastNonNullVector(index)
  7326. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7327. Path3D.prototype._getLastNonNullVector = function (index) {
  7328. var i = 1;
  7329. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7330. while (nLVector.length() === 0 && index > i + 1) {
  7331. i++;
  7332. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7333. }
  7334. return nLVector;
  7335. };
  7336. // private function normalVector(v0, vt, va) :
  7337. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7338. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7339. Path3D.prototype._normalVector = function (v0, vt, va) {
  7340. var normal0;
  7341. var tgl = vt.length();
  7342. if (tgl === 0.0) {
  7343. tgl = 1.0;
  7344. }
  7345. if (va === undefined || va === null) {
  7346. var point;
  7347. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7348. point = new Vector3(0.0, -1.0, 0.0);
  7349. }
  7350. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7351. point = new Vector3(1.0, 0.0, 0.0);
  7352. }
  7353. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7354. point = new Vector3(0.0, 0.0, 1.0);
  7355. }
  7356. else {
  7357. point = Vector3.Zero();
  7358. }
  7359. normal0 = Vector3.Cross(vt, point);
  7360. }
  7361. else {
  7362. normal0 = Vector3.Cross(vt, va);
  7363. Vector3.CrossToRef(normal0, vt, normal0);
  7364. }
  7365. normal0.normalize();
  7366. return normal0;
  7367. };
  7368. return Path3D;
  7369. }());
  7370. BABYLON.Path3D = Path3D;
  7371. var Curve3 = /** @class */ (function () {
  7372. /**
  7373. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7374. * A Curve3 is designed from a series of successive Vector3.
  7375. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7376. */
  7377. function Curve3(points) {
  7378. this._length = 0.0;
  7379. this._points = points;
  7380. this._length = this._computeLength(points);
  7381. }
  7382. /**
  7383. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7384. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7385. * @param v1 (Vector3) the control point
  7386. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7390. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7391. var bez = new Array();
  7392. var equation = function (t, val0, val1, val2) {
  7393. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7394. return res;
  7395. };
  7396. for (var i = 0; i <= nbPoints; i++) {
  7397. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7398. }
  7399. return new Curve3(bez);
  7400. };
  7401. /**
  7402. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7403. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7404. * @param v1 (Vector3) the first control point
  7405. * @param v2 (Vector3) the second control point
  7406. * @param v3 (Vector3) the end point of the Cubic Bezier
  7407. * @param nbPoints (integer) the wanted number of points in the curve
  7408. */
  7409. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7410. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7411. var bez = new Array();
  7412. var equation = function (t, val0, val1, val2, val3) {
  7413. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7414. return res;
  7415. };
  7416. for (var i = 0; i <= nbPoints; i++) {
  7417. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7418. }
  7419. return new Curve3(bez);
  7420. };
  7421. /**
  7422. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7423. * @param p1 (Vector3) the origin point of the Hermite Spline
  7424. * @param t1 (Vector3) the tangent vector at the origin point
  7425. * @param p2 (Vector3) the end point of the Hermite Spline
  7426. * @param t2 (Vector3) the tangent vector at the end point
  7427. * @param nbPoints (integer) the wanted number of points in the curve
  7428. */
  7429. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7430. var hermite = new Array();
  7431. var step = 1.0 / nbPoints;
  7432. for (var i = 0; i <= nbPoints; i++) {
  7433. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7434. }
  7435. return new Curve3(hermite);
  7436. };
  7437. /**
  7438. * Returns a Curve3 object along a CatmullRom Spline curve :
  7439. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7440. * @param nbPoints (integer) the wanted number of points between each curve control points
  7441. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7442. */
  7443. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7444. var catmullRom = new Array();
  7445. var step = 1.0 / nbPoints;
  7446. var amount = 0.0;
  7447. if (closed) {
  7448. var pointsCount = points.length;
  7449. for (var i = 0; i < pointsCount; i++) {
  7450. amount = 0;
  7451. for (var c = 0; c < nbPoints; c++) {
  7452. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7453. amount += step;
  7454. }
  7455. }
  7456. catmullRom.push(catmullRom[0]);
  7457. }
  7458. else {
  7459. var totalPoints = new Array();
  7460. totalPoints.push(points[0].clone());
  7461. Array.prototype.push.apply(totalPoints, points);
  7462. totalPoints.push(points[points.length - 1].clone());
  7463. for (var i = 0; i < totalPoints.length - 3; i++) {
  7464. amount = 0;
  7465. for (var c = 0; c < nbPoints; c++) {
  7466. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7467. amount += step;
  7468. }
  7469. }
  7470. i--;
  7471. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7472. }
  7473. return new Curve3(catmullRom);
  7474. };
  7475. /**
  7476. * Returns the Curve3 stored array of successive Vector3
  7477. */
  7478. Curve3.prototype.getPoints = function () {
  7479. return this._points;
  7480. };
  7481. /**
  7482. * Returns the computed length (float) of the curve.
  7483. */
  7484. Curve3.prototype.length = function () {
  7485. return this._length;
  7486. };
  7487. /**
  7488. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7489. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7490. * curveA and curveB keep unchanged.
  7491. */
  7492. Curve3.prototype.continue = function (curve) {
  7493. var lastPoint = this._points[this._points.length - 1];
  7494. var continuedPoints = this._points.slice();
  7495. var curvePoints = curve.getPoints();
  7496. for (var i = 1; i < curvePoints.length; i++) {
  7497. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7498. }
  7499. var continuedCurve = new Curve3(continuedPoints);
  7500. return continuedCurve;
  7501. };
  7502. Curve3.prototype._computeLength = function (path) {
  7503. var l = 0;
  7504. for (var i = 1; i < path.length; i++) {
  7505. l += (path[i].subtract(path[i - 1])).length();
  7506. }
  7507. return l;
  7508. };
  7509. return Curve3;
  7510. }());
  7511. BABYLON.Curve3 = Curve3;
  7512. // Vertex formats
  7513. var PositionNormalVertex = /** @class */ (function () {
  7514. function PositionNormalVertex(position, normal) {
  7515. if (position === void 0) { position = Vector3.Zero(); }
  7516. if (normal === void 0) { normal = Vector3.Up(); }
  7517. this.position = position;
  7518. this.normal = normal;
  7519. }
  7520. PositionNormalVertex.prototype.clone = function () {
  7521. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7522. };
  7523. return PositionNormalVertex;
  7524. }());
  7525. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7526. var PositionNormalTextureVertex = /** @class */ (function () {
  7527. function PositionNormalTextureVertex(position, normal, uv) {
  7528. if (position === void 0) { position = Vector3.Zero(); }
  7529. if (normal === void 0) { normal = Vector3.Up(); }
  7530. if (uv === void 0) { uv = Vector2.Zero(); }
  7531. this.position = position;
  7532. this.normal = normal;
  7533. this.uv = uv;
  7534. }
  7535. PositionNormalTextureVertex.prototype.clone = function () {
  7536. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7537. };
  7538. return PositionNormalTextureVertex;
  7539. }());
  7540. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7541. // Temporary pre-allocated objects for engine internal use
  7542. // usage in any internal function :
  7543. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7544. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7545. var Tmp = /** @class */ (function () {
  7546. function Tmp() {
  7547. }
  7548. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7549. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7550. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7551. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7552. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7553. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7554. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7555. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7556. Matrix.Zero(), Matrix.Zero(),
  7557. Matrix.Zero(), Matrix.Zero(),
  7558. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7559. return Tmp;
  7560. }());
  7561. BABYLON.Tmp = Tmp;
  7562. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7563. var MathTmp = /** @class */ (function () {
  7564. function MathTmp() {
  7565. }
  7566. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7567. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7568. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7569. return MathTmp;
  7570. }());
  7571. })(BABYLON || (BABYLON = {}));
  7572. //# sourceMappingURL=babylon.math.js.map
  7573. var BABYLON;
  7574. (function (BABYLON) {
  7575. var Scalar = /** @class */ (function () {
  7576. function Scalar() {
  7577. }
  7578. /**
  7579. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7580. */
  7581. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7583. var num = a - b;
  7584. return -epsilon <= num && num <= epsilon;
  7585. };
  7586. /**
  7587. * Returns a string : the upper case translation of the number i to hexadecimal.
  7588. */
  7589. Scalar.ToHex = function (i) {
  7590. var str = i.toString(16);
  7591. if (i <= 15) {
  7592. return ("0" + str).toUpperCase();
  7593. }
  7594. return str.toUpperCase();
  7595. };
  7596. /**
  7597. * Returns -1 if value is negative and +1 is value is positive.
  7598. * Returns the value itself if it's equal to zero.
  7599. */
  7600. Scalar.Sign = function (value) {
  7601. value = +value; // convert to a number
  7602. if (value === 0 || isNaN(value))
  7603. return value;
  7604. return value > 0 ? 1 : -1;
  7605. };
  7606. /**
  7607. * Returns the value itself if it's between min and max.
  7608. * Returns min if the value is lower than min.
  7609. * Returns max if the value is greater than max.
  7610. */
  7611. Scalar.Clamp = function (value, min, max) {
  7612. if (min === void 0) { min = 0; }
  7613. if (max === void 0) { max = 1; }
  7614. return Math.min(max, Math.max(min, value));
  7615. };
  7616. /**
  7617. * Returns the log2 of value.
  7618. */
  7619. Scalar.Log2 = function (value) {
  7620. return Math.log(value) * Math.LOG2E;
  7621. };
  7622. /**
  7623. * Loops the value, so that it is never larger than length and never smaller than 0.
  7624. *
  7625. * This is similar to the modulo operator but it works with floating point numbers.
  7626. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7627. * With t = 5 and length = 2.5, the result would be 0.0.
  7628. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7629. */
  7630. Scalar.Repeat = function (value, length) {
  7631. return value - Math.floor(value / length) * length;
  7632. };
  7633. /**
  7634. * Normalize the value between 0.0 and 1.0 using min and max values
  7635. */
  7636. Scalar.Normalize = function (value, min, max) {
  7637. return (value - min) / (max - min);
  7638. };
  7639. /**
  7640. * Denormalize the value from 0.0 and 1.0 using min and max values
  7641. */
  7642. Scalar.Denormalize = function (normalized, min, max) {
  7643. return (normalized * (max - min) + min);
  7644. };
  7645. /**
  7646. * Calculates the shortest difference between two given angles given in degrees.
  7647. */
  7648. Scalar.DeltaAngle = function (current, target) {
  7649. var num = Scalar.Repeat(target - current, 360.0);
  7650. if (num > 180.0) {
  7651. num -= 360.0;
  7652. }
  7653. return num;
  7654. };
  7655. /**
  7656. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7657. *
  7658. * The returned value will move back and forth between 0 and length
  7659. */
  7660. Scalar.PingPong = function (tx, length) {
  7661. var t = Scalar.Repeat(tx, length * 2.0);
  7662. return length - Math.abs(t - length);
  7663. };
  7664. /**
  7665. * Interpolates between min and max with smoothing at the limits.
  7666. *
  7667. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7668. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7669. */
  7670. Scalar.SmoothStep = function (from, to, tx) {
  7671. var t = Scalar.Clamp(tx);
  7672. t = -2.0 * t * t * t + 3.0 * t * t;
  7673. return to * t + from * (1.0 - t);
  7674. };
  7675. /**
  7676. * Moves a value current towards target.
  7677. *
  7678. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7679. * Negative values of maxDelta pushes the value away from target.
  7680. */
  7681. Scalar.MoveTowards = function (current, target, maxDelta) {
  7682. var result = 0;
  7683. if (Math.abs(target - current) <= maxDelta) {
  7684. result = target;
  7685. }
  7686. else {
  7687. result = current + Scalar.Sign(target - current) * maxDelta;
  7688. }
  7689. return result;
  7690. };
  7691. /**
  7692. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7693. *
  7694. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7695. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7696. */
  7697. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7698. var num = Scalar.DeltaAngle(current, target);
  7699. var result = 0;
  7700. if (-maxDelta < num && num < maxDelta) {
  7701. result = target;
  7702. }
  7703. else {
  7704. target = current + num;
  7705. result = Scalar.MoveTowards(current, target, maxDelta);
  7706. }
  7707. return result;
  7708. };
  7709. /**
  7710. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7711. */
  7712. Scalar.Lerp = function (start, end, amount) {
  7713. return start + ((end - start) * amount);
  7714. };
  7715. /**
  7716. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7717. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7718. */
  7719. Scalar.LerpAngle = function (start, end, amount) {
  7720. var num = Scalar.Repeat(end - start, 360.0);
  7721. if (num > 180.0) {
  7722. num -= 360.0;
  7723. }
  7724. return start + num * Scalar.Clamp(amount);
  7725. };
  7726. /**
  7727. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7728. */
  7729. Scalar.InverseLerp = function (a, b, value) {
  7730. var result = 0;
  7731. if (a != b) {
  7732. result = Scalar.Clamp((value - a) / (b - a));
  7733. }
  7734. else {
  7735. result = 0.0;
  7736. }
  7737. return result;
  7738. };
  7739. /**
  7740. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7741. */
  7742. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7743. var squared = amount * amount;
  7744. var cubed = amount * squared;
  7745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7747. var part3 = (cubed - (2.0 * squared)) + amount;
  7748. var part4 = cubed - squared;
  7749. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7750. };
  7751. /**
  7752. * Returns a random float number between and min and max values
  7753. */
  7754. Scalar.RandomRange = function (min, max) {
  7755. if (min === max)
  7756. return min;
  7757. return ((Math.random() * (max - min)) + min);
  7758. };
  7759. /**
  7760. * This function returns percentage of a number in a given range.
  7761. *
  7762. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7763. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7764. */
  7765. Scalar.RangeToPercent = function (number, min, max) {
  7766. return ((number - min) / (max - min));
  7767. };
  7768. /**
  7769. * This function returns number that corresponds to the percentage in a given range.
  7770. *
  7771. * PercentToRange(0.34,0,100) will return 34.
  7772. */
  7773. Scalar.PercentToRange = function (percent, min, max) {
  7774. return ((max - min) * percent + min);
  7775. };
  7776. /**
  7777. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7778. * @param angle The angle to normalize in radian.
  7779. * @return The converted angle.
  7780. */
  7781. Scalar.NormalizeRadians = function (angle) {
  7782. // More precise but slower version kept for reference.
  7783. // angle = angle % Tools.TwoPi;
  7784. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7785. //if (angle > Math.PI) {
  7786. // angle -= Tools.TwoPi;
  7787. //}
  7788. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7789. return angle;
  7790. };
  7791. /**
  7792. * Two pi constants convenient for computation.
  7793. */
  7794. Scalar.TwoPi = Math.PI * 2;
  7795. return Scalar;
  7796. }());
  7797. BABYLON.Scalar = Scalar;
  7798. })(BABYLON || (BABYLON = {}));
  7799. //# sourceMappingURL=babylon.math.scalar.js.map
  7800. //# sourceMappingURL=babylon.mixins.js.map
  7801. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7802. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7803. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7804. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7805. //# sourceMappingURL=babylon.webgl2.js.map
  7806. var BABYLON;
  7807. (function (BABYLON) {
  7808. var __decoratorInitialStore = {};
  7809. var __mergedStore = {};
  7810. var _copySource = function (creationFunction, source, instanciate) {
  7811. var destination = creationFunction();
  7812. // Tags
  7813. if (BABYLON.Tags) {
  7814. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7815. }
  7816. var classStore = getMergedStore(destination);
  7817. // Properties
  7818. for (var property in classStore) {
  7819. var propertyDescriptor = classStore[property];
  7820. var sourceProperty = source[property];
  7821. var propertyType = propertyDescriptor.type;
  7822. if (sourceProperty !== undefined && sourceProperty !== null) {
  7823. switch (propertyType) {
  7824. case 0: // Value
  7825. case 6: // Mesh reference
  7826. case 11: // Camera reference
  7827. destination[property] = sourceProperty;
  7828. break;
  7829. case 1: // Texture
  7830. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7831. break;
  7832. case 2: // Color3
  7833. case 3: // FresnelParameters
  7834. case 4: // Vector2
  7835. case 5: // Vector3
  7836. case 7: // Color Curves
  7837. case 10: // Quaternion
  7838. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7839. break;
  7840. }
  7841. }
  7842. }
  7843. return destination;
  7844. };
  7845. function getDirectStore(target) {
  7846. var classKey = target.getClassName();
  7847. if (!__decoratorInitialStore[classKey]) {
  7848. __decoratorInitialStore[classKey] = {};
  7849. }
  7850. return __decoratorInitialStore[classKey];
  7851. }
  7852. /**
  7853. * Return the list of properties flagged as serializable
  7854. * @param target: host object
  7855. */
  7856. function getMergedStore(target) {
  7857. var classKey = target.getClassName();
  7858. if (__mergedStore[classKey]) {
  7859. return __mergedStore[classKey];
  7860. }
  7861. __mergedStore[classKey] = {};
  7862. var store = __mergedStore[classKey];
  7863. var currentTarget = target;
  7864. var currentKey = classKey;
  7865. while (currentKey) {
  7866. var initialStore = __decoratorInitialStore[currentKey];
  7867. for (var property in initialStore) {
  7868. store[property] = initialStore[property];
  7869. }
  7870. var parent_1 = void 0;
  7871. var done = false;
  7872. do {
  7873. parent_1 = Object.getPrototypeOf(currentTarget);
  7874. if (!parent_1.getClassName) {
  7875. done = true;
  7876. break;
  7877. }
  7878. if (parent_1.getClassName() !== currentKey) {
  7879. break;
  7880. }
  7881. currentTarget = parent_1;
  7882. } while (parent_1);
  7883. if (done) {
  7884. break;
  7885. }
  7886. currentKey = parent_1.getClassName();
  7887. currentTarget = parent_1;
  7888. }
  7889. return store;
  7890. }
  7891. function generateSerializableMember(type, sourceName) {
  7892. return function (target, propertyKey) {
  7893. var classStore = getDirectStore(target);
  7894. if (!classStore[propertyKey]) {
  7895. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7896. }
  7897. };
  7898. }
  7899. function generateExpandMember(setCallback, targetKey) {
  7900. if (targetKey === void 0) { targetKey = null; }
  7901. return function (target, propertyKey) {
  7902. var key = targetKey || ("_" + propertyKey);
  7903. Object.defineProperty(target, propertyKey, {
  7904. get: function () {
  7905. return this[key];
  7906. },
  7907. set: function (value) {
  7908. if (this[key] === value) {
  7909. return;
  7910. }
  7911. this[key] = value;
  7912. target[setCallback].apply(this);
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. };
  7918. }
  7919. function expandToProperty(callback, targetKey) {
  7920. if (targetKey === void 0) { targetKey = null; }
  7921. return generateExpandMember(callback, targetKey);
  7922. }
  7923. BABYLON.expandToProperty = expandToProperty;
  7924. function serialize(sourceName) {
  7925. return generateSerializableMember(0, sourceName); // value member
  7926. }
  7927. BABYLON.serialize = serialize;
  7928. function serializeAsTexture(sourceName) {
  7929. return generateSerializableMember(1, sourceName); // texture member
  7930. }
  7931. BABYLON.serializeAsTexture = serializeAsTexture;
  7932. function serializeAsColor3(sourceName) {
  7933. return generateSerializableMember(2, sourceName); // color3 member
  7934. }
  7935. BABYLON.serializeAsColor3 = serializeAsColor3;
  7936. function serializeAsFresnelParameters(sourceName) {
  7937. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7938. }
  7939. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7940. function serializeAsVector2(sourceName) {
  7941. return generateSerializableMember(4, sourceName); // vector2 member
  7942. }
  7943. BABYLON.serializeAsVector2 = serializeAsVector2;
  7944. function serializeAsVector3(sourceName) {
  7945. return generateSerializableMember(5, sourceName); // vector3 member
  7946. }
  7947. BABYLON.serializeAsVector3 = serializeAsVector3;
  7948. function serializeAsMeshReference(sourceName) {
  7949. return generateSerializableMember(6, sourceName); // mesh reference member
  7950. }
  7951. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7952. function serializeAsColorCurves(sourceName) {
  7953. return generateSerializableMember(7, sourceName); // color curves
  7954. }
  7955. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7956. function serializeAsColor4(sourceName) {
  7957. return generateSerializableMember(8, sourceName); // color 4
  7958. }
  7959. BABYLON.serializeAsColor4 = serializeAsColor4;
  7960. function serializeAsImageProcessingConfiguration(sourceName) {
  7961. return generateSerializableMember(9, sourceName); // image processing
  7962. }
  7963. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7964. function serializeAsQuaternion(sourceName) {
  7965. return generateSerializableMember(10, sourceName); // quaternion member
  7966. }
  7967. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7968. /**
  7969. * Decorator used to define property that can be serialized as reference to a camera
  7970. * @param sourceName defines the name of the property to decorate
  7971. */
  7972. function serializeAsCameraReference(sourceName) {
  7973. return generateSerializableMember(11, sourceName); // camera reference member
  7974. }
  7975. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7976. var SerializationHelper = /** @class */ (function () {
  7977. function SerializationHelper() {
  7978. }
  7979. SerializationHelper.Serialize = function (entity, serializationObject) {
  7980. if (!serializationObject) {
  7981. serializationObject = {};
  7982. }
  7983. // Tags
  7984. if (BABYLON.Tags) {
  7985. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7986. }
  7987. var serializedProperties = getMergedStore(entity);
  7988. // Properties
  7989. for (var property in serializedProperties) {
  7990. var propertyDescriptor = serializedProperties[property];
  7991. var targetPropertyName = propertyDescriptor.sourceName || property;
  7992. var propertyType = propertyDescriptor.type;
  7993. var sourceProperty = entity[property];
  7994. if (sourceProperty !== undefined && sourceProperty !== null) {
  7995. switch (propertyType) {
  7996. case 0: // Value
  7997. serializationObject[targetPropertyName] = sourceProperty;
  7998. break;
  7999. case 1: // Texture
  8000. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8001. break;
  8002. case 2: // Color3
  8003. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8004. break;
  8005. case 3: // FresnelParameters
  8006. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8007. break;
  8008. case 4: // Vector2
  8009. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8010. break;
  8011. case 5: // Vector3
  8012. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8013. break;
  8014. case 6: // Mesh reference
  8015. serializationObject[targetPropertyName] = sourceProperty.id;
  8016. break;
  8017. case 7: // Color Curves
  8018. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8019. break;
  8020. case 8: // Color 4
  8021. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8022. break;
  8023. case 9: // Image Processing
  8024. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8025. break;
  8026. case 10: // Quaternion
  8027. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8028. break;
  8029. case 11: // Camera reference
  8030. serializationObject[targetPropertyName] = sourceProperty.id;
  8031. break;
  8032. }
  8033. }
  8034. }
  8035. return serializationObject;
  8036. };
  8037. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8038. if (rootUrl === void 0) { rootUrl = null; }
  8039. var destination = creationFunction();
  8040. if (!rootUrl) {
  8041. rootUrl = "";
  8042. }
  8043. // Tags
  8044. if (BABYLON.Tags) {
  8045. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8046. }
  8047. var classStore = getMergedStore(destination);
  8048. // Properties
  8049. for (var property in classStore) {
  8050. var propertyDescriptor = classStore[property];
  8051. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8052. var propertyType = propertyDescriptor.type;
  8053. if (sourceProperty !== undefined && sourceProperty !== null) {
  8054. var dest = destination;
  8055. switch (propertyType) {
  8056. case 0: // Value
  8057. dest[property] = sourceProperty;
  8058. break;
  8059. case 1: // Texture
  8060. if (scene) {
  8061. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8062. }
  8063. break;
  8064. case 2: // Color3
  8065. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8066. break;
  8067. case 3: // FresnelParameters
  8068. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8069. break;
  8070. case 4: // Vector2
  8071. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8072. break;
  8073. case 5: // Vector3
  8074. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8075. break;
  8076. case 6: // Mesh reference
  8077. if (scene) {
  8078. dest[property] = scene.getLastMeshByID(sourceProperty);
  8079. }
  8080. break;
  8081. case 7: // Color Curves
  8082. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8083. break;
  8084. case 8: // Color 4
  8085. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8086. break;
  8087. case 9: // Image Processing
  8088. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8089. break;
  8090. case 10: // Quaternion
  8091. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8092. break;
  8093. case 11: // Camera reference
  8094. if (scene) {
  8095. dest[property] = scene.getCameraByID(sourceProperty);
  8096. }
  8097. break;
  8098. }
  8099. }
  8100. }
  8101. return destination;
  8102. };
  8103. SerializationHelper.Clone = function (creationFunction, source) {
  8104. return _copySource(creationFunction, source, false);
  8105. };
  8106. SerializationHelper.Instanciate = function (creationFunction, source) {
  8107. return _copySource(creationFunction, source, true);
  8108. };
  8109. return SerializationHelper;
  8110. }());
  8111. BABYLON.SerializationHelper = SerializationHelper;
  8112. })(BABYLON || (BABYLON = {}));
  8113. //# sourceMappingURL=babylon.decorators.js.map
  8114. var BABYLON;
  8115. (function (BABYLON) {
  8116. /**
  8117. * Wrapper class for promise with external resolve and reject.
  8118. */
  8119. var Deferred = /** @class */ (function () {
  8120. /**
  8121. * Constructor for this deferred object.
  8122. */
  8123. function Deferred() {
  8124. var _this = this;
  8125. this.promise = new Promise(function (resolve, reject) {
  8126. _this._resolve = resolve;
  8127. _this._reject = reject;
  8128. });
  8129. }
  8130. Object.defineProperty(Deferred.prototype, "resolve", {
  8131. /**
  8132. * The resolve method of the promise associated with this deferred object.
  8133. */
  8134. get: function () {
  8135. return this._resolve;
  8136. },
  8137. enumerable: true,
  8138. configurable: true
  8139. });
  8140. Object.defineProperty(Deferred.prototype, "reject", {
  8141. /**
  8142. * The reject method of the promise associated with this deferred object.
  8143. */
  8144. get: function () {
  8145. return this._reject;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. return Deferred;
  8151. }());
  8152. BABYLON.Deferred = Deferred;
  8153. })(BABYLON || (BABYLON = {}));
  8154. //# sourceMappingURL=babylon.deferred.js.map
  8155. var BABYLON;
  8156. (function (BABYLON) {
  8157. /**
  8158. * A class serves as a medium between the observable and its observers
  8159. */
  8160. var EventState = /** @class */ (function () {
  8161. /**
  8162. * Create a new EventState
  8163. * @param mask defines the mask associated with this state
  8164. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8165. * @param target defines the original target of the state
  8166. * @param currentTarget defines the current target of the state
  8167. */
  8168. function EventState(mask, skipNextObservers, target, currentTarget) {
  8169. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8170. this.initalize(mask, skipNextObservers, target, currentTarget);
  8171. }
  8172. /**
  8173. * Initialize the current event state
  8174. * @param mask defines the mask associated with this state
  8175. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8176. * @param target defines the original target of the state
  8177. * @param currentTarget defines the current target of the state
  8178. * @returns the current event state
  8179. */
  8180. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8181. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8182. this.mask = mask;
  8183. this.skipNextObservers = skipNextObservers;
  8184. this.target = target;
  8185. this.currentTarget = currentTarget;
  8186. return this;
  8187. };
  8188. return EventState;
  8189. }());
  8190. BABYLON.EventState = EventState;
  8191. /**
  8192. * Represent an Observer registered to a given Observable object.
  8193. */
  8194. var Observer = /** @class */ (function () {
  8195. /**
  8196. * Creates a new observer
  8197. * @param callback defines the callback to call when the observer is notified
  8198. * @param mask defines the mask of the observer (used to filter notifications)
  8199. * @param scope defines the current scope used to restore the JS context
  8200. */
  8201. function Observer(
  8202. /**
  8203. * Defines the callback to call when the observer is notified
  8204. */
  8205. callback,
  8206. /**
  8207. * Defines the mask of the observer (used to filter notifications)
  8208. */
  8209. mask,
  8210. /**
  8211. * Defines the current scope used to restore the JS context
  8212. */
  8213. scope) {
  8214. if (scope === void 0) { scope = null; }
  8215. this.callback = callback;
  8216. this.mask = mask;
  8217. this.scope = scope;
  8218. /** @hidden */
  8219. this._willBeUnregistered = false;
  8220. /**
  8221. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8222. */
  8223. this.unregisterOnNextCall = false;
  8224. }
  8225. return Observer;
  8226. }());
  8227. BABYLON.Observer = Observer;
  8228. /**
  8229. * Represent a list of observers registered to multiple Observables object.
  8230. */
  8231. var MultiObserver = /** @class */ (function () {
  8232. function MultiObserver() {
  8233. }
  8234. /**
  8235. * Release associated resources
  8236. */
  8237. MultiObserver.prototype.dispose = function () {
  8238. if (this._observers && this._observables) {
  8239. for (var index = 0; index < this._observers.length; index++) {
  8240. this._observables[index].remove(this._observers[index]);
  8241. }
  8242. }
  8243. this._observers = null;
  8244. this._observables = null;
  8245. };
  8246. /**
  8247. * Raise a callback when one of the observable will notify
  8248. * @param observables defines a list of observables to watch
  8249. * @param callback defines the callback to call on notification
  8250. * @param mask defines the mask used to filter notifications
  8251. * @param scope defines the current scope used to restore the JS context
  8252. * @returns the new MultiObserver
  8253. */
  8254. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8255. if (mask === void 0) { mask = -1; }
  8256. if (scope === void 0) { scope = null; }
  8257. var result = new MultiObserver();
  8258. result._observers = new Array();
  8259. result._observables = observables;
  8260. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8261. var observable = observables_1[_i];
  8262. var observer = observable.add(callback, mask, false, scope);
  8263. if (observer) {
  8264. result._observers.push(observer);
  8265. }
  8266. }
  8267. return result;
  8268. };
  8269. return MultiObserver;
  8270. }());
  8271. BABYLON.MultiObserver = MultiObserver;
  8272. /**
  8273. * The Observable class is a simple implementation of the Observable pattern.
  8274. *
  8275. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8276. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8277. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8278. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8279. */
  8280. var Observable = /** @class */ (function () {
  8281. /**
  8282. * Creates a new observable
  8283. * @param onObserverAdded defines a callback to call when a new observer is added
  8284. */
  8285. function Observable(onObserverAdded) {
  8286. this._observers = new Array();
  8287. this._eventState = new EventState(0);
  8288. if (onObserverAdded) {
  8289. this._onObserverAdded = onObserverAdded;
  8290. }
  8291. }
  8292. /**
  8293. * Create a new Observer with the specified callback
  8294. * @param callback the callback that will be executed for that Observer
  8295. * @param mask the mask used to filter observers
  8296. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8297. * @param scope optional scope for the callback to be called from
  8298. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8299. * @returns the new observer created for the callback
  8300. */
  8301. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8302. if (mask === void 0) { mask = -1; }
  8303. if (insertFirst === void 0) { insertFirst = false; }
  8304. if (scope === void 0) { scope = null; }
  8305. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8306. if (!callback) {
  8307. return null;
  8308. }
  8309. var observer = new Observer(callback, mask, scope);
  8310. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8311. if (insertFirst) {
  8312. this._observers.unshift(observer);
  8313. }
  8314. else {
  8315. this._observers.push(observer);
  8316. }
  8317. if (this._onObserverAdded) {
  8318. this._onObserverAdded(observer);
  8319. }
  8320. return observer;
  8321. };
  8322. /**
  8323. * Create a new Observer with the specified callback and unregisters after the next notification
  8324. * @param callback the callback that will be executed for that Observer
  8325. * @returns the new observer created for the callback
  8326. */
  8327. Observable.prototype.addOnce = function (callback) {
  8328. return this.add(callback, undefined, undefined, undefined, true);
  8329. };
  8330. /**
  8331. * Remove an Observer from the Observable object
  8332. * @param observer the instance of the Observer to remove
  8333. * @returns false if it doesn't belong to this Observable
  8334. */
  8335. Observable.prototype.remove = function (observer) {
  8336. if (!observer) {
  8337. return false;
  8338. }
  8339. var index = this._observers.indexOf(observer);
  8340. if (index !== -1) {
  8341. this._deferUnregister(observer);
  8342. return true;
  8343. }
  8344. return false;
  8345. };
  8346. /**
  8347. * Remove a callback from the Observable object
  8348. * @param callback the callback to remove
  8349. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8350. * @returns false if it doesn't belong to this Observable
  8351. */
  8352. Observable.prototype.removeCallback = function (callback, scope) {
  8353. for (var index = 0; index < this._observers.length; index++) {
  8354. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8355. this._deferUnregister(this._observers[index]);
  8356. return true;
  8357. }
  8358. }
  8359. return false;
  8360. };
  8361. Observable.prototype._deferUnregister = function (observer) {
  8362. var _this = this;
  8363. observer.unregisterOnNextCall = false;
  8364. observer._willBeUnregistered = true;
  8365. BABYLON.Tools.SetImmediate(function () {
  8366. _this._remove(observer);
  8367. });
  8368. };
  8369. // This should only be called when not iterating over _observers to avoid callback skipping.
  8370. // Removes an observer from the _observer Array.
  8371. Observable.prototype._remove = function (observer) {
  8372. if (!observer) {
  8373. return false;
  8374. }
  8375. var index = this._observers.indexOf(observer);
  8376. if (index !== -1) {
  8377. this._observers.splice(index, 1);
  8378. return true;
  8379. }
  8380. return false;
  8381. };
  8382. /**
  8383. * Notify all Observers by calling their respective callback with the given data
  8384. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8385. * @param eventData defines the data to send to all observers
  8386. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8387. * @param target defines the original target of the state
  8388. * @param currentTarget defines the current target of the state
  8389. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8390. */
  8391. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8392. if (mask === void 0) { mask = -1; }
  8393. if (!this._observers.length) {
  8394. return true;
  8395. }
  8396. var state = this._eventState;
  8397. state.mask = mask;
  8398. state.target = target;
  8399. state.currentTarget = currentTarget;
  8400. state.skipNextObservers = false;
  8401. state.lastReturnValue = eventData;
  8402. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8403. var obs = _a[_i];
  8404. if (obs._willBeUnregistered) {
  8405. continue;
  8406. }
  8407. if (obs.mask & mask) {
  8408. if (obs.scope) {
  8409. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8410. }
  8411. else {
  8412. state.lastReturnValue = obs.callback(eventData, state);
  8413. }
  8414. if (obs.unregisterOnNextCall) {
  8415. this._deferUnregister(obs);
  8416. }
  8417. }
  8418. if (state.skipNextObservers) {
  8419. return false;
  8420. }
  8421. }
  8422. return true;
  8423. };
  8424. /**
  8425. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8426. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8427. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8428. * and it is crucial that all callbacks will be executed.
  8429. * The order of the callbacks is kept, callbacks are not executed parallel.
  8430. *
  8431. * @param eventData The data to be sent to each callback
  8432. * @param mask is used to filter observers defaults to -1
  8433. * @param target defines the callback target (see EventState)
  8434. * @param currentTarget defines he current object in the bubbling phase
  8435. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8436. */
  8437. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8438. var _this = this;
  8439. if (mask === void 0) { mask = -1; }
  8440. // create an empty promise
  8441. var p = Promise.resolve(eventData);
  8442. // no observers? return this promise.
  8443. if (!this._observers.length) {
  8444. return p;
  8445. }
  8446. var state = this._eventState;
  8447. state.mask = mask;
  8448. state.target = target;
  8449. state.currentTarget = currentTarget;
  8450. state.skipNextObservers = false;
  8451. // execute one callback after another (not using Promise.all, the order is important)
  8452. this._observers.forEach(function (obs) {
  8453. if (state.skipNextObservers) {
  8454. return;
  8455. }
  8456. if (obs._willBeUnregistered) {
  8457. return;
  8458. }
  8459. if (obs.mask & mask) {
  8460. if (obs.scope) {
  8461. p = p.then(function (lastReturnedValue) {
  8462. state.lastReturnValue = lastReturnedValue;
  8463. return obs.callback.apply(obs.scope, [eventData, state]);
  8464. });
  8465. }
  8466. else {
  8467. p = p.then(function (lastReturnedValue) {
  8468. state.lastReturnValue = lastReturnedValue;
  8469. return obs.callback(eventData, state);
  8470. });
  8471. }
  8472. if (obs.unregisterOnNextCall) {
  8473. _this._deferUnregister(obs);
  8474. }
  8475. }
  8476. });
  8477. // return the eventData
  8478. return p.then(function () { return eventData; });
  8479. };
  8480. /**
  8481. * Notify a specific observer
  8482. * @param observer defines the observer to notify
  8483. * @param eventData defines the data to be sent to each callback
  8484. * @param mask is used to filter observers defaults to -1
  8485. */
  8486. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8487. if (mask === void 0) { mask = -1; }
  8488. var state = this._eventState;
  8489. state.mask = mask;
  8490. state.skipNextObservers = false;
  8491. observer.callback(eventData, state);
  8492. };
  8493. /**
  8494. * Gets a boolean indicating if the observable has at least one observer
  8495. * @returns true is the Observable has at least one Observer registered
  8496. */
  8497. Observable.prototype.hasObservers = function () {
  8498. return this._observers.length > 0;
  8499. };
  8500. /**
  8501. * Clear the list of observers
  8502. */
  8503. Observable.prototype.clear = function () {
  8504. this._observers = new Array();
  8505. this._onObserverAdded = null;
  8506. };
  8507. /**
  8508. * Clone the current observable
  8509. * @returns a new observable
  8510. */
  8511. Observable.prototype.clone = function () {
  8512. var result = new Observable();
  8513. result._observers = this._observers.slice(0);
  8514. return result;
  8515. };
  8516. /**
  8517. * Does this observable handles observer registered with a given mask
  8518. * @param mask defines the mask to be tested
  8519. * @return whether or not one observer registered with the given mask is handeled
  8520. **/
  8521. Observable.prototype.hasSpecificMask = function (mask) {
  8522. if (mask === void 0) { mask = -1; }
  8523. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8524. var obs = _a[_i];
  8525. if (obs.mask & mask || obs.mask === mask) {
  8526. return true;
  8527. }
  8528. }
  8529. return false;
  8530. };
  8531. return Observable;
  8532. }());
  8533. BABYLON.Observable = Observable;
  8534. })(BABYLON || (BABYLON = {}));
  8535. //# sourceMappingURL=babylon.observable.js.map
  8536. var BABYLON;
  8537. (function (BABYLON) {
  8538. /**
  8539. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8540. */
  8541. var SmartArray = /** @class */ (function () {
  8542. /**
  8543. * Instantiates a Smart Array.
  8544. * @param capacity defines the default capacity of the array.
  8545. */
  8546. function SmartArray(capacity) {
  8547. /**
  8548. * The active length of the array.
  8549. */
  8550. this.length = 0;
  8551. this.data = new Array(capacity);
  8552. this._id = SmartArray._GlobalId++;
  8553. }
  8554. /**
  8555. * Pushes a value at the end of the active data.
  8556. * @param value defines the object to push in the array.
  8557. */
  8558. SmartArray.prototype.push = function (value) {
  8559. this.data[this.length++] = value;
  8560. if (this.length > this.data.length) {
  8561. this.data.length *= 2;
  8562. }
  8563. };
  8564. /**
  8565. * Iterates over the active data and apply the lambda to them.
  8566. * @param func defines the action to apply on each value.
  8567. */
  8568. SmartArray.prototype.forEach = function (func) {
  8569. for (var index = 0; index < this.length; index++) {
  8570. func(this.data[index]);
  8571. }
  8572. };
  8573. /**
  8574. * Sorts the full sets of data.
  8575. * @param compareFn defines the comparison function to apply.
  8576. */
  8577. SmartArray.prototype.sort = function (compareFn) {
  8578. this.data.sort(compareFn);
  8579. };
  8580. /**
  8581. * Resets the active data to an empty array.
  8582. */
  8583. SmartArray.prototype.reset = function () {
  8584. this.length = 0;
  8585. };
  8586. /**
  8587. * Releases all the data from the array as well as the array.
  8588. */
  8589. SmartArray.prototype.dispose = function () {
  8590. this.reset();
  8591. if (this.data) {
  8592. this.data.length = 0;
  8593. this.data = [];
  8594. }
  8595. };
  8596. /**
  8597. * Concats the active data with a given array.
  8598. * @param array defines the data to concatenate with.
  8599. */
  8600. SmartArray.prototype.concat = function (array) {
  8601. if (array.length === 0) {
  8602. return;
  8603. }
  8604. if (this.length + array.length > this.data.length) {
  8605. this.data.length = (this.length + array.length) * 2;
  8606. }
  8607. for (var index = 0; index < array.length; index++) {
  8608. this.data[this.length++] = (array.data || array)[index];
  8609. }
  8610. };
  8611. /**
  8612. * Returns the position of a value in the active data.
  8613. * @param value defines the value to find the index for
  8614. * @returns the index if found in the active data otherwise -1
  8615. */
  8616. SmartArray.prototype.indexOf = function (value) {
  8617. var position = this.data.indexOf(value);
  8618. if (position >= this.length) {
  8619. return -1;
  8620. }
  8621. return position;
  8622. };
  8623. /**
  8624. * Returns whether an element is part of the active data.
  8625. * @param value defines the value to look for
  8626. * @returns true if found in the active data otherwise false
  8627. */
  8628. SmartArray.prototype.contains = function (value) {
  8629. return this.indexOf(value) !== -1;
  8630. };
  8631. // Statics
  8632. SmartArray._GlobalId = 0;
  8633. return SmartArray;
  8634. }());
  8635. BABYLON.SmartArray = SmartArray;
  8636. /**
  8637. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8638. * The data in this array can only be present once
  8639. */
  8640. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8641. __extends(SmartArrayNoDuplicate, _super);
  8642. function SmartArrayNoDuplicate() {
  8643. var _this = _super !== null && _super.apply(this, arguments) || this;
  8644. _this._duplicateId = 0;
  8645. return _this;
  8646. }
  8647. /**
  8648. * Pushes a value at the end of the active data.
  8649. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8650. * @param value defines the object to push in the array.
  8651. */
  8652. SmartArrayNoDuplicate.prototype.push = function (value) {
  8653. _super.prototype.push.call(this, value);
  8654. if (!value.__smartArrayFlags) {
  8655. value.__smartArrayFlags = {};
  8656. }
  8657. value.__smartArrayFlags[this._id] = this._duplicateId;
  8658. };
  8659. /**
  8660. * Pushes a value at the end of the active data.
  8661. * If the data is already present, it won t be added again
  8662. * @param value defines the object to push in the array.
  8663. * @returns true if added false if it was already present
  8664. */
  8665. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8666. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8667. return false;
  8668. }
  8669. this.push(value);
  8670. return true;
  8671. };
  8672. /**
  8673. * Resets the active data to an empty array.
  8674. */
  8675. SmartArrayNoDuplicate.prototype.reset = function () {
  8676. _super.prototype.reset.call(this);
  8677. this._duplicateId++;
  8678. };
  8679. /**
  8680. * Concats the active data with a given array.
  8681. * This ensures no dupplicate will be present in the result.
  8682. * @param array defines the data to concatenate with.
  8683. */
  8684. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8685. if (array.length === 0) {
  8686. return;
  8687. }
  8688. if (this.length + array.length > this.data.length) {
  8689. this.data.length = (this.length + array.length) * 2;
  8690. }
  8691. for (var index = 0; index < array.length; index++) {
  8692. var item = (array.data || array)[index];
  8693. this.pushNoDuplicate(item);
  8694. }
  8695. };
  8696. return SmartArrayNoDuplicate;
  8697. }(SmartArray));
  8698. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8699. })(BABYLON || (BABYLON = {}));
  8700. //# sourceMappingURL=babylon.smartArray.js.map
  8701. var BABYLON;
  8702. (function (BABYLON) {
  8703. /** Class used to store color4 gradient */
  8704. var ColorGradient = /** @class */ (function () {
  8705. function ColorGradient() {
  8706. }
  8707. /**
  8708. * Will get a color picked randomly between color1 and color2.
  8709. * If color2 is undefined then color1 will be used
  8710. * @param result defines the target Color4 to store the result in
  8711. */
  8712. ColorGradient.prototype.getColorToRef = function (result) {
  8713. if (!this.color2) {
  8714. result.copyFrom(this.color1);
  8715. return;
  8716. }
  8717. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8718. };
  8719. return ColorGradient;
  8720. }());
  8721. BABYLON.ColorGradient = ColorGradient;
  8722. /** Class used to store color 3 gradient */
  8723. var Color3Gradient = /** @class */ (function () {
  8724. function Color3Gradient() {
  8725. }
  8726. return Color3Gradient;
  8727. }());
  8728. BABYLON.Color3Gradient = Color3Gradient;
  8729. /** Class used to store factor gradient */
  8730. var FactorGradient = /** @class */ (function () {
  8731. function FactorGradient() {
  8732. }
  8733. /**
  8734. * Will get a number picked randomly between factor1 and factor2.
  8735. * If factor2 is undefined then factor1 will be used
  8736. * @returns the picked number
  8737. */
  8738. FactorGradient.prototype.getFactor = function () {
  8739. if (this.factor2 === undefined) {
  8740. return this.factor1;
  8741. }
  8742. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8743. };
  8744. return FactorGradient;
  8745. }());
  8746. BABYLON.FactorGradient = FactorGradient;
  8747. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8748. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8749. var LoadFileError = /** @class */ (function (_super) {
  8750. __extends(LoadFileError, _super);
  8751. function LoadFileError(message, request) {
  8752. var _this = _super.call(this, message) || this;
  8753. _this.request = request;
  8754. _this.name = "LoadFileError";
  8755. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8756. return _this;
  8757. }
  8758. // Polyfill for Object.setPrototypeOf if necessary.
  8759. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8760. return LoadFileError;
  8761. }(Error));
  8762. BABYLON.LoadFileError = LoadFileError;
  8763. var RetryStrategy = /** @class */ (function () {
  8764. function RetryStrategy() {
  8765. }
  8766. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8767. if (maxRetries === void 0) { maxRetries = 3; }
  8768. if (baseInterval === void 0) { baseInterval = 500; }
  8769. return function (url, request, retryIndex) {
  8770. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8771. return -1;
  8772. }
  8773. return Math.pow(2, retryIndex) * baseInterval;
  8774. };
  8775. };
  8776. return RetryStrategy;
  8777. }());
  8778. BABYLON.RetryStrategy = RetryStrategy;
  8779. // Screenshots
  8780. var screenshotCanvas;
  8781. var cloneValue = function (source, destinationObject) {
  8782. if (!source)
  8783. return null;
  8784. if (source instanceof BABYLON.Mesh) {
  8785. return null;
  8786. }
  8787. if (source instanceof BABYLON.SubMesh) {
  8788. return source.clone(destinationObject);
  8789. }
  8790. else if (source.clone) {
  8791. return source.clone();
  8792. }
  8793. return null;
  8794. };
  8795. var Tools = /** @class */ (function () {
  8796. function Tools() {
  8797. }
  8798. /**
  8799. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8800. * @param u defines the coordinate on X axis
  8801. * @param v defines the coordinate on Y axis
  8802. * @param width defines the width of the source data
  8803. * @param height defines the height of the source data
  8804. * @param pixels defines the source byte array
  8805. * @param color defines the output color
  8806. */
  8807. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8808. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8809. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8810. var position = (wrappedU + wrappedV * width) * 4;
  8811. color.r = pixels[position] / 255;
  8812. color.g = pixels[position + 1] / 255;
  8813. color.b = pixels[position + 2] / 255;
  8814. color.a = pixels[position + 3] / 255;
  8815. };
  8816. /**
  8817. * Interpolates between a and b via alpha
  8818. * @param a The lower value (returned when alpha = 0)
  8819. * @param b The upper value (returned when alpha = 1)
  8820. * @param alpha The interpolation-factor
  8821. * @return The mixed value
  8822. */
  8823. Tools.Mix = function (a, b, alpha) {
  8824. return a * (1 - alpha) + b * alpha;
  8825. };
  8826. Tools.Instantiate = function (className) {
  8827. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8828. return Tools.RegisteredExternalClasses[className];
  8829. }
  8830. var arr = className.split(".");
  8831. var fn = (window || this);
  8832. for (var i = 0, len = arr.length; i < len; i++) {
  8833. fn = fn[arr[i]];
  8834. }
  8835. if (typeof fn !== "function") {
  8836. return null;
  8837. }
  8838. return fn;
  8839. };
  8840. /**
  8841. * Provides a slice function that will work even on IE
  8842. * @param data defines the array to slice
  8843. * @param start defines the start of the data (optional)
  8844. * @param end defines the end of the data (optional)
  8845. * @returns the new sliced array
  8846. */
  8847. Tools.Slice = function (data, start, end) {
  8848. if (data.slice) {
  8849. return data.slice(start, end);
  8850. }
  8851. return Array.prototype.slice.call(data, start, end);
  8852. };
  8853. Tools.SetImmediate = function (action) {
  8854. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8855. window.setImmediate(action);
  8856. }
  8857. else {
  8858. setTimeout(action, 1);
  8859. }
  8860. };
  8861. Tools.IsExponentOfTwo = function (value) {
  8862. var count = 1;
  8863. do {
  8864. count *= 2;
  8865. } while (count < value);
  8866. return count === value;
  8867. };
  8868. /**
  8869. * Returns the nearest 32-bit single precision float representation of a Number
  8870. * @param value A Number. If the parameter is of a different type, it will get converted
  8871. * to a number or to NaN if it cannot be converted
  8872. * @returns number
  8873. */
  8874. Tools.FloatRound = function (value) {
  8875. if (Math.fround) {
  8876. return Math.fround(value);
  8877. }
  8878. return (Tools._tmpFloatArray[0] = value);
  8879. };
  8880. /**
  8881. * Find the next highest power of two.
  8882. * @param x Number to start search from.
  8883. * @return Next highest power of two.
  8884. */
  8885. Tools.CeilingPOT = function (x) {
  8886. x--;
  8887. x |= x >> 1;
  8888. x |= x >> 2;
  8889. x |= x >> 4;
  8890. x |= x >> 8;
  8891. x |= x >> 16;
  8892. x++;
  8893. return x;
  8894. };
  8895. /**
  8896. * Find the next lowest power of two.
  8897. * @param x Number to start search from.
  8898. * @return Next lowest power of two.
  8899. */
  8900. Tools.FloorPOT = function (x) {
  8901. x = x | (x >> 1);
  8902. x = x | (x >> 2);
  8903. x = x | (x >> 4);
  8904. x = x | (x >> 8);
  8905. x = x | (x >> 16);
  8906. return x - (x >> 1);
  8907. };
  8908. /**
  8909. * Find the nearest power of two.
  8910. * @param x Number to start search from.
  8911. * @return Next nearest power of two.
  8912. */
  8913. Tools.NearestPOT = function (x) {
  8914. var c = Tools.CeilingPOT(x);
  8915. var f = Tools.FloorPOT(x);
  8916. return (c - x) > (x - f) ? f : c;
  8917. };
  8918. Tools.GetExponentOfTwo = function (value, max, mode) {
  8919. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8920. var pot;
  8921. switch (mode) {
  8922. case BABYLON.Engine.SCALEMODE_FLOOR:
  8923. pot = Tools.FloorPOT(value);
  8924. break;
  8925. case BABYLON.Engine.SCALEMODE_NEAREST:
  8926. pot = Tools.NearestPOT(value);
  8927. break;
  8928. case BABYLON.Engine.SCALEMODE_CEILING:
  8929. default:
  8930. pot = Tools.CeilingPOT(value);
  8931. break;
  8932. }
  8933. return Math.min(pot, max);
  8934. };
  8935. Tools.GetFilename = function (path) {
  8936. var index = path.lastIndexOf("/");
  8937. if (index < 0)
  8938. return path;
  8939. return path.substring(index + 1);
  8940. };
  8941. /**
  8942. * Extracts the "folder" part of a path (everything before the filename).
  8943. * @param uri The URI to extract the info from
  8944. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8945. * @returns The "folder" part of the path
  8946. */
  8947. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8948. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8949. var index = uri.lastIndexOf("/");
  8950. if (index < 0) {
  8951. if (returnUnchangedIfNoSlash) {
  8952. return uri;
  8953. }
  8954. return "";
  8955. }
  8956. return uri.substring(0, index + 1);
  8957. };
  8958. Tools.GetDOMTextContent = function (element) {
  8959. var result = "";
  8960. var child = element.firstChild;
  8961. while (child) {
  8962. if (child.nodeType === 3) {
  8963. result += child.textContent;
  8964. }
  8965. child = child.nextSibling;
  8966. }
  8967. return result;
  8968. };
  8969. Tools.ToDegrees = function (angle) {
  8970. return angle * 180 / Math.PI;
  8971. };
  8972. Tools.ToRadians = function (angle) {
  8973. return angle * Math.PI / 180;
  8974. };
  8975. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8976. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8977. var output = "";
  8978. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8979. var i = 0;
  8980. var bytes = new Uint8Array(buffer);
  8981. while (i < bytes.length) {
  8982. chr1 = bytes[i++];
  8983. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8984. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8985. enc1 = chr1 >> 2;
  8986. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8987. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8988. enc4 = chr3 & 63;
  8989. if (isNaN(chr2)) {
  8990. enc3 = enc4 = 64;
  8991. }
  8992. else if (isNaN(chr3)) {
  8993. enc4 = 64;
  8994. }
  8995. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8996. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8997. }
  8998. return "data:image/png;base64," + output;
  8999. };
  9000. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9001. if (bias === void 0) { bias = null; }
  9002. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9003. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9004. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9005. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9006. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9007. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9008. }
  9009. if (bias) {
  9010. minimum.x -= minimum.x * bias.x + bias.y;
  9011. minimum.y -= minimum.y * bias.x + bias.y;
  9012. minimum.z -= minimum.z * bias.x + bias.y;
  9013. maximum.x += maximum.x * bias.x + bias.y;
  9014. maximum.y += maximum.y * bias.x + bias.y;
  9015. maximum.z += maximum.z * bias.x + bias.y;
  9016. }
  9017. return {
  9018. minimum: minimum,
  9019. maximum: maximum
  9020. };
  9021. };
  9022. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9023. if (bias === void 0) { bias = null; }
  9024. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9025. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9026. if (!stride) {
  9027. stride = 3;
  9028. }
  9029. for (var index = start; index < start + count; index++) {
  9030. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9031. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9032. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9033. }
  9034. if (bias) {
  9035. minimum.x -= minimum.x * bias.x + bias.y;
  9036. minimum.y -= minimum.y * bias.x + bias.y;
  9037. minimum.z -= minimum.z * bias.x + bias.y;
  9038. maximum.x += maximum.x * bias.x + bias.y;
  9039. maximum.y += maximum.y * bias.x + bias.y;
  9040. maximum.z += maximum.z * bias.x + bias.y;
  9041. }
  9042. return {
  9043. minimum: minimum,
  9044. maximum: maximum
  9045. };
  9046. };
  9047. Tools.Vector2ArrayFeeder = function (array) {
  9048. return function (index) {
  9049. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9050. var length = isFloatArray ? array.length / 2 : array.length;
  9051. if (index >= length) {
  9052. return null;
  9053. }
  9054. if (isFloatArray) {
  9055. var fa = array;
  9056. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9057. }
  9058. var a = array;
  9059. return a[index];
  9060. };
  9061. };
  9062. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9063. if (bias === void 0) { bias = null; }
  9064. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9065. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9066. var i = 0;
  9067. var cur = feeder(i++);
  9068. while (cur) {
  9069. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9070. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9071. cur = feeder(i++);
  9072. }
  9073. if (bias) {
  9074. minimum.x -= minimum.x * bias.x + bias.y;
  9075. minimum.y -= minimum.y * bias.x + bias.y;
  9076. maximum.x += maximum.x * bias.x + bias.y;
  9077. maximum.y += maximum.y * bias.x + bias.y;
  9078. }
  9079. return {
  9080. minimum: minimum,
  9081. maximum: maximum
  9082. };
  9083. };
  9084. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9085. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9086. return null;
  9087. return Array.isArray(obj) ? obj : [obj];
  9088. };
  9089. // Misc.
  9090. Tools.GetPointerPrefix = function () {
  9091. var eventPrefix = "pointer";
  9092. // Check if pointer events are supported
  9093. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9094. eventPrefix = "mouse";
  9095. }
  9096. return eventPrefix;
  9097. };
  9098. /**
  9099. * @param func - the function to be called
  9100. * @param requester - the object that will request the next frame. Falls back to window.
  9101. */
  9102. Tools.QueueNewFrame = function (func, requester) {
  9103. if (!Tools.IsWindowObjectExist()) {
  9104. return setTimeout(func, 16);
  9105. }
  9106. if (!requester) {
  9107. requester = window;
  9108. }
  9109. if (requester.requestAnimationFrame) {
  9110. return requester.requestAnimationFrame(func);
  9111. }
  9112. else if (requester.msRequestAnimationFrame) {
  9113. return requester.msRequestAnimationFrame(func);
  9114. }
  9115. else if (requester.webkitRequestAnimationFrame) {
  9116. return requester.webkitRequestAnimationFrame(func);
  9117. }
  9118. else if (requester.mozRequestAnimationFrame) {
  9119. return requester.mozRequestAnimationFrame(func);
  9120. }
  9121. else if (requester.oRequestAnimationFrame) {
  9122. return requester.oRequestAnimationFrame(func);
  9123. }
  9124. else {
  9125. return window.setTimeout(func, 16);
  9126. }
  9127. };
  9128. Tools.RequestFullscreen = function (element) {
  9129. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9130. if (!requestFunction)
  9131. return;
  9132. requestFunction.call(element);
  9133. };
  9134. Tools.ExitFullscreen = function () {
  9135. if (document.exitFullscreen) {
  9136. document.exitFullscreen();
  9137. }
  9138. else if (document.mozCancelFullScreen) {
  9139. document.mozCancelFullScreen();
  9140. }
  9141. else if (document.webkitCancelFullScreen) {
  9142. document.webkitCancelFullScreen();
  9143. }
  9144. else if (document.msCancelFullScreen) {
  9145. document.msCancelFullScreen();
  9146. }
  9147. };
  9148. Tools.SetCorsBehavior = function (url, element) {
  9149. if (url && url.indexOf("data:") === 0) {
  9150. return;
  9151. }
  9152. if (Tools.CorsBehavior) {
  9153. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9154. element.crossOrigin = Tools.CorsBehavior;
  9155. }
  9156. else {
  9157. var result = Tools.CorsBehavior(url);
  9158. if (result) {
  9159. element.crossOrigin = result;
  9160. }
  9161. }
  9162. }
  9163. };
  9164. // External files
  9165. Tools.CleanUrl = function (url) {
  9166. url = url.replace(/#/mg, "%23");
  9167. return url;
  9168. };
  9169. /**
  9170. * Loads an image as an HTMLImageElement.
  9171. * @param input url string, ArrayBuffer, or Blob to load
  9172. * @param onLoad callback called when the image successfully loads
  9173. * @param onError callback called when the image fails to load
  9174. * @param database database for caching
  9175. * @returns the HTMLImageElement of the loaded image
  9176. */
  9177. Tools.LoadImage = function (input, onLoad, onError, database) {
  9178. var url;
  9179. var usingObjectURL = false;
  9180. if (input instanceof ArrayBuffer) {
  9181. url = URL.createObjectURL(new Blob([input]));
  9182. usingObjectURL = true;
  9183. }
  9184. else if (input instanceof Blob) {
  9185. url = URL.createObjectURL(input);
  9186. usingObjectURL = true;
  9187. }
  9188. else {
  9189. url = Tools.CleanUrl(input);
  9190. url = Tools.PreprocessUrl(input);
  9191. }
  9192. var img = new Image();
  9193. Tools.SetCorsBehavior(url, img);
  9194. var loadHandler = function () {
  9195. if (usingObjectURL && img.src) {
  9196. URL.revokeObjectURL(img.src);
  9197. }
  9198. img.removeEventListener("load", loadHandler);
  9199. img.removeEventListener("error", errorHandler);
  9200. onLoad(img);
  9201. };
  9202. var errorHandler = function (err) {
  9203. if (usingObjectURL && img.src) {
  9204. URL.revokeObjectURL(img.src);
  9205. }
  9206. img.removeEventListener("load", loadHandler);
  9207. img.removeEventListener("error", errorHandler);
  9208. Tools.Error("Error while trying to load image: " + input);
  9209. if (onError) {
  9210. onError("Error while trying to load image: " + input, err);
  9211. }
  9212. };
  9213. img.addEventListener("load", loadHandler);
  9214. img.addEventListener("error", errorHandler);
  9215. var noIndexedDB = function () {
  9216. img.src = url;
  9217. };
  9218. var loadFromIndexedDB = function () {
  9219. if (database) {
  9220. database.loadImageFromDB(url, img);
  9221. }
  9222. };
  9223. //ANY database to do!
  9224. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9225. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9226. }
  9227. else {
  9228. if (url.indexOf("file:") !== -1) {
  9229. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9230. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9231. try {
  9232. var blobURL;
  9233. try {
  9234. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9235. }
  9236. catch (ex) {
  9237. // Chrome doesn't support oneTimeOnly parameter
  9238. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9239. }
  9240. img.src = blobURL;
  9241. usingObjectURL = true;
  9242. }
  9243. catch (e) {
  9244. img.src = "";
  9245. }
  9246. return img;
  9247. }
  9248. }
  9249. noIndexedDB();
  9250. }
  9251. return img;
  9252. };
  9253. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9254. url = Tools.CleanUrl(url);
  9255. url = Tools.PreprocessUrl(url);
  9256. // If file and file input are set
  9257. if (url.indexOf("file:") !== -1) {
  9258. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9259. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9260. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9261. }
  9262. }
  9263. var loadUrl = Tools.BaseUrl + url;
  9264. var aborted = false;
  9265. var fileRequest = {
  9266. onCompleteObservable: new BABYLON.Observable(),
  9267. abort: function () { return aborted = true; },
  9268. };
  9269. var requestFile = function () {
  9270. var request = new XMLHttpRequest();
  9271. var retryHandle = null;
  9272. fileRequest.abort = function () {
  9273. aborted = true;
  9274. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9275. request.abort();
  9276. }
  9277. if (retryHandle !== null) {
  9278. clearTimeout(retryHandle);
  9279. retryHandle = null;
  9280. }
  9281. };
  9282. var retryLoop = function (retryIndex) {
  9283. request.open('GET', loadUrl, true);
  9284. if (useArrayBuffer) {
  9285. request.responseType = "arraybuffer";
  9286. }
  9287. if (onProgress) {
  9288. request.addEventListener("progress", onProgress);
  9289. }
  9290. var onLoadEnd = function () {
  9291. request.removeEventListener("loadend", onLoadEnd);
  9292. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9293. fileRequest.onCompleteObservable.clear();
  9294. };
  9295. request.addEventListener("loadend", onLoadEnd);
  9296. var onReadyStateChange = function () {
  9297. if (aborted) {
  9298. return;
  9299. }
  9300. // In case of undefined state in some browsers.
  9301. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9302. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9303. request.removeEventListener("readystatechange", onReadyStateChange);
  9304. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9305. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9306. return;
  9307. }
  9308. var retryStrategy = Tools.DefaultRetryStrategy;
  9309. if (retryStrategy) {
  9310. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9311. if (waitTime !== -1) {
  9312. // Prevent the request from completing for retry.
  9313. request.removeEventListener("loadend", onLoadEnd);
  9314. request = new XMLHttpRequest();
  9315. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9316. return;
  9317. }
  9318. }
  9319. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9320. if (onError) {
  9321. onError(request, e);
  9322. }
  9323. else {
  9324. throw e;
  9325. }
  9326. }
  9327. };
  9328. request.addEventListener("readystatechange", onReadyStateChange);
  9329. request.send();
  9330. };
  9331. retryLoop(0);
  9332. };
  9333. // Caching all files
  9334. if (database && database.enableSceneOffline) {
  9335. var noIndexedDB_1 = function (request) {
  9336. if (request && request.status > 400) {
  9337. if (onError) {
  9338. onError(request);
  9339. }
  9340. }
  9341. else {
  9342. if (!aborted) {
  9343. requestFile();
  9344. }
  9345. }
  9346. };
  9347. var loadFromIndexedDB = function () {
  9348. // TODO: database needs to support aborting and should return a IFileRequest
  9349. if (aborted) {
  9350. return;
  9351. }
  9352. if (database) {
  9353. database.loadFileFromDB(url, function (data) {
  9354. if (!aborted) {
  9355. onSuccess(data);
  9356. }
  9357. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9358. }, onProgress ? function (event) {
  9359. if (!aborted) {
  9360. onProgress(event);
  9361. }
  9362. } : undefined, noIndexedDB_1, useArrayBuffer);
  9363. }
  9364. };
  9365. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9366. }
  9367. else {
  9368. requestFile();
  9369. }
  9370. return fileRequest;
  9371. };
  9372. /**
  9373. * Load a script (identified by an url). When the url returns, the
  9374. * content of this file is added into a new script element, attached to the DOM (body element)
  9375. */
  9376. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9377. if (!Tools.IsWindowObjectExist()) {
  9378. return;
  9379. }
  9380. var head = document.getElementsByTagName('head')[0];
  9381. var script = document.createElement('script');
  9382. script.type = 'text/javascript';
  9383. script.src = scriptUrl;
  9384. script.onload = function () {
  9385. if (onSuccess) {
  9386. onSuccess();
  9387. }
  9388. };
  9389. script.onerror = function (e) {
  9390. if (onError) {
  9391. onError("Unable to load script '" + scriptUrl + "'", e);
  9392. }
  9393. };
  9394. head.appendChild(script);
  9395. };
  9396. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9397. var reader = new FileReader();
  9398. var request = {
  9399. onCompleteObservable: new BABYLON.Observable(),
  9400. abort: function () { return reader.abort(); },
  9401. };
  9402. reader.onloadend = function (e) {
  9403. request.onCompleteObservable.notifyObservers(request);
  9404. };
  9405. reader.onload = function (e) {
  9406. //target doesn't have result from ts 1.3
  9407. callback(e.target['result']);
  9408. };
  9409. reader.onprogress = progressCallback;
  9410. reader.readAsDataURL(fileToLoad);
  9411. return request;
  9412. };
  9413. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9414. var reader = new FileReader();
  9415. var request = {
  9416. onCompleteObservable: new BABYLON.Observable(),
  9417. abort: function () { return reader.abort(); },
  9418. };
  9419. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9420. reader.onerror = function (e) {
  9421. Tools.Log("Error while reading file: " + fileToLoad.name);
  9422. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9423. };
  9424. reader.onload = function (e) {
  9425. //target doesn't have result from ts 1.3
  9426. callback(e.target['result']);
  9427. };
  9428. if (progressCallBack) {
  9429. reader.onprogress = progressCallBack;
  9430. }
  9431. if (!useArrayBuffer) {
  9432. // Asynchronous read
  9433. reader.readAsText(fileToLoad);
  9434. }
  9435. else {
  9436. reader.readAsArrayBuffer(fileToLoad);
  9437. }
  9438. return request;
  9439. };
  9440. //returns a downloadable url to a file content.
  9441. Tools.FileAsURL = function (content) {
  9442. var fileBlob = new Blob([content]);
  9443. var url = window.URL || window.webkitURL;
  9444. var link = url.createObjectURL(fileBlob);
  9445. return link;
  9446. };
  9447. // Misc.
  9448. Tools.Format = function (value, decimals) {
  9449. if (decimals === void 0) { decimals = 2; }
  9450. return value.toFixed(decimals);
  9451. };
  9452. Tools.CheckExtends = function (v, min, max) {
  9453. if (v.x < min.x)
  9454. min.x = v.x;
  9455. if (v.y < min.y)
  9456. min.y = v.y;
  9457. if (v.z < min.z)
  9458. min.z = v.z;
  9459. if (v.x > max.x)
  9460. max.x = v.x;
  9461. if (v.y > max.y)
  9462. max.y = v.y;
  9463. if (v.z > max.z)
  9464. max.z = v.z;
  9465. };
  9466. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9467. for (var prop in source) {
  9468. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9469. continue;
  9470. }
  9471. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9472. continue;
  9473. }
  9474. var sourceValue = source[prop];
  9475. var typeOfSourceValue = typeof sourceValue;
  9476. if (typeOfSourceValue === "function") {
  9477. continue;
  9478. }
  9479. try {
  9480. if (typeOfSourceValue === "object") {
  9481. if (sourceValue instanceof Array) {
  9482. destination[prop] = [];
  9483. if (sourceValue.length > 0) {
  9484. if (typeof sourceValue[0] == "object") {
  9485. for (var index = 0; index < sourceValue.length; index++) {
  9486. var clonedValue = cloneValue(sourceValue[index], destination);
  9487. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9488. destination[prop].push(clonedValue);
  9489. }
  9490. }
  9491. }
  9492. else {
  9493. destination[prop] = sourceValue.slice(0);
  9494. }
  9495. }
  9496. }
  9497. else {
  9498. destination[prop] = cloneValue(sourceValue, destination);
  9499. }
  9500. }
  9501. else {
  9502. destination[prop] = sourceValue;
  9503. }
  9504. }
  9505. catch (e) {
  9506. // Just ignore error (it could be because of a read-only property)
  9507. }
  9508. }
  9509. };
  9510. Tools.IsEmpty = function (obj) {
  9511. for (var i in obj) {
  9512. if (obj.hasOwnProperty(i)) {
  9513. return false;
  9514. }
  9515. }
  9516. return true;
  9517. };
  9518. Tools.RegisterTopRootEvents = function (events) {
  9519. for (var index = 0; index < events.length; index++) {
  9520. var event = events[index];
  9521. window.addEventListener(event.name, event.handler, false);
  9522. try {
  9523. if (window.parent) {
  9524. window.parent.addEventListener(event.name, event.handler, false);
  9525. }
  9526. }
  9527. catch (e) {
  9528. // Silently fails...
  9529. }
  9530. }
  9531. };
  9532. Tools.UnregisterTopRootEvents = function (events) {
  9533. for (var index = 0; index < events.length; index++) {
  9534. var event = events[index];
  9535. window.removeEventListener(event.name, event.handler);
  9536. try {
  9537. if (window.parent) {
  9538. window.parent.removeEventListener(event.name, event.handler);
  9539. }
  9540. }
  9541. catch (e) {
  9542. // Silently fails...
  9543. }
  9544. }
  9545. };
  9546. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9547. if (mimeType === void 0) { mimeType = "image/png"; }
  9548. // Read the contents of the framebuffer
  9549. var numberOfChannelsByLine = width * 4;
  9550. var halfHeight = height / 2;
  9551. //Reading datas from WebGL
  9552. var data = engine.readPixels(0, 0, width, height);
  9553. //To flip image on Y axis.
  9554. for (var i = 0; i < halfHeight; i++) {
  9555. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9556. var currentCell = j + i * numberOfChannelsByLine;
  9557. var targetLine = height - i - 1;
  9558. var targetCell = j + targetLine * numberOfChannelsByLine;
  9559. var temp = data[currentCell];
  9560. data[currentCell] = data[targetCell];
  9561. data[targetCell] = temp;
  9562. }
  9563. }
  9564. // Create a 2D canvas to store the result
  9565. if (!screenshotCanvas) {
  9566. screenshotCanvas = document.createElement('canvas');
  9567. }
  9568. screenshotCanvas.width = width;
  9569. screenshotCanvas.height = height;
  9570. var context = screenshotCanvas.getContext('2d');
  9571. if (context) {
  9572. // Copy the pixels to a 2D canvas
  9573. var imageData = context.createImageData(width, height);
  9574. var castData = (imageData.data);
  9575. castData.set(data);
  9576. context.putImageData(imageData, 0, 0);
  9577. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9578. }
  9579. };
  9580. /**
  9581. * Converts the canvas data to blob.
  9582. * This acts as a polyfill for browsers not supporting the to blob function.
  9583. * @param canvas Defines the canvas to extract the data from
  9584. * @param successCallback Defines the callback triggered once the data are available
  9585. * @param mimeType Defines the mime type of the result
  9586. */
  9587. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9588. if (mimeType === void 0) { mimeType = "image/png"; }
  9589. // We need HTMLCanvasElement.toBlob for HD screenshots
  9590. if (!canvas.toBlob) {
  9591. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9592. canvas.toBlob = function (callback, type, quality) {
  9593. var _this = this;
  9594. setTimeout(function () {
  9595. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9596. for (var i = 0; i < len; i++) {
  9597. arr[i] = binStr.charCodeAt(i);
  9598. }
  9599. callback(new Blob([arr]));
  9600. });
  9601. };
  9602. }
  9603. canvas.toBlob(function (blob) {
  9604. successCallback(blob);
  9605. }, mimeType);
  9606. };
  9607. /**
  9608. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9609. * @param successCallback Defines the callback triggered once the data are available
  9610. * @param mimeType Defines the mime type of the result
  9611. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9612. */
  9613. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9614. if (mimeType === void 0) { mimeType = "image/png"; }
  9615. if (successCallback) {
  9616. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9617. successCallback(base64Image);
  9618. }
  9619. else {
  9620. this.ToBlob(screenshotCanvas, function (blob) {
  9621. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9622. if (("download" in document.createElement("a"))) {
  9623. if (!fileName) {
  9624. var date = new Date();
  9625. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9626. fileName = "screenshot_" + stringDate + ".png";
  9627. }
  9628. Tools.Download(blob, fileName);
  9629. }
  9630. else {
  9631. var url = URL.createObjectURL(blob);
  9632. var newWindow = window.open("");
  9633. if (!newWindow)
  9634. return;
  9635. var img = newWindow.document.createElement("img");
  9636. img.onload = function () {
  9637. // no longer need to read the blob so it's revoked
  9638. URL.revokeObjectURL(url);
  9639. };
  9640. img.src = url;
  9641. newWindow.document.body.appendChild(img);
  9642. }
  9643. }, mimeType);
  9644. }
  9645. };
  9646. /**
  9647. * Downloads a blob in the browser
  9648. * @param blob defines the blob to download
  9649. * @param fileName defines the name of the downloaded file
  9650. */
  9651. Tools.Download = function (blob, fileName) {
  9652. if (navigator && navigator.msSaveBlob) {
  9653. navigator.msSaveBlob(blob, fileName);
  9654. return;
  9655. }
  9656. var url = window.URL.createObjectURL(blob);
  9657. var a = document.createElement("a");
  9658. document.body.appendChild(a);
  9659. a.style.display = "none";
  9660. a.href = url;
  9661. a.download = fileName;
  9662. a.addEventListener("click", function () {
  9663. if (a.parentElement) {
  9664. a.parentElement.removeChild(a);
  9665. }
  9666. });
  9667. a.click();
  9668. window.URL.revokeObjectURL(url);
  9669. };
  9670. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9671. if (mimeType === void 0) { mimeType = "image/png"; }
  9672. var width;
  9673. var height;
  9674. // If a precision value is specified
  9675. if (size.precision) {
  9676. width = Math.round(engine.getRenderWidth() * size.precision);
  9677. height = Math.round(width / engine.getAspectRatio(camera));
  9678. }
  9679. else if (size.width && size.height) {
  9680. width = size.width;
  9681. height = size.height;
  9682. }
  9683. //If passing only width, computing height to keep display canvas ratio.
  9684. else if (size.width && !size.height) {
  9685. width = size.width;
  9686. height = Math.round(width / engine.getAspectRatio(camera));
  9687. }
  9688. //If passing only height, computing width to keep display canvas ratio.
  9689. else if (size.height && !size.width) {
  9690. height = size.height;
  9691. width = Math.round(height * engine.getAspectRatio(camera));
  9692. }
  9693. //Assuming here that "size" parameter is a number
  9694. else if (!isNaN(size)) {
  9695. height = size;
  9696. width = size;
  9697. }
  9698. else {
  9699. Tools.Error("Invalid 'size' parameter !");
  9700. return;
  9701. }
  9702. if (!screenshotCanvas) {
  9703. screenshotCanvas = document.createElement('canvas');
  9704. }
  9705. screenshotCanvas.width = width;
  9706. screenshotCanvas.height = height;
  9707. var renderContext = screenshotCanvas.getContext("2d");
  9708. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9709. var newWidth = width;
  9710. var newHeight = newWidth / ratio;
  9711. if (newHeight > height) {
  9712. newHeight = height;
  9713. newWidth = newHeight * ratio;
  9714. }
  9715. var offsetX = Math.max(0, width - newWidth) / 2;
  9716. var offsetY = Math.max(0, height - newHeight) / 2;
  9717. var renderingCanvas = engine.getRenderingCanvas();
  9718. if (renderContext && renderingCanvas) {
  9719. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9720. }
  9721. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9722. };
  9723. /**
  9724. * Generates an image screenshot from the specified camera.
  9725. *
  9726. * @param engine The engine to use for rendering
  9727. * @param camera The camera to use for rendering
  9728. * @param size This parameter can be set to a single number or to an object with the
  9729. * following (optional) properties: precision, width, height. If a single number is passed,
  9730. * it will be used for both width and height. If an object is passed, the screenshot size
  9731. * will be derived from the parameters. The precision property is a multiplier allowing
  9732. * rendering at a higher or lower resolution.
  9733. * @param successCallback The callback receives a single parameter which contains the
  9734. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9735. * src parameter of an <img> to display it.
  9736. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9737. * Check your browser for supported MIME types.
  9738. * @param samples Texture samples (default: 1)
  9739. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9740. * @param fileName A name for for the downloaded file.
  9741. * @constructor
  9742. */
  9743. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9744. if (mimeType === void 0) { mimeType = "image/png"; }
  9745. if (samples === void 0) { samples = 1; }
  9746. if (antialiasing === void 0) { antialiasing = false; }
  9747. var width;
  9748. var height;
  9749. //If a precision value is specified
  9750. if (size.precision) {
  9751. width = Math.round(engine.getRenderWidth() * size.precision);
  9752. height = Math.round(width / engine.getAspectRatio(camera));
  9753. size = { width: width, height: height };
  9754. }
  9755. else if (size.width && size.height) {
  9756. width = size.width;
  9757. height = size.height;
  9758. }
  9759. //If passing only width, computing height to keep display canvas ratio.
  9760. else if (size.width && !size.height) {
  9761. width = size.width;
  9762. height = Math.round(width / engine.getAspectRatio(camera));
  9763. size = { width: width, height: height };
  9764. }
  9765. //If passing only height, computing width to keep display canvas ratio.
  9766. else if (size.height && !size.width) {
  9767. height = size.height;
  9768. width = Math.round(height * engine.getAspectRatio(camera));
  9769. size = { width: width, height: height };
  9770. }
  9771. //Assuming here that "size" parameter is a number
  9772. else if (!isNaN(size)) {
  9773. height = size;
  9774. width = size;
  9775. }
  9776. else {
  9777. Tools.Error("Invalid 'size' parameter !");
  9778. return;
  9779. }
  9780. var scene = camera.getScene();
  9781. var previousCamera = null;
  9782. if (scene.activeCamera !== camera) {
  9783. previousCamera = scene.activeCamera;
  9784. scene.activeCamera = camera;
  9785. }
  9786. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9787. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9788. texture.renderList = null;
  9789. texture.samples = samples;
  9790. if (antialiasing) {
  9791. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9792. }
  9793. texture.onAfterRenderObservable.add(function () {
  9794. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9795. });
  9796. scene.incrementRenderId();
  9797. scene.resetCachedMaterial();
  9798. texture.render(true);
  9799. texture.dispose();
  9800. if (previousCamera) {
  9801. scene.activeCamera = previousCamera;
  9802. }
  9803. camera.getProjectionMatrix(true); // Force cache refresh;
  9804. };
  9805. // XHR response validator for local file scenario
  9806. Tools.ValidateXHRData = function (xhr, dataType) {
  9807. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9808. if (dataType === void 0) { dataType = 7; }
  9809. try {
  9810. if (dataType & 1) {
  9811. if (xhr.responseText && xhr.responseText.length > 0) {
  9812. return true;
  9813. }
  9814. else if (dataType === 1) {
  9815. return false;
  9816. }
  9817. }
  9818. if (dataType & 2) {
  9819. // Check header width and height since there is no "TGA" magic number
  9820. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9821. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9822. return true;
  9823. }
  9824. else if (dataType === 2) {
  9825. return false;
  9826. }
  9827. }
  9828. if (dataType & 4) {
  9829. // Check for the "DDS" magic number
  9830. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9831. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9832. return true;
  9833. }
  9834. else {
  9835. return false;
  9836. }
  9837. }
  9838. }
  9839. catch (e) {
  9840. // Global protection
  9841. }
  9842. return false;
  9843. };
  9844. /**
  9845. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9846. * Be aware Math.random() could cause collisions, but:
  9847. * "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"
  9848. */
  9849. Tools.RandomId = function () {
  9850. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9851. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9852. return v.toString(16);
  9853. });
  9854. };
  9855. /**
  9856. * Test if the given uri is a base64 string.
  9857. * @param uri The uri to test
  9858. * @return True if the uri is a base64 string or false otherwise.
  9859. */
  9860. Tools.IsBase64 = function (uri) {
  9861. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9862. };
  9863. /**
  9864. * Decode the given base64 uri.
  9865. * @param uri The uri to decode
  9866. * @return The decoded base64 data.
  9867. */
  9868. Tools.DecodeBase64 = function (uri) {
  9869. var decodedString = atob(uri.split(",")[1]);
  9870. var bufferLength = decodedString.length;
  9871. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9872. for (var i = 0; i < bufferLength; i++) {
  9873. bufferView[i] = decodedString.charCodeAt(i);
  9874. }
  9875. return bufferView.buffer;
  9876. };
  9877. Object.defineProperty(Tools, "NoneLogLevel", {
  9878. get: function () {
  9879. return Tools._NoneLogLevel;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Tools, "MessageLogLevel", {
  9885. get: function () {
  9886. return Tools._MessageLogLevel;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Tools, "WarningLogLevel", {
  9892. get: function () {
  9893. return Tools._WarningLogLevel;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Tools, "ErrorLogLevel", {
  9899. get: function () {
  9900. return Tools._ErrorLogLevel;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Tools, "AllLogLevel", {
  9906. get: function () {
  9907. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Tools._AddLogEntry = function (entry) {
  9913. Tools._LogCache = entry + Tools._LogCache;
  9914. if (Tools.OnNewCacheEntry) {
  9915. Tools.OnNewCacheEntry(entry);
  9916. }
  9917. };
  9918. Tools._FormatMessage = function (message) {
  9919. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9920. var date = new Date();
  9921. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9922. };
  9923. Tools._LogDisabled = function (message) {
  9924. // nothing to do
  9925. };
  9926. Tools._LogEnabled = function (message) {
  9927. var formattedMessage = Tools._FormatMessage(message);
  9928. console.log("BJS - " + formattedMessage);
  9929. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9930. Tools._AddLogEntry(entry);
  9931. };
  9932. Tools._WarnDisabled = function (message) {
  9933. // nothing to do
  9934. };
  9935. Tools._WarnEnabled = function (message) {
  9936. var formattedMessage = Tools._FormatMessage(message);
  9937. console.warn("BJS - " + formattedMessage);
  9938. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9939. Tools._AddLogEntry(entry);
  9940. };
  9941. Tools._ErrorDisabled = function (message) {
  9942. // nothing to do
  9943. };
  9944. Tools._ErrorEnabled = function (message) {
  9945. Tools.errorsCount++;
  9946. var formattedMessage = Tools._FormatMessage(message);
  9947. console.error("BJS - " + formattedMessage);
  9948. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9949. Tools._AddLogEntry(entry);
  9950. };
  9951. Object.defineProperty(Tools, "LogCache", {
  9952. get: function () {
  9953. return Tools._LogCache;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Tools.ClearLogCache = function () {
  9959. Tools._LogCache = "";
  9960. Tools.errorsCount = 0;
  9961. };
  9962. Object.defineProperty(Tools, "LogLevels", {
  9963. set: function (level) {
  9964. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9965. Tools.Log = Tools._LogEnabled;
  9966. }
  9967. else {
  9968. Tools.Log = Tools._LogDisabled;
  9969. }
  9970. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9971. Tools.Warn = Tools._WarnEnabled;
  9972. }
  9973. else {
  9974. Tools.Warn = Tools._WarnDisabled;
  9975. }
  9976. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9977. Tools.Error = Tools._ErrorEnabled;
  9978. }
  9979. else {
  9980. Tools.Error = Tools._ErrorDisabled;
  9981. }
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. /**
  9987. * Check if the loaded document was accessed via `file:`-Protocol.
  9988. * @returns boolean
  9989. */
  9990. Tools.IsFileURL = function () {
  9991. return location.protocol === "file:";
  9992. };
  9993. Tools.IsWindowObjectExist = function () {
  9994. return (typeof window) !== "undefined";
  9995. };
  9996. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9997. get: function () {
  9998. return Tools._PerformanceNoneLogLevel;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  10004. get: function () {
  10005. return Tools._PerformanceUserMarkLogLevel;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  10011. get: function () {
  10012. return Tools._PerformanceConsoleLogLevel;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10018. set: function (level) {
  10019. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10020. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10021. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10022. return;
  10023. }
  10024. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10025. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10026. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10027. return;
  10028. }
  10029. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10030. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10031. },
  10032. enumerable: true,
  10033. configurable: true
  10034. });
  10035. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10036. };
  10037. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10038. };
  10039. Tools._StartUserMark = function (counterName, condition) {
  10040. if (condition === void 0) { condition = true; }
  10041. if (!Tools._performance) {
  10042. if (!Tools.IsWindowObjectExist()) {
  10043. return;
  10044. }
  10045. Tools._performance = window.performance;
  10046. }
  10047. if (!condition || !Tools._performance.mark) {
  10048. return;
  10049. }
  10050. Tools._performance.mark(counterName + "-Begin");
  10051. };
  10052. Tools._EndUserMark = function (counterName, condition) {
  10053. if (condition === void 0) { condition = true; }
  10054. if (!condition || !Tools._performance.mark) {
  10055. return;
  10056. }
  10057. Tools._performance.mark(counterName + "-End");
  10058. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10059. };
  10060. Tools._StartPerformanceConsole = function (counterName, condition) {
  10061. if (condition === void 0) { condition = true; }
  10062. if (!condition) {
  10063. return;
  10064. }
  10065. Tools._StartUserMark(counterName, condition);
  10066. if (console.time) {
  10067. console.time(counterName);
  10068. }
  10069. };
  10070. Tools._EndPerformanceConsole = function (counterName, condition) {
  10071. if (condition === void 0) { condition = true; }
  10072. if (!condition) {
  10073. return;
  10074. }
  10075. Tools._EndUserMark(counterName, condition);
  10076. if (console.time) {
  10077. console.timeEnd(counterName);
  10078. }
  10079. };
  10080. Object.defineProperty(Tools, "Now", {
  10081. get: function () {
  10082. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10083. return window.performance.now();
  10084. }
  10085. return Date.now();
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. /**
  10091. * This method will return the name of the class used to create the instance of the given object.
  10092. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10093. * @param object the object to get the class name from
  10094. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10095. */
  10096. Tools.GetClassName = function (object, isType) {
  10097. if (isType === void 0) { isType = false; }
  10098. var name = null;
  10099. if (!isType && object.getClassName) {
  10100. name = object.getClassName();
  10101. }
  10102. else {
  10103. if (object instanceof Object) {
  10104. var classObj = isType ? object : Object.getPrototypeOf(object);
  10105. name = classObj.constructor["__bjsclassName__"];
  10106. }
  10107. if (!name) {
  10108. name = typeof object;
  10109. }
  10110. }
  10111. return name;
  10112. };
  10113. Tools.First = function (array, predicate) {
  10114. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10115. var el = array_1[_i];
  10116. if (predicate(el)) {
  10117. return el;
  10118. }
  10119. }
  10120. return null;
  10121. };
  10122. /**
  10123. * This method will return the name of the full name of the class, including its owning module (if any).
  10124. * 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).
  10125. * @param object the object to get the class name from
  10126. * @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.
  10127. */
  10128. Tools.getFullClassName = function (object, isType) {
  10129. if (isType === void 0) { isType = false; }
  10130. var className = null;
  10131. var moduleName = null;
  10132. if (!isType && object.getClassName) {
  10133. className = object.getClassName();
  10134. }
  10135. else {
  10136. if (object instanceof Object) {
  10137. var classObj = isType ? object : Object.getPrototypeOf(object);
  10138. className = classObj.constructor["__bjsclassName__"];
  10139. moduleName = classObj.constructor["__bjsmoduleName__"];
  10140. }
  10141. if (!className) {
  10142. className = typeof object;
  10143. }
  10144. }
  10145. if (!className) {
  10146. return null;
  10147. }
  10148. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10149. };
  10150. /**
  10151. * 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.
  10152. * @param array
  10153. */
  10154. Tools.arrayOrStringFeeder = function (array) {
  10155. return function (index) {
  10156. if (index >= array.length) {
  10157. return null;
  10158. }
  10159. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10160. if (val && val.getHashCode) {
  10161. val = val.getHashCode();
  10162. }
  10163. if (typeof val === "string") {
  10164. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10165. }
  10166. return val;
  10167. };
  10168. };
  10169. /**
  10170. * Compute the hashCode of a stream of number
  10171. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10172. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10173. * @return the hash code computed
  10174. */
  10175. Tools.hashCodeFromStream = function (feeder) {
  10176. // Based from here: http://stackoverflow.com/a/7616484/802124
  10177. var hash = 0;
  10178. var index = 0;
  10179. var chr = feeder(index++);
  10180. while (chr != null) {
  10181. hash = ((hash << 5) - hash) + chr;
  10182. hash |= 0; // Convert to 32bit integer
  10183. chr = feeder(index++);
  10184. }
  10185. return hash;
  10186. };
  10187. /**
  10188. * Returns a promise that resolves after the given amount of time.
  10189. * @param delay Number of milliseconds to delay
  10190. * @returns Promise that resolves after the given amount of time
  10191. */
  10192. Tools.DelayAsync = function (delay) {
  10193. return new Promise(function (resolve) {
  10194. setTimeout(function () {
  10195. resolve();
  10196. }, delay);
  10197. });
  10198. };
  10199. /**
  10200. * Gets the current gradient from an array of IValueGradient
  10201. * @param ratio defines the current ratio to get
  10202. * @param gradients defines the array of IValueGradient
  10203. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10204. */
  10205. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10206. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10207. var currentGradient = gradients[gradientIndex];
  10208. var nextGradient = gradients[gradientIndex + 1];
  10209. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10210. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10211. updateFunc(currentGradient, nextGradient, scale);
  10212. return;
  10213. }
  10214. }
  10215. // Use last index if over
  10216. var lastIndex = gradients.length - 1;
  10217. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10218. };
  10219. Tools.BaseUrl = "";
  10220. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10221. /**
  10222. * Default behaviour for cors in the application.
  10223. * It can be a string if the expected behavior is identical in the entire app.
  10224. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10225. */
  10226. Tools.CorsBehavior = "anonymous";
  10227. Tools.UseFallbackTexture = true;
  10228. /**
  10229. * Use this object to register external classes like custom textures or material
  10230. * to allow the laoders to instantiate them
  10231. */
  10232. Tools.RegisteredExternalClasses = {};
  10233. // Used in case of a texture loading problem
  10234. 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";
  10235. Tools._tmpFloatArray = new Float32Array(1);
  10236. Tools.PreprocessUrl = function (url) {
  10237. return url;
  10238. };
  10239. // Logs
  10240. Tools._NoneLogLevel = 0;
  10241. Tools._MessageLogLevel = 1;
  10242. Tools._WarningLogLevel = 2;
  10243. Tools._ErrorLogLevel = 4;
  10244. Tools._LogCache = "";
  10245. Tools.errorsCount = 0;
  10246. Tools.Log = Tools._LogEnabled;
  10247. Tools.Warn = Tools._WarnEnabled;
  10248. Tools.Error = Tools._ErrorEnabled;
  10249. // Performances
  10250. Tools._PerformanceNoneLogLevel = 0;
  10251. Tools._PerformanceUserMarkLogLevel = 1;
  10252. Tools._PerformanceConsoleLogLevel = 2;
  10253. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10254. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10255. return Tools;
  10256. }());
  10257. BABYLON.Tools = Tools;
  10258. /**
  10259. * This class is used to track a performance counter which is number based.
  10260. * The user has access to many properties which give statistics of different nature
  10261. *
  10262. * The implementer can track two kinds of Performance Counter: time and count
  10263. * 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.
  10264. * 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.
  10265. */
  10266. var PerfCounter = /** @class */ (function () {
  10267. function PerfCounter() {
  10268. this._startMonitoringTime = 0;
  10269. this._min = 0;
  10270. this._max = 0;
  10271. this._average = 0;
  10272. this._lastSecAverage = 0;
  10273. this._current = 0;
  10274. this._totalValueCount = 0;
  10275. this._totalAccumulated = 0;
  10276. this._lastSecAccumulated = 0;
  10277. this._lastSecTime = 0;
  10278. this._lastSecValueCount = 0;
  10279. }
  10280. Object.defineProperty(PerfCounter.prototype, "min", {
  10281. /**
  10282. * Returns the smallest value ever
  10283. */
  10284. get: function () {
  10285. return this._min;
  10286. },
  10287. enumerable: true,
  10288. configurable: true
  10289. });
  10290. Object.defineProperty(PerfCounter.prototype, "max", {
  10291. /**
  10292. * Returns the biggest value ever
  10293. */
  10294. get: function () {
  10295. return this._max;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(PerfCounter.prototype, "average", {
  10301. /**
  10302. * Returns the average value since the performance counter is running
  10303. */
  10304. get: function () {
  10305. return this._average;
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10311. /**
  10312. * Returns the average value of the last second the counter was monitored
  10313. */
  10314. get: function () {
  10315. return this._lastSecAverage;
  10316. },
  10317. enumerable: true,
  10318. configurable: true
  10319. });
  10320. Object.defineProperty(PerfCounter.prototype, "current", {
  10321. /**
  10322. * Returns the current value
  10323. */
  10324. get: function () {
  10325. return this._current;
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. Object.defineProperty(PerfCounter.prototype, "total", {
  10331. get: function () {
  10332. return this._totalAccumulated;
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. Object.defineProperty(PerfCounter.prototype, "count", {
  10338. get: function () {
  10339. return this._totalValueCount;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. /**
  10345. * Call this method to start monitoring a new frame.
  10346. * 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.
  10347. */
  10348. PerfCounter.prototype.fetchNewFrame = function () {
  10349. this._totalValueCount++;
  10350. this._current = 0;
  10351. this._lastSecValueCount++;
  10352. };
  10353. /**
  10354. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10355. * @param newCount the count value to add to the monitored count
  10356. * @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.
  10357. */
  10358. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10359. if (!PerfCounter.Enabled) {
  10360. return;
  10361. }
  10362. this._current += newCount;
  10363. if (fetchResult) {
  10364. this._fetchResult();
  10365. }
  10366. };
  10367. /**
  10368. * Start monitoring this performance counter
  10369. */
  10370. PerfCounter.prototype.beginMonitoring = function () {
  10371. if (!PerfCounter.Enabled) {
  10372. return;
  10373. }
  10374. this._startMonitoringTime = Tools.Now;
  10375. };
  10376. /**
  10377. * Compute the time lapsed since the previous beginMonitoring() call.
  10378. * @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
  10379. */
  10380. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10381. if (newFrame === void 0) { newFrame = true; }
  10382. if (!PerfCounter.Enabled) {
  10383. return;
  10384. }
  10385. if (newFrame) {
  10386. this.fetchNewFrame();
  10387. }
  10388. var currentTime = Tools.Now;
  10389. this._current = currentTime - this._startMonitoringTime;
  10390. if (newFrame) {
  10391. this._fetchResult();
  10392. }
  10393. };
  10394. PerfCounter.prototype._fetchResult = function () {
  10395. this._totalAccumulated += this._current;
  10396. this._lastSecAccumulated += this._current;
  10397. // Min/Max update
  10398. this._min = Math.min(this._min, this._current);
  10399. this._max = Math.max(this._max, this._current);
  10400. this._average = this._totalAccumulated / this._totalValueCount;
  10401. // Reset last sec?
  10402. var now = Tools.Now;
  10403. if ((now - this._lastSecTime) > 1000) {
  10404. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10405. this._lastSecTime = now;
  10406. this._lastSecAccumulated = 0;
  10407. this._lastSecValueCount = 0;
  10408. }
  10409. };
  10410. PerfCounter.Enabled = true;
  10411. return PerfCounter;
  10412. }());
  10413. BABYLON.PerfCounter = PerfCounter;
  10414. /**
  10415. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10416. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10417. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10418. * @param name The name of the class, case should be preserved
  10419. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10420. */
  10421. function className(name, module) {
  10422. return function (target) {
  10423. target["__bjsclassName__"] = name;
  10424. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10425. };
  10426. }
  10427. BABYLON.className = className;
  10428. /**
  10429. * An implementation of a loop for asynchronous functions.
  10430. */
  10431. var AsyncLoop = /** @class */ (function () {
  10432. /**
  10433. * Constructor.
  10434. * @param iterations the number of iterations.
  10435. * @param func the function to run each iteration
  10436. * @param successCallback the callback that will be called upon succesful execution
  10437. * @param offset starting offset.
  10438. */
  10439. function AsyncLoop(
  10440. /**
  10441. * Defines the number of iterations for the loop
  10442. */
  10443. iterations, func, successCallback, offset) {
  10444. if (offset === void 0) { offset = 0; }
  10445. this.iterations = iterations;
  10446. this.index = offset - 1;
  10447. this._done = false;
  10448. this._fn = func;
  10449. this._successCallback = successCallback;
  10450. }
  10451. /**
  10452. * Execute the next iteration. Must be called after the last iteration was finished.
  10453. */
  10454. AsyncLoop.prototype.executeNext = function () {
  10455. if (!this._done) {
  10456. if (this.index + 1 < this.iterations) {
  10457. ++this.index;
  10458. this._fn(this);
  10459. }
  10460. else {
  10461. this.breakLoop();
  10462. }
  10463. }
  10464. };
  10465. /**
  10466. * Break the loop and run the success callback.
  10467. */
  10468. AsyncLoop.prototype.breakLoop = function () {
  10469. this._done = true;
  10470. this._successCallback();
  10471. };
  10472. /**
  10473. * Create and run an async loop.
  10474. * @param iterations the number of iterations.
  10475. * @param _fn the function to run each iteration
  10476. * @param _successCallback the callback that will be called upon succesful execution
  10477. * @param offset starting offset.
  10478. * @returns the created async loop object
  10479. */
  10480. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10481. if (offset === void 0) { offset = 0; }
  10482. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10483. loop.executeNext();
  10484. return loop;
  10485. };
  10486. /**
  10487. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10488. * @param iterations total number of iterations
  10489. * @param syncedIterations number of synchronous iterations in each async iteration.
  10490. * @param fn the function to call each iteration.
  10491. * @param callback a success call back that will be called when iterating stops.
  10492. * @param breakFunction a break condition (optional)
  10493. * @param timeout timeout settings for the setTimeout function. default - 0.
  10494. * @returns the created async loop object
  10495. */
  10496. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10497. if (timeout === void 0) { timeout = 0; }
  10498. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10499. if (breakFunction && breakFunction())
  10500. loop.breakLoop();
  10501. else {
  10502. setTimeout(function () {
  10503. for (var i = 0; i < syncedIterations; ++i) {
  10504. var iteration = (loop.index * syncedIterations) + i;
  10505. if (iteration >= iterations)
  10506. break;
  10507. fn(iteration);
  10508. if (breakFunction && breakFunction()) {
  10509. loop.breakLoop();
  10510. break;
  10511. }
  10512. }
  10513. loop.executeNext();
  10514. }, timeout);
  10515. }
  10516. }, callback);
  10517. };
  10518. return AsyncLoop;
  10519. }());
  10520. BABYLON.AsyncLoop = AsyncLoop;
  10521. })(BABYLON || (BABYLON = {}));
  10522. //# sourceMappingURL=babylon.tools.js.map
  10523. var BABYLON;
  10524. (function (BABYLON) {
  10525. var PromiseStates;
  10526. (function (PromiseStates) {
  10527. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10528. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10529. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10530. })(PromiseStates || (PromiseStates = {}));
  10531. var FulFillmentAgregator = /** @class */ (function () {
  10532. function FulFillmentAgregator() {
  10533. this.count = 0;
  10534. this.target = 0;
  10535. this.results = [];
  10536. }
  10537. return FulFillmentAgregator;
  10538. }());
  10539. var InternalPromise = /** @class */ (function () {
  10540. function InternalPromise(resolver) {
  10541. var _this = this;
  10542. this._state = PromiseStates.Pending;
  10543. this._children = new Array();
  10544. this._rejectWasConsumed = false;
  10545. if (!resolver) {
  10546. return;
  10547. }
  10548. try {
  10549. resolver(function (value) {
  10550. _this._resolve(value);
  10551. }, function (reason) {
  10552. _this._reject(reason);
  10553. });
  10554. }
  10555. catch (e) {
  10556. this._reject(e);
  10557. }
  10558. }
  10559. Object.defineProperty(InternalPromise.prototype, "_result", {
  10560. get: function () {
  10561. return this._resultValue;
  10562. },
  10563. set: function (value) {
  10564. this._resultValue = value;
  10565. if (this._parent && this._parent._result === undefined) {
  10566. this._parent._result = value;
  10567. }
  10568. },
  10569. enumerable: true,
  10570. configurable: true
  10571. });
  10572. InternalPromise.prototype.catch = function (onRejected) {
  10573. return this.then(undefined, onRejected);
  10574. };
  10575. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10576. var _this = this;
  10577. var newPromise = new InternalPromise();
  10578. newPromise._onFulfilled = onFulfilled;
  10579. newPromise._onRejected = onRejected;
  10580. // Composition
  10581. this._children.push(newPromise);
  10582. newPromise._parent = this;
  10583. if (this._state !== PromiseStates.Pending) {
  10584. BABYLON.Tools.SetImmediate(function () {
  10585. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10586. var returnedValue = newPromise._resolve(_this._result);
  10587. if (returnedValue !== undefined && returnedValue !== null) {
  10588. if (returnedValue._state !== undefined) {
  10589. var returnedPromise = returnedValue;
  10590. newPromise._children.push(returnedPromise);
  10591. returnedPromise._parent = newPromise;
  10592. newPromise = returnedPromise;
  10593. }
  10594. else {
  10595. newPromise._result = returnedValue;
  10596. }
  10597. }
  10598. }
  10599. else {
  10600. newPromise._reject(_this._reason);
  10601. }
  10602. });
  10603. }
  10604. return newPromise;
  10605. };
  10606. InternalPromise.prototype._moveChildren = function (children) {
  10607. var _this = this;
  10608. var _a;
  10609. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10610. this._children.forEach(function (child) {
  10611. child._parent = _this;
  10612. });
  10613. if (this._state === PromiseStates.Fulfilled) {
  10614. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10615. var child = _b[_i];
  10616. child._resolve(this._result);
  10617. }
  10618. }
  10619. else if (this._state === PromiseStates.Rejected) {
  10620. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10621. var child = _d[_c];
  10622. child._reject(this._reason);
  10623. }
  10624. }
  10625. };
  10626. InternalPromise.prototype._resolve = function (value) {
  10627. try {
  10628. this._state = PromiseStates.Fulfilled;
  10629. var returnedValue = null;
  10630. if (this._onFulfilled) {
  10631. returnedValue = this._onFulfilled(value);
  10632. }
  10633. if (returnedValue !== undefined && returnedValue !== null) {
  10634. if (returnedValue._state !== undefined) {
  10635. // Transmit children
  10636. var returnedPromise = returnedValue;
  10637. returnedPromise._parent = this;
  10638. returnedPromise._moveChildren(this._children);
  10639. value = returnedPromise._result;
  10640. }
  10641. else {
  10642. value = returnedValue;
  10643. }
  10644. }
  10645. this._result = value;
  10646. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10647. var child = _a[_i];
  10648. child._resolve(value);
  10649. }
  10650. this._children.length = 0;
  10651. delete this._onFulfilled;
  10652. delete this._onRejected;
  10653. }
  10654. catch (e) {
  10655. this._reject(e, true);
  10656. }
  10657. };
  10658. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10659. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10660. this._state = PromiseStates.Rejected;
  10661. this._reason = reason;
  10662. if (this._onRejected && !onLocalThrow) {
  10663. try {
  10664. this._onRejected(reason);
  10665. this._rejectWasConsumed = true;
  10666. }
  10667. catch (e) {
  10668. reason = e;
  10669. }
  10670. }
  10671. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10672. var child = _a[_i];
  10673. if (this._rejectWasConsumed) {
  10674. child._resolve(null);
  10675. }
  10676. else {
  10677. child._reject(reason);
  10678. }
  10679. }
  10680. this._children.length = 0;
  10681. delete this._onFulfilled;
  10682. delete this._onRejected;
  10683. };
  10684. InternalPromise.resolve = function (value) {
  10685. var newPromise = new InternalPromise();
  10686. newPromise._resolve(value);
  10687. return newPromise;
  10688. };
  10689. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10690. promise.then(function (value) {
  10691. agregator.results[index] = value;
  10692. agregator.count++;
  10693. if (agregator.count === agregator.target) {
  10694. agregator.rootPromise._resolve(agregator.results);
  10695. }
  10696. return null;
  10697. }, function (reason) {
  10698. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10699. agregator.rootPromise._reject(reason);
  10700. }
  10701. });
  10702. };
  10703. InternalPromise.all = function (promises) {
  10704. var newPromise = new InternalPromise();
  10705. var agregator = new FulFillmentAgregator();
  10706. agregator.target = promises.length;
  10707. agregator.rootPromise = newPromise;
  10708. if (promises.length) {
  10709. for (var index = 0; index < promises.length; index++) {
  10710. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10711. }
  10712. }
  10713. else {
  10714. newPromise._resolve([]);
  10715. }
  10716. return newPromise;
  10717. };
  10718. InternalPromise.race = function (promises) {
  10719. var newPromise = new InternalPromise();
  10720. if (promises.length) {
  10721. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10722. var promise = promises_1[_i];
  10723. promise.then(function (value) {
  10724. if (newPromise) {
  10725. newPromise._resolve(value);
  10726. newPromise = null;
  10727. }
  10728. return null;
  10729. }, function (reason) {
  10730. if (newPromise) {
  10731. newPromise._reject(reason);
  10732. newPromise = null;
  10733. }
  10734. });
  10735. }
  10736. }
  10737. return newPromise;
  10738. };
  10739. return InternalPromise;
  10740. }());
  10741. /**
  10742. * Helper class that provides a small promise polyfill
  10743. */
  10744. var PromisePolyfill = /** @class */ (function () {
  10745. function PromisePolyfill() {
  10746. }
  10747. /**
  10748. * Static function used to check if the polyfill is required
  10749. * If this is the case then the function will inject the polyfill to window.Promise
  10750. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10751. */
  10752. PromisePolyfill.Apply = function (force) {
  10753. if (force === void 0) { force = false; }
  10754. if (force || typeof Promise === 'undefined') {
  10755. var root = window;
  10756. root.Promise = InternalPromise;
  10757. }
  10758. };
  10759. return PromisePolyfill;
  10760. }());
  10761. BABYLON.PromisePolyfill = PromisePolyfill;
  10762. })(BABYLON || (BABYLON = {}));
  10763. //# sourceMappingURL=babylon.promise.js.map
  10764. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10765. var BABYLON;
  10766. (function (BABYLON) {
  10767. /**
  10768. * Helper class to push actions to a pool of workers.
  10769. */
  10770. var WorkerPool = /** @class */ (function () {
  10771. /**
  10772. * Constructor
  10773. * @param workers Array of workers to use for actions
  10774. */
  10775. function WorkerPool(workers) {
  10776. this._pendingActions = new Array();
  10777. this._workerInfos = workers.map(function (worker) { return ({
  10778. worker: worker,
  10779. active: false
  10780. }); });
  10781. }
  10782. /**
  10783. * Terminates all workers and clears any pending actions.
  10784. */
  10785. WorkerPool.prototype.dispose = function () {
  10786. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10787. var workerInfo = _a[_i];
  10788. workerInfo.worker.terminate();
  10789. }
  10790. delete this._workerInfos;
  10791. delete this._pendingActions;
  10792. };
  10793. /**
  10794. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10795. * pended until a worker has completed its action.
  10796. * @param action The action to perform. Call onComplete when the action is complete.
  10797. */
  10798. WorkerPool.prototype.push = function (action) {
  10799. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10800. var workerInfo = _a[_i];
  10801. if (!workerInfo.active) {
  10802. this._execute(workerInfo, action);
  10803. return;
  10804. }
  10805. }
  10806. this._pendingActions.push(action);
  10807. };
  10808. WorkerPool.prototype._execute = function (workerInfo, action) {
  10809. var _this = this;
  10810. workerInfo.active = true;
  10811. action(workerInfo.worker, function () {
  10812. workerInfo.active = false;
  10813. var nextAction = _this._pendingActions.shift();
  10814. if (nextAction) {
  10815. _this._execute(workerInfo, nextAction);
  10816. }
  10817. });
  10818. };
  10819. return WorkerPool;
  10820. }());
  10821. BABYLON.WorkerPool = WorkerPool;
  10822. })(BABYLON || (BABYLON = {}));
  10823. //# sourceMappingURL=babylon.workerPool.js.map
  10824. var BABYLON;
  10825. (function (BABYLON) {
  10826. /**
  10827. * @hidden
  10828. **/
  10829. var _AlphaState = /** @class */ (function () {
  10830. /**
  10831. * Initializes the state.
  10832. */
  10833. function _AlphaState() {
  10834. this._isAlphaBlendDirty = false;
  10835. this._isBlendFunctionParametersDirty = false;
  10836. this._isBlendEquationParametersDirty = false;
  10837. this._isBlendConstantsDirty = false;
  10838. this._alphaBlend = false;
  10839. this._blendFunctionParameters = new Array(4);
  10840. this._blendEquationParameters = new Array(2);
  10841. this._blendConstants = new Array(4);
  10842. this.reset();
  10843. }
  10844. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10845. get: function () {
  10846. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10852. get: function () {
  10853. return this._alphaBlend;
  10854. },
  10855. set: function (value) {
  10856. if (this._alphaBlend === value) {
  10857. return;
  10858. }
  10859. this._alphaBlend = value;
  10860. this._isAlphaBlendDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10866. if (this._blendConstants[0] === r &&
  10867. this._blendConstants[1] === g &&
  10868. this._blendConstants[2] === b &&
  10869. this._blendConstants[3] === a) {
  10870. return;
  10871. }
  10872. this._blendConstants[0] = r;
  10873. this._blendConstants[1] = g;
  10874. this._blendConstants[2] = b;
  10875. this._blendConstants[3] = a;
  10876. this._isBlendConstantsDirty = true;
  10877. };
  10878. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10879. if (this._blendFunctionParameters[0] === value0 &&
  10880. this._blendFunctionParameters[1] === value1 &&
  10881. this._blendFunctionParameters[2] === value2 &&
  10882. this._blendFunctionParameters[3] === value3) {
  10883. return;
  10884. }
  10885. this._blendFunctionParameters[0] = value0;
  10886. this._blendFunctionParameters[1] = value1;
  10887. this._blendFunctionParameters[2] = value2;
  10888. this._blendFunctionParameters[3] = value3;
  10889. this._isBlendFunctionParametersDirty = true;
  10890. };
  10891. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10892. if (this._blendEquationParameters[0] === rgb &&
  10893. this._blendEquationParameters[1] === alpha) {
  10894. return;
  10895. }
  10896. this._blendEquationParameters[0] = rgb;
  10897. this._blendEquationParameters[1] = alpha;
  10898. this._isBlendEquationParametersDirty = true;
  10899. };
  10900. _AlphaState.prototype.reset = function () {
  10901. this._alphaBlend = false;
  10902. this._blendFunctionParameters[0] = null;
  10903. this._blendFunctionParameters[1] = null;
  10904. this._blendFunctionParameters[2] = null;
  10905. this._blendFunctionParameters[3] = null;
  10906. this._blendEquationParameters[0] = null;
  10907. this._blendEquationParameters[1] = null;
  10908. this._blendConstants[0] = null;
  10909. this._blendConstants[1] = null;
  10910. this._blendConstants[2] = null;
  10911. this._blendConstants[3] = null;
  10912. this._isAlphaBlendDirty = true;
  10913. this._isBlendFunctionParametersDirty = false;
  10914. this._isBlendEquationParametersDirty = false;
  10915. this._isBlendConstantsDirty = false;
  10916. };
  10917. _AlphaState.prototype.apply = function (gl) {
  10918. if (!this.isDirty) {
  10919. return;
  10920. }
  10921. // Alpha blend
  10922. if (this._isAlphaBlendDirty) {
  10923. if (this._alphaBlend) {
  10924. gl.enable(gl.BLEND);
  10925. }
  10926. else {
  10927. gl.disable(gl.BLEND);
  10928. }
  10929. this._isAlphaBlendDirty = false;
  10930. }
  10931. // Alpha function
  10932. if (this._isBlendFunctionParametersDirty) {
  10933. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10934. this._isBlendFunctionParametersDirty = false;
  10935. }
  10936. // Alpha equation
  10937. if (this._isBlendEquationParametersDirty) {
  10938. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  10939. this._isBlendEquationParametersDirty = false;
  10940. }
  10941. // Constants
  10942. if (this._isBlendConstantsDirty) {
  10943. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10944. this._isBlendConstantsDirty = false;
  10945. }
  10946. };
  10947. return _AlphaState;
  10948. }());
  10949. BABYLON._AlphaState = _AlphaState;
  10950. })(BABYLON || (BABYLON = {}));
  10951. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10952. var BABYLON;
  10953. (function (BABYLON) {
  10954. /**
  10955. * @hidden
  10956. **/
  10957. var _DepthCullingState = /** @class */ (function () {
  10958. /**
  10959. * Initializes the state.
  10960. */
  10961. function _DepthCullingState() {
  10962. this._isDepthTestDirty = false;
  10963. this._isDepthMaskDirty = false;
  10964. this._isDepthFuncDirty = false;
  10965. this._isCullFaceDirty = false;
  10966. this._isCullDirty = false;
  10967. this._isZOffsetDirty = false;
  10968. this._isFrontFaceDirty = false;
  10969. this.reset();
  10970. }
  10971. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10972. get: function () {
  10973. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10979. get: function () {
  10980. return this._zOffset;
  10981. },
  10982. set: function (value) {
  10983. if (this._zOffset === value) {
  10984. return;
  10985. }
  10986. this._zOffset = value;
  10987. this._isZOffsetDirty = true;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10993. get: function () {
  10994. return this._cullFace;
  10995. },
  10996. set: function (value) {
  10997. if (this._cullFace === value) {
  10998. return;
  10999. }
  11000. this._cullFace = value;
  11001. this._isCullFaceDirty = true;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11007. get: function () {
  11008. return this._cull;
  11009. },
  11010. set: function (value) {
  11011. if (this._cull === value) {
  11012. return;
  11013. }
  11014. this._cull = value;
  11015. this._isCullDirty = true;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11021. get: function () {
  11022. return this._depthFunc;
  11023. },
  11024. set: function (value) {
  11025. if (this._depthFunc === value) {
  11026. return;
  11027. }
  11028. this._depthFunc = value;
  11029. this._isDepthFuncDirty = true;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11035. get: function () {
  11036. return this._depthMask;
  11037. },
  11038. set: function (value) {
  11039. if (this._depthMask === value) {
  11040. return;
  11041. }
  11042. this._depthMask = value;
  11043. this._isDepthMaskDirty = true;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11049. get: function () {
  11050. return this._depthTest;
  11051. },
  11052. set: function (value) {
  11053. if (this._depthTest === value) {
  11054. return;
  11055. }
  11056. this._depthTest = value;
  11057. this._isDepthTestDirty = true;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11063. get: function () {
  11064. return this._frontFace;
  11065. },
  11066. set: function (value) {
  11067. if (this._frontFace === value) {
  11068. return;
  11069. }
  11070. this._frontFace = value;
  11071. this._isFrontFaceDirty = true;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. _DepthCullingState.prototype.reset = function () {
  11077. this._depthMask = true;
  11078. this._depthTest = true;
  11079. this._depthFunc = null;
  11080. this._cullFace = null;
  11081. this._cull = null;
  11082. this._zOffset = 0;
  11083. this._frontFace = null;
  11084. this._isDepthTestDirty = true;
  11085. this._isDepthMaskDirty = true;
  11086. this._isDepthFuncDirty = false;
  11087. this._isCullFaceDirty = false;
  11088. this._isCullDirty = false;
  11089. this._isZOffsetDirty = false;
  11090. this._isFrontFaceDirty = false;
  11091. };
  11092. _DepthCullingState.prototype.apply = function (gl) {
  11093. if (!this.isDirty) {
  11094. return;
  11095. }
  11096. // Cull
  11097. if (this._isCullDirty) {
  11098. if (this.cull) {
  11099. gl.enable(gl.CULL_FACE);
  11100. }
  11101. else {
  11102. gl.disable(gl.CULL_FACE);
  11103. }
  11104. this._isCullDirty = false;
  11105. }
  11106. // Cull face
  11107. if (this._isCullFaceDirty) {
  11108. gl.cullFace(this.cullFace);
  11109. this._isCullFaceDirty = false;
  11110. }
  11111. // Depth mask
  11112. if (this._isDepthMaskDirty) {
  11113. gl.depthMask(this.depthMask);
  11114. this._isDepthMaskDirty = false;
  11115. }
  11116. // Depth test
  11117. if (this._isDepthTestDirty) {
  11118. if (this.depthTest) {
  11119. gl.enable(gl.DEPTH_TEST);
  11120. }
  11121. else {
  11122. gl.disable(gl.DEPTH_TEST);
  11123. }
  11124. this._isDepthTestDirty = false;
  11125. }
  11126. // Depth func
  11127. if (this._isDepthFuncDirty) {
  11128. gl.depthFunc(this.depthFunc);
  11129. this._isDepthFuncDirty = false;
  11130. }
  11131. // zOffset
  11132. if (this._isZOffsetDirty) {
  11133. if (this.zOffset) {
  11134. gl.enable(gl.POLYGON_OFFSET_FILL);
  11135. gl.polygonOffset(this.zOffset, 0);
  11136. }
  11137. else {
  11138. gl.disable(gl.POLYGON_OFFSET_FILL);
  11139. }
  11140. this._isZOffsetDirty = false;
  11141. }
  11142. // Front face
  11143. if (this._isFrontFaceDirty) {
  11144. gl.frontFace(this.frontFace);
  11145. this._isFrontFaceDirty = false;
  11146. }
  11147. };
  11148. return _DepthCullingState;
  11149. }());
  11150. BABYLON._DepthCullingState = _DepthCullingState;
  11151. })(BABYLON || (BABYLON = {}));
  11152. //# sourceMappingURL=babylon.depthCullingState.js.map
  11153. var BABYLON;
  11154. (function (BABYLON) {
  11155. /**
  11156. * @hidden
  11157. **/
  11158. var _StencilState = /** @class */ (function () {
  11159. function _StencilState() {
  11160. this._isStencilTestDirty = false;
  11161. this._isStencilMaskDirty = false;
  11162. this._isStencilFuncDirty = false;
  11163. this._isStencilOpDirty = false;
  11164. this.reset();
  11165. }
  11166. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11167. get: function () {
  11168. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11169. },
  11170. enumerable: true,
  11171. configurable: true
  11172. });
  11173. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11174. get: function () {
  11175. return this._stencilFunc;
  11176. },
  11177. set: function (value) {
  11178. if (this._stencilFunc === value) {
  11179. return;
  11180. }
  11181. this._stencilFunc = value;
  11182. this._isStencilFuncDirty = true;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11188. get: function () {
  11189. return this._stencilFuncRef;
  11190. },
  11191. set: function (value) {
  11192. if (this._stencilFuncRef === value) {
  11193. return;
  11194. }
  11195. this._stencilFuncRef = value;
  11196. this._isStencilFuncDirty = true;
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11202. get: function () {
  11203. return this._stencilFuncMask;
  11204. },
  11205. set: function (value) {
  11206. if (this._stencilFuncMask === value) {
  11207. return;
  11208. }
  11209. this._stencilFuncMask = value;
  11210. this._isStencilFuncDirty = true;
  11211. },
  11212. enumerable: true,
  11213. configurable: true
  11214. });
  11215. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11216. get: function () {
  11217. return this._stencilOpStencilFail;
  11218. },
  11219. set: function (value) {
  11220. if (this._stencilOpStencilFail === value) {
  11221. return;
  11222. }
  11223. this._stencilOpStencilFail = value;
  11224. this._isStencilOpDirty = true;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11230. get: function () {
  11231. return this._stencilOpDepthFail;
  11232. },
  11233. set: function (value) {
  11234. if (this._stencilOpDepthFail === value) {
  11235. return;
  11236. }
  11237. this._stencilOpDepthFail = value;
  11238. this._isStencilOpDirty = true;
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11244. get: function () {
  11245. return this._stencilOpStencilDepthPass;
  11246. },
  11247. set: function (value) {
  11248. if (this._stencilOpStencilDepthPass === value) {
  11249. return;
  11250. }
  11251. this._stencilOpStencilDepthPass = value;
  11252. this._isStencilOpDirty = true;
  11253. },
  11254. enumerable: true,
  11255. configurable: true
  11256. });
  11257. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11258. get: function () {
  11259. return this._stencilMask;
  11260. },
  11261. set: function (value) {
  11262. if (this._stencilMask === value) {
  11263. return;
  11264. }
  11265. this._stencilMask = value;
  11266. this._isStencilMaskDirty = true;
  11267. },
  11268. enumerable: true,
  11269. configurable: true
  11270. });
  11271. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11272. get: function () {
  11273. return this._stencilTest;
  11274. },
  11275. set: function (value) {
  11276. if (this._stencilTest === value) {
  11277. return;
  11278. }
  11279. this._stencilTest = value;
  11280. this._isStencilTestDirty = true;
  11281. },
  11282. enumerable: true,
  11283. configurable: true
  11284. });
  11285. _StencilState.prototype.reset = function () {
  11286. this._stencilTest = false;
  11287. this._stencilMask = 0xFF;
  11288. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11289. this._stencilFuncRef = 1;
  11290. this._stencilFuncMask = 0xFF;
  11291. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11292. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11293. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11294. this._isStencilTestDirty = true;
  11295. this._isStencilMaskDirty = true;
  11296. this._isStencilFuncDirty = true;
  11297. this._isStencilOpDirty = true;
  11298. };
  11299. _StencilState.prototype.apply = function (gl) {
  11300. if (!this.isDirty) {
  11301. return;
  11302. }
  11303. // Stencil test
  11304. if (this._isStencilTestDirty) {
  11305. if (this.stencilTest) {
  11306. gl.enable(gl.STENCIL_TEST);
  11307. }
  11308. else {
  11309. gl.disable(gl.STENCIL_TEST);
  11310. }
  11311. this._isStencilTestDirty = false;
  11312. }
  11313. // Stencil mask
  11314. if (this._isStencilMaskDirty) {
  11315. gl.stencilMask(this.stencilMask);
  11316. this._isStencilMaskDirty = false;
  11317. }
  11318. // Stencil func
  11319. if (this._isStencilFuncDirty) {
  11320. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11321. this._isStencilFuncDirty = false;
  11322. }
  11323. // Stencil op
  11324. if (this._isStencilOpDirty) {
  11325. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11326. this._isStencilOpDirty = false;
  11327. }
  11328. };
  11329. return _StencilState;
  11330. }());
  11331. BABYLON._StencilState = _StencilState;
  11332. })(BABYLON || (BABYLON = {}));
  11333. //# sourceMappingURL=babylon.stencilState.js.map
  11334. var __assign = (this && this.__assign) || function () {
  11335. __assign = Object.assign || function(t) {
  11336. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11337. s = arguments[i];
  11338. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11339. t[p] = s[p];
  11340. }
  11341. return t;
  11342. };
  11343. return __assign.apply(this, arguments);
  11344. };
  11345. var BABYLON;
  11346. (function (BABYLON) {
  11347. /**
  11348. * Keeps track of all the buffer info used in engine.
  11349. */
  11350. var BufferPointer = /** @class */ (function () {
  11351. function BufferPointer() {
  11352. }
  11353. return BufferPointer;
  11354. }());
  11355. /**
  11356. * Interface for attribute information associated with buffer instanciation
  11357. */
  11358. var InstancingAttributeInfo = /** @class */ (function () {
  11359. function InstancingAttributeInfo() {
  11360. }
  11361. return InstancingAttributeInfo;
  11362. }());
  11363. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11364. /**
  11365. * Define options used to create a render target texture
  11366. */
  11367. var RenderTargetCreationOptions = /** @class */ (function () {
  11368. function RenderTargetCreationOptions() {
  11369. }
  11370. return RenderTargetCreationOptions;
  11371. }());
  11372. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11373. /**
  11374. * Define options used to create a depth texture
  11375. */
  11376. var DepthTextureCreationOptions = /** @class */ (function () {
  11377. function DepthTextureCreationOptions() {
  11378. }
  11379. return DepthTextureCreationOptions;
  11380. }());
  11381. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11382. /**
  11383. * Class used to describe the capabilities of the engine relatively to the current browser
  11384. */
  11385. var EngineCapabilities = /** @class */ (function () {
  11386. function EngineCapabilities() {
  11387. }
  11388. return EngineCapabilities;
  11389. }());
  11390. BABYLON.EngineCapabilities = EngineCapabilities;
  11391. /**
  11392. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11393. */
  11394. var Engine = /** @class */ (function () {
  11395. /**
  11396. * Creates a new engine
  11397. * @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
  11398. * @param antialias defines enable antialiasing (default: false)
  11399. * @param options defines further options to be sent to the getContext() function
  11400. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11401. */
  11402. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11403. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11404. var _this = this;
  11405. // Public members
  11406. /**
  11407. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11408. */
  11409. this.forcePOTTextures = false;
  11410. /**
  11411. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11412. */
  11413. this.isFullscreen = false;
  11414. /**
  11415. * Gets a boolean indicating if the pointer is currently locked
  11416. */
  11417. this.isPointerLock = false;
  11418. /**
  11419. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11420. */
  11421. this.cullBackFaces = true;
  11422. /**
  11423. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11424. */
  11425. this.renderEvenInBackground = true;
  11426. /**
  11427. * Gets or sets a boolean indicating that cache can be kept between frames
  11428. */
  11429. this.preventCacheWipeBetweenFrames = false;
  11430. /**
  11431. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11432. **/
  11433. this.enableOfflineSupport = false;
  11434. /**
  11435. * 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)
  11436. **/
  11437. this.disableManifestCheck = false;
  11438. /**
  11439. * Gets the list of created scenes
  11440. */
  11441. this.scenes = new Array();
  11442. /**
  11443. * Gets the list of created postprocesses
  11444. */
  11445. this.postProcesses = new Array();
  11446. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11447. this.validateShaderPrograms = false;
  11448. // Observables
  11449. /**
  11450. * Observable event triggered each time the rendering canvas is resized
  11451. */
  11452. this.onResizeObservable = new BABYLON.Observable();
  11453. /**
  11454. * Observable event triggered each time the canvas loses focus
  11455. */
  11456. this.onCanvasBlurObservable = new BABYLON.Observable();
  11457. /**
  11458. * Observable event triggered each time the canvas gains focus
  11459. */
  11460. this.onCanvasFocusObservable = new BABYLON.Observable();
  11461. /**
  11462. * Observable event triggered each time the canvas receives pointerout event
  11463. */
  11464. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11465. /**
  11466. * Observable event triggered before each texture is initialized
  11467. */
  11468. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11469. //WebVR
  11470. this._vrDisplay = undefined;
  11471. this._vrSupported = false;
  11472. this._vrExclusivePointerMode = false;
  11473. // Uniform buffers list
  11474. /**
  11475. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11476. */
  11477. this.disableUniformBuffers = false;
  11478. /** @hidden */
  11479. this._uniformBuffers = new Array();
  11480. // Observables
  11481. /**
  11482. * Observable raised when the engine begins a new frame
  11483. */
  11484. this.onBeginFrameObservable = new BABYLON.Observable();
  11485. /**
  11486. * Observable raised when the engine ends the current frame
  11487. */
  11488. this.onEndFrameObservable = new BABYLON.Observable();
  11489. /**
  11490. * Observable raised when the engine is about to compile a shader
  11491. */
  11492. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11493. /**
  11494. * Observable raised when the engine has jsut compiled a shader
  11495. */
  11496. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11497. this._windowIsBackground = false;
  11498. this._webGLVersion = 1.0;
  11499. /** @hidden */
  11500. this._badOS = false;
  11501. /** @hidden */
  11502. this._badDesktopOS = false;
  11503. /**
  11504. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11505. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11506. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11507. */
  11508. this.disableTextureBindingOptimization = false;
  11509. /**
  11510. * Observable signaled when VR display mode changes
  11511. */
  11512. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11513. /**
  11514. * Observable signaled when VR request present is complete
  11515. */
  11516. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11517. /**
  11518. * Observable signaled when VR request present starts
  11519. */
  11520. this.onVRRequestPresentStart = new BABYLON.Observable();
  11521. this._colorWrite = true;
  11522. /** @hidden */
  11523. this._drawCalls = new BABYLON.PerfCounter();
  11524. /** @hidden */
  11525. this._textureCollisions = new BABYLON.PerfCounter();
  11526. this._renderingQueueLaunched = false;
  11527. this._activeRenderLoops = new Array();
  11528. // Deterministic lockstepMaxSteps
  11529. this._deterministicLockstep = false;
  11530. this._lockstepMaxSteps = 4;
  11531. // Lost context
  11532. /**
  11533. * Observable signaled when a context lost event is raised
  11534. */
  11535. this.onContextLostObservable = new BABYLON.Observable();
  11536. /**
  11537. * Observable signaled when a context restored event is raised
  11538. */
  11539. this.onContextRestoredObservable = new BABYLON.Observable();
  11540. this._contextWasLost = false;
  11541. this._doNotHandleContextLost = false;
  11542. // FPS
  11543. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11544. this._fps = 60;
  11545. this._deltaTime = 0;
  11546. /**
  11547. * Turn this value on if you want to pause FPS computation when in background
  11548. */
  11549. this.disablePerformanceMonitorInBackground = false;
  11550. // States
  11551. /** @hidden */
  11552. this._depthCullingState = new BABYLON._DepthCullingState();
  11553. /** @hidden */
  11554. this._stencilState = new BABYLON._StencilState();
  11555. /** @hidden */
  11556. this._alphaState = new BABYLON._AlphaState();
  11557. /** @hidden */
  11558. this._alphaMode = Engine.ALPHA_DISABLE;
  11559. // Cache
  11560. this._internalTexturesCache = new Array();
  11561. /** @hidden */
  11562. this._activeChannel = 0;
  11563. this._currentTextureChannel = -1;
  11564. /** @hidden */
  11565. this._boundTexturesCache = {};
  11566. this._compiledEffects = {};
  11567. this._vertexAttribArraysEnabled = [];
  11568. this._uintIndicesCurrentlySet = false;
  11569. this._currentBoundBuffer = new Array();
  11570. /** @hidden */
  11571. this._currentFramebuffer = null;
  11572. this._currentBufferPointers = new Array();
  11573. this._currentInstanceLocations = new Array();
  11574. this._currentInstanceBuffers = new Array();
  11575. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11576. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11577. this._vaoRecordInProgress = false;
  11578. this._mustWipeVertexAttributes = false;
  11579. this._nextFreeTextureSlots = new Array();
  11580. this._maxSimultaneousTextures = 0;
  11581. this._activeRequests = new Array();
  11582. // Hardware supported Compressed Textures
  11583. this._texturesSupported = new Array();
  11584. /**
  11585. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11586. */
  11587. this.premultipliedAlpha = true;
  11588. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11589. this._onVRFullScreenTriggered = function () {
  11590. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11591. //get the old size before we change
  11592. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11593. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11594. //get the width and height, change the render size
  11595. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11596. _this.setHardwareScalingLevel(1);
  11597. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11598. }
  11599. else {
  11600. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11601. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11602. }
  11603. };
  11604. this._unpackFlipYCached = null;
  11605. /**
  11606. * In case you are sharing the context with other applications, it might
  11607. * be interested to not cache the unpack flip y state to ensure a consistent
  11608. * value would be set.
  11609. */
  11610. this.enableUnpackFlipYCached = true;
  11611. this._boundUniforms = {};
  11612. // Register promises
  11613. BABYLON.PromisePolyfill.Apply();
  11614. var canvas = null;
  11615. Engine.Instances.push(this);
  11616. if (!canvasOrContext) {
  11617. return;
  11618. }
  11619. options = options || {};
  11620. if (canvasOrContext.getContext) {
  11621. canvas = canvasOrContext;
  11622. this._renderingCanvas = canvas;
  11623. if (antialias != null) {
  11624. options.antialias = antialias;
  11625. }
  11626. if (options.deterministicLockstep === undefined) {
  11627. options.deterministicLockstep = false;
  11628. }
  11629. if (options.lockstepMaxSteps === undefined) {
  11630. options.lockstepMaxSteps = 4;
  11631. }
  11632. if (options.preserveDrawingBuffer === undefined) {
  11633. options.preserveDrawingBuffer = false;
  11634. }
  11635. if (options.audioEngine === undefined) {
  11636. options.audioEngine = true;
  11637. }
  11638. if (options.stencil === undefined) {
  11639. options.stencil = true;
  11640. }
  11641. if (options.premultipliedAlpha === false) {
  11642. this.premultipliedAlpha = false;
  11643. }
  11644. this._deterministicLockstep = options.deterministicLockstep;
  11645. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11646. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11647. // Exceptions
  11648. if (navigator && navigator.userAgent) {
  11649. var ua = navigator.userAgent;
  11650. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11651. var exception = _a[_i];
  11652. var key = exception.key;
  11653. var targets = exception.targets;
  11654. if (ua.indexOf(key) > -1) {
  11655. if (exception.capture && exception.captureConstraint) {
  11656. var capture = exception.capture;
  11657. var constraint = exception.captureConstraint;
  11658. var regex = new RegExp(capture);
  11659. var matches = regex.exec(ua);
  11660. if (matches && matches.length > 0) {
  11661. var capturedValue = parseInt(matches[matches.length - 1]);
  11662. if (capturedValue >= constraint) {
  11663. continue;
  11664. }
  11665. }
  11666. }
  11667. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11668. var target = targets_1[_b];
  11669. switch (target) {
  11670. case "uniformBuffer":
  11671. this.disableUniformBuffers = true;
  11672. break;
  11673. case "textureBindingOptimization":
  11674. this.disableTextureBindingOptimization = true;
  11675. break;
  11676. }
  11677. }
  11678. }
  11679. }
  11680. }
  11681. // GL
  11682. if (!options.disableWebGL2Support) {
  11683. try {
  11684. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11685. if (this._gl) {
  11686. this._webGLVersion = 2.0;
  11687. }
  11688. }
  11689. catch (e) {
  11690. // Do nothing
  11691. }
  11692. }
  11693. if (!this._gl) {
  11694. if (!canvas) {
  11695. throw new Error("The provided canvas is null or undefined.");
  11696. }
  11697. try {
  11698. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11699. }
  11700. catch (e) {
  11701. throw new Error("WebGL not supported");
  11702. }
  11703. }
  11704. if (!this._gl) {
  11705. throw new Error("WebGL not supported");
  11706. }
  11707. this._onCanvasFocus = function () {
  11708. _this.onCanvasFocusObservable.notifyObservers(_this);
  11709. };
  11710. this._onCanvasBlur = function () {
  11711. _this.onCanvasBlurObservable.notifyObservers(_this);
  11712. };
  11713. canvas.addEventListener("focus", this._onCanvasFocus);
  11714. canvas.addEventListener("blur", this._onCanvasBlur);
  11715. this._onBlur = function () {
  11716. if (_this.disablePerformanceMonitorInBackground) {
  11717. _this._performanceMonitor.disable();
  11718. }
  11719. _this._windowIsBackground = true;
  11720. };
  11721. this._onFocus = function () {
  11722. if (_this.disablePerformanceMonitorInBackground) {
  11723. _this._performanceMonitor.enable();
  11724. }
  11725. _this._windowIsBackground = false;
  11726. };
  11727. this._onCanvasPointerOut = function (ev) {
  11728. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11729. };
  11730. window.addEventListener("blur", this._onBlur);
  11731. window.addEventListener("focus", this._onFocus);
  11732. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11733. // Context lost
  11734. if (!this._doNotHandleContextLost) {
  11735. this._onContextLost = function (evt) {
  11736. evt.preventDefault();
  11737. _this._contextWasLost = true;
  11738. BABYLON.Tools.Warn("WebGL context lost.");
  11739. _this.onContextLostObservable.notifyObservers(_this);
  11740. };
  11741. this._onContextRestored = function (evt) {
  11742. // Adding a timeout to avoid race condition at browser level
  11743. setTimeout(function () {
  11744. // Rebuild gl context
  11745. _this._initGLContext();
  11746. // Rebuild effects
  11747. _this._rebuildEffects();
  11748. // Rebuild textures
  11749. _this._rebuildInternalTextures();
  11750. // Rebuild buffers
  11751. _this._rebuildBuffers();
  11752. // Cache
  11753. _this.wipeCaches(true);
  11754. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11755. _this.onContextRestoredObservable.notifyObservers(_this);
  11756. _this._contextWasLost = false;
  11757. }, 0);
  11758. };
  11759. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11760. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11761. }
  11762. }
  11763. else {
  11764. this._gl = canvasOrContext;
  11765. this._renderingCanvas = this._gl.canvas;
  11766. if (this._gl.renderbufferStorageMultisample) {
  11767. this._webGLVersion = 2.0;
  11768. }
  11769. options.stencil = this._gl.getContextAttributes().stencil;
  11770. }
  11771. // Viewport
  11772. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11773. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11774. this.resize();
  11775. this._isStencilEnable = options.stencil ? true : false;
  11776. this._initGLContext();
  11777. if (canvas) {
  11778. // Fullscreen
  11779. this._onFullscreenChange = function () {
  11780. if (document.fullscreen !== undefined) {
  11781. _this.isFullscreen = document.fullscreen;
  11782. }
  11783. else if (document.mozFullScreen !== undefined) {
  11784. _this.isFullscreen = document.mozFullScreen;
  11785. }
  11786. else if (document.webkitIsFullScreen !== undefined) {
  11787. _this.isFullscreen = document.webkitIsFullScreen;
  11788. }
  11789. else if (document.msIsFullScreen !== undefined) {
  11790. _this.isFullscreen = document.msIsFullScreen;
  11791. }
  11792. // Pointer lock
  11793. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11794. canvas.requestPointerLock = canvas.requestPointerLock ||
  11795. canvas.msRequestPointerLock ||
  11796. canvas.mozRequestPointerLock ||
  11797. canvas.webkitRequestPointerLock;
  11798. if (canvas.requestPointerLock) {
  11799. canvas.requestPointerLock();
  11800. }
  11801. }
  11802. };
  11803. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11804. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11805. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11806. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11807. // Pointer lock
  11808. this._onPointerLockChange = function () {
  11809. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11810. document.webkitPointerLockElement === canvas ||
  11811. document.msPointerLockElement === canvas ||
  11812. document.pointerLockElement === canvas);
  11813. };
  11814. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11815. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11816. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11817. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11818. this._onVRDisplayPointerRestricted = function () {
  11819. if (canvas) {
  11820. canvas.requestPointerLock();
  11821. }
  11822. };
  11823. this._onVRDisplayPointerUnrestricted = function () {
  11824. document.exitPointerLock();
  11825. };
  11826. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11827. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11828. }
  11829. // Create Audio Engine if needed.
  11830. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11831. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11832. }
  11833. // Prepare buffer pointers
  11834. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11835. this._currentBufferPointers[i] = new BufferPointer();
  11836. }
  11837. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11838. // Load WebVR Devices
  11839. if (options.autoEnableWebVR) {
  11840. this.initWebVR();
  11841. }
  11842. // Detect if we are running on a faulty buggy OS.
  11843. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11844. // Detect if we are running on a faulty buggy desktop OS.
  11845. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11846. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11847. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11848. }
  11849. Object.defineProperty(Engine, "LastCreatedEngine", {
  11850. /**
  11851. * Gets the latest created engine
  11852. */
  11853. get: function () {
  11854. if (Engine.Instances.length === 0) {
  11855. return null;
  11856. }
  11857. return Engine.Instances[Engine.Instances.length - 1];
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine, "LastCreatedScene", {
  11863. /**
  11864. * Gets the latest created scene
  11865. */
  11866. get: function () {
  11867. var lastCreatedEngine = Engine.LastCreatedEngine;
  11868. if (!lastCreatedEngine) {
  11869. return null;
  11870. }
  11871. if (lastCreatedEngine.scenes.length === 0) {
  11872. return null;
  11873. }
  11874. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. /**
  11880. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11881. * @param flag defines which part of the materials must be marked as dirty
  11882. * @param predicate defines a predicate used to filter which materials should be affected
  11883. */
  11884. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11885. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11886. var engine = Engine.Instances[engineIndex];
  11887. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11888. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11889. }
  11890. }
  11891. };
  11892. Object.defineProperty(Engine, "Version", {
  11893. /**
  11894. * Returns the current version of the framework
  11895. */
  11896. get: function () {
  11897. return "3.3.0-rc.0";
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11903. /**
  11904. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11905. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11906. */
  11907. get: function () {
  11908. return this._vrExclusivePointerMode;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11914. /**
  11915. * Gets a boolean indicating that the engine supports uniform buffers
  11916. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11917. */
  11918. get: function () {
  11919. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11925. /**
  11926. * Gets a boolean indicating that only power of 2 textures are supported
  11927. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11928. */
  11929. get: function () {
  11930. return this._webGLVersion < 2 || this.forcePOTTextures;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11936. /**
  11937. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11938. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11939. */
  11940. get: function () {
  11941. return this._doNotHandleContextLost;
  11942. },
  11943. set: function (value) {
  11944. this._doNotHandleContextLost = value;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11950. /**
  11951. * Gets the performance monitor attached to this engine
  11952. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11953. */
  11954. get: function () {
  11955. return this._performanceMonitor;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11961. /**
  11962. * Gets the list of texture formats supported
  11963. */
  11964. get: function () {
  11965. return this._texturesSupported;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11971. /**
  11972. * Gets the list of texture formats in use
  11973. */
  11974. get: function () {
  11975. return this._textureFormatInUse;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(Engine.prototype, "currentViewport", {
  11981. /**
  11982. * Gets the current viewport
  11983. */
  11984. get: function () {
  11985. return this._cachedViewport;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11991. /**
  11992. * Gets the default empty texture
  11993. */
  11994. get: function () {
  11995. if (!this._emptyTexture) {
  11996. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11997. }
  11998. return this._emptyTexture;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12004. /**
  12005. * Gets the default empty 3D texture
  12006. */
  12007. get: function () {
  12008. if (!this._emptyTexture3D) {
  12009. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12010. }
  12011. return this._emptyTexture3D;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12017. /**
  12018. * Gets the default empty cube texture
  12019. */
  12020. get: function () {
  12021. if (!this._emptyCubeTexture) {
  12022. var faceData = new Uint8Array(4);
  12023. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12024. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12025. }
  12026. return this._emptyCubeTexture;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Engine.prototype._rebuildInternalTextures = function () {
  12032. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12033. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12034. var internalTexture = currentState_1[_i];
  12035. internalTexture._rebuild();
  12036. }
  12037. };
  12038. Engine.prototype._rebuildEffects = function () {
  12039. for (var key in this._compiledEffects) {
  12040. var effect = this._compiledEffects[key];
  12041. effect._prepareEffect();
  12042. }
  12043. BABYLON.Effect.ResetCache();
  12044. };
  12045. Engine.prototype._rebuildBuffers = function () {
  12046. // Index / Vertex
  12047. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12048. var scene = _a[_i];
  12049. scene.resetCachedMaterial();
  12050. scene._rebuildGeometries();
  12051. scene._rebuildTextures();
  12052. }
  12053. // Uniforms
  12054. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12055. var uniformBuffer = _c[_b];
  12056. uniformBuffer._rebuild();
  12057. }
  12058. };
  12059. Engine.prototype._initGLContext = function () {
  12060. // Caps
  12061. this._caps = new EngineCapabilities();
  12062. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12063. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12064. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12065. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12066. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12067. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12068. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12069. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12070. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12071. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12072. // Infos
  12073. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12074. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12075. if (rendererInfo != null) {
  12076. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12077. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12078. }
  12079. if (!this._glVendor) {
  12080. this._glVendor = "Unknown vendor";
  12081. }
  12082. if (!this._glRenderer) {
  12083. this._glRenderer = "Unknown renderer";
  12084. }
  12085. // Constants
  12086. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12087. if (this._gl.RGBA16F !== 0x881A) {
  12088. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12089. }
  12090. if (this._gl.RGBA32F !== 0x8814) {
  12091. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12092. }
  12093. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12094. this._gl.DEPTH24_STENCIL8 = 35056;
  12095. }
  12096. // Extensions
  12097. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12098. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12099. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12100. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12101. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12102. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12103. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12104. 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');
  12105. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12106. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12107. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12108. this._caps.highPrecisionShaderSupported = true;
  12109. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12110. if (this._caps.timerQuery) {
  12111. if (this._webGLVersion === 1) {
  12112. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12113. }
  12114. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12115. }
  12116. // Checks if some of the format renders first to allow the use of webgl inspector.
  12117. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12118. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12119. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12120. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12121. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12122. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12123. if (this._webGLVersion > 1) {
  12124. this._gl.HALF_FLOAT_OES = 0x140B;
  12125. }
  12126. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12127. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12128. // Draw buffers
  12129. if (this._webGLVersion > 1) {
  12130. this._caps.drawBuffersExtension = true;
  12131. }
  12132. else {
  12133. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12134. if (drawBuffersExtension !== null) {
  12135. this._caps.drawBuffersExtension = true;
  12136. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12137. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12138. for (var i = 0; i < 16; i++) {
  12139. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12140. }
  12141. }
  12142. else {
  12143. this._caps.drawBuffersExtension = false;
  12144. }
  12145. }
  12146. // Depth Texture
  12147. if (this._webGLVersion > 1) {
  12148. this._caps.depthTextureExtension = true;
  12149. }
  12150. else {
  12151. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12152. if (depthTextureExtension != null) {
  12153. this._caps.depthTextureExtension = true;
  12154. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12155. }
  12156. }
  12157. // Vertex array object
  12158. if (this._webGLVersion > 1) {
  12159. this._caps.vertexArrayObject = true;
  12160. }
  12161. else {
  12162. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12163. if (vertexArrayObjectExtension != null) {
  12164. this._caps.vertexArrayObject = true;
  12165. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12166. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12167. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12168. }
  12169. else {
  12170. this._caps.vertexArrayObject = false;
  12171. }
  12172. }
  12173. // Instances count
  12174. if (this._webGLVersion > 1) {
  12175. this._caps.instancedArrays = true;
  12176. }
  12177. else {
  12178. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12179. if (instanceExtension != null) {
  12180. this._caps.instancedArrays = true;
  12181. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12182. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12183. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12184. }
  12185. else {
  12186. this._caps.instancedArrays = false;
  12187. }
  12188. }
  12189. // Intelligently add supported compressed formats in order to check for.
  12190. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12191. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12192. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12193. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12194. if (this._caps.astc)
  12195. this.texturesSupported.push('-astc.ktx');
  12196. if (this._caps.s3tc)
  12197. this.texturesSupported.push('-dxt.ktx');
  12198. if (this._caps.pvrtc)
  12199. this.texturesSupported.push('-pvrtc.ktx');
  12200. if (this._caps.etc2)
  12201. this.texturesSupported.push('-etc2.ktx');
  12202. if (this._caps.etc1)
  12203. this.texturesSupported.push('-etc1.ktx');
  12204. if (this._gl.getShaderPrecisionFormat) {
  12205. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12206. if (highp) {
  12207. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12208. }
  12209. }
  12210. // Depth buffer
  12211. this.setDepthBuffer(true);
  12212. this.setDepthFunctionToLessOrEqual();
  12213. this.setDepthWrite(true);
  12214. // Texture maps
  12215. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12216. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12217. this._nextFreeTextureSlots.push(slot);
  12218. }
  12219. };
  12220. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12221. /**
  12222. * Gets version of the current webGL context
  12223. */
  12224. get: function () {
  12225. return this._webGLVersion;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12231. /**
  12232. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12233. */
  12234. get: function () {
  12235. return this._isStencilEnable;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Engine.prototype._prepareWorkingCanvas = function () {
  12241. if (this._workingCanvas) {
  12242. return;
  12243. }
  12244. this._workingCanvas = document.createElement("canvas");
  12245. var context = this._workingCanvas.getContext("2d");
  12246. if (context) {
  12247. this._workingContext = context;
  12248. }
  12249. };
  12250. /**
  12251. * Reset the texture cache to empty state
  12252. */
  12253. Engine.prototype.resetTextureCache = function () {
  12254. for (var key in this._boundTexturesCache) {
  12255. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12256. continue;
  12257. }
  12258. var boundTexture = this._boundTexturesCache[key];
  12259. if (boundTexture) {
  12260. this._removeDesignatedSlot(boundTexture);
  12261. }
  12262. this._boundTexturesCache[key] = null;
  12263. }
  12264. if (!this.disableTextureBindingOptimization) {
  12265. this._nextFreeTextureSlots = [];
  12266. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12267. this._nextFreeTextureSlots.push(slot);
  12268. }
  12269. }
  12270. this._currentTextureChannel = -1;
  12271. };
  12272. /**
  12273. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12274. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12275. * @returns true if engine is in deterministic lock step mode
  12276. */
  12277. Engine.prototype.isDeterministicLockStep = function () {
  12278. return this._deterministicLockstep;
  12279. };
  12280. /**
  12281. * Gets the max steps when engine is running in deterministic lock step
  12282. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12283. * @returns the max steps
  12284. */
  12285. Engine.prototype.getLockstepMaxSteps = function () {
  12286. return this._lockstepMaxSteps;
  12287. };
  12288. /**
  12289. * Gets an object containing information about the current webGL context
  12290. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12291. */
  12292. Engine.prototype.getGlInfo = function () {
  12293. return {
  12294. vendor: this._glVendor,
  12295. renderer: this._glRenderer,
  12296. version: this._glVersion
  12297. };
  12298. };
  12299. /**
  12300. * Gets current aspect ratio
  12301. * @param camera defines the camera to use to get the aspect ratio
  12302. * @param useScreen defines if screen size must be used (or the current render target if any)
  12303. * @returns a number defining the aspect ratio
  12304. */
  12305. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12306. if (useScreen === void 0) { useScreen = false; }
  12307. var viewport = camera.viewport;
  12308. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12309. };
  12310. /**
  12311. * Gets current screen aspect ratio
  12312. * @returns a number defining the aspect ratio
  12313. */
  12314. Engine.prototype.getScreenAspectRatio = function () {
  12315. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12316. };
  12317. /**
  12318. * Gets the current render width
  12319. * @param useScreen defines if screen size must be used (or the current render target if any)
  12320. * @returns a number defining the current render width
  12321. */
  12322. Engine.prototype.getRenderWidth = function (useScreen) {
  12323. if (useScreen === void 0) { useScreen = false; }
  12324. if (!useScreen && this._currentRenderTarget) {
  12325. return this._currentRenderTarget.width;
  12326. }
  12327. return this._gl.drawingBufferWidth;
  12328. };
  12329. /**
  12330. * Gets the current render height
  12331. * @param useScreen defines if screen size must be used (or the current render target if any)
  12332. * @returns a number defining the current render height
  12333. */
  12334. Engine.prototype.getRenderHeight = function (useScreen) {
  12335. if (useScreen === void 0) { useScreen = false; }
  12336. if (!useScreen && this._currentRenderTarget) {
  12337. return this._currentRenderTarget.height;
  12338. }
  12339. return this._gl.drawingBufferHeight;
  12340. };
  12341. /**
  12342. * Gets the HTML canvas attached with the current webGL context
  12343. * @returns a HTML canvas
  12344. */
  12345. Engine.prototype.getRenderingCanvas = function () {
  12346. return this._renderingCanvas;
  12347. };
  12348. /**
  12349. * Gets the client rect of the HTML canvas attached with the current webGL context
  12350. * @returns a client rectanglee
  12351. */
  12352. Engine.prototype.getRenderingCanvasClientRect = function () {
  12353. if (!this._renderingCanvas) {
  12354. return null;
  12355. }
  12356. return this._renderingCanvas.getBoundingClientRect();
  12357. };
  12358. /**
  12359. * Defines the hardware scaling level.
  12360. * By default the hardware scaling level is computed from the window device ratio.
  12361. * 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.
  12362. * @param level defines the level to use
  12363. */
  12364. Engine.prototype.setHardwareScalingLevel = function (level) {
  12365. this._hardwareScalingLevel = level;
  12366. this.resize();
  12367. };
  12368. /**
  12369. * Gets the current hardware scaling level.
  12370. * By default the hardware scaling level is computed from the window device ratio.
  12371. * 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.
  12372. * @returns a number indicating the current hardware scaling level
  12373. */
  12374. Engine.prototype.getHardwareScalingLevel = function () {
  12375. return this._hardwareScalingLevel;
  12376. };
  12377. /**
  12378. * Gets the list of loaded textures
  12379. * @returns an array containing all loaded textures
  12380. */
  12381. Engine.prototype.getLoadedTexturesCache = function () {
  12382. return this._internalTexturesCache;
  12383. };
  12384. /**
  12385. * Gets the object containing all engine capabilities
  12386. * @returns the EngineCapabilities object
  12387. */
  12388. Engine.prototype.getCaps = function () {
  12389. return this._caps;
  12390. };
  12391. Object.defineProperty(Engine.prototype, "drawCalls", {
  12392. /** @hidden */
  12393. get: function () {
  12394. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12395. return 0;
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12401. /** @hidden */
  12402. get: function () {
  12403. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12404. return null;
  12405. },
  12406. enumerable: true,
  12407. configurable: true
  12408. });
  12409. /**
  12410. * Gets the current depth function
  12411. * @returns a number defining the depth function
  12412. */
  12413. Engine.prototype.getDepthFunction = function () {
  12414. return this._depthCullingState.depthFunc;
  12415. };
  12416. /**
  12417. * Sets the current depth function
  12418. * @param depthFunc defines the function to use
  12419. */
  12420. Engine.prototype.setDepthFunction = function (depthFunc) {
  12421. this._depthCullingState.depthFunc = depthFunc;
  12422. };
  12423. /**
  12424. * Sets the current depth function to GREATER
  12425. */
  12426. Engine.prototype.setDepthFunctionToGreater = function () {
  12427. this._depthCullingState.depthFunc = this._gl.GREATER;
  12428. };
  12429. /**
  12430. * Sets the current depth function to GEQUAL
  12431. */
  12432. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12433. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12434. };
  12435. /**
  12436. * Sets the current depth function to LESS
  12437. */
  12438. Engine.prototype.setDepthFunctionToLess = function () {
  12439. this._depthCullingState.depthFunc = this._gl.LESS;
  12440. };
  12441. /**
  12442. * Sets the current depth function to LEQUAL
  12443. */
  12444. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12445. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12446. };
  12447. /**
  12448. * Gets a boolean indicating if stencil buffer is enabled
  12449. * @returns the current stencil buffer state
  12450. */
  12451. Engine.prototype.getStencilBuffer = function () {
  12452. return this._stencilState.stencilTest;
  12453. };
  12454. /**
  12455. * Enable or disable the stencil buffer
  12456. * @param enable defines if the stencil buffer must be enabled or disabled
  12457. */
  12458. Engine.prototype.setStencilBuffer = function (enable) {
  12459. this._stencilState.stencilTest = enable;
  12460. };
  12461. /**
  12462. * Gets the current stencil mask
  12463. * @returns a number defining the new stencil mask to use
  12464. */
  12465. Engine.prototype.getStencilMask = function () {
  12466. return this._stencilState.stencilMask;
  12467. };
  12468. /**
  12469. * Sets the current stencil mask
  12470. * @param mask defines the new stencil mask to use
  12471. */
  12472. Engine.prototype.setStencilMask = function (mask) {
  12473. this._stencilState.stencilMask = mask;
  12474. };
  12475. /**
  12476. * Gets the current stencil function
  12477. * @returns a number defining the stencil function to use
  12478. */
  12479. Engine.prototype.getStencilFunction = function () {
  12480. return this._stencilState.stencilFunc;
  12481. };
  12482. /**
  12483. * Gets the current stencil reference value
  12484. * @returns a number defining the stencil reference value to use
  12485. */
  12486. Engine.prototype.getStencilFunctionReference = function () {
  12487. return this._stencilState.stencilFuncRef;
  12488. };
  12489. /**
  12490. * Gets the current stencil mask
  12491. * @returns a number defining the stencil mask to use
  12492. */
  12493. Engine.prototype.getStencilFunctionMask = function () {
  12494. return this._stencilState.stencilFuncMask;
  12495. };
  12496. /**
  12497. * Sets the current stencil function
  12498. * @param stencilFunc defines the new stencil function to use
  12499. */
  12500. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12501. this._stencilState.stencilFunc = stencilFunc;
  12502. };
  12503. /**
  12504. * Sets the current stencil reference
  12505. * @param reference defines the new stencil reference to use
  12506. */
  12507. Engine.prototype.setStencilFunctionReference = function (reference) {
  12508. this._stencilState.stencilFuncRef = reference;
  12509. };
  12510. /**
  12511. * Sets the current stencil mask
  12512. * @param mask defines the new stencil mask to use
  12513. */
  12514. Engine.prototype.setStencilFunctionMask = function (mask) {
  12515. this._stencilState.stencilFuncMask = mask;
  12516. };
  12517. /**
  12518. * Gets the current stencil operation when stencil fails
  12519. * @returns a number defining stencil operation to use when stencil fails
  12520. */
  12521. Engine.prototype.getStencilOperationFail = function () {
  12522. return this._stencilState.stencilOpStencilFail;
  12523. };
  12524. /**
  12525. * Gets the current stencil operation when depth fails
  12526. * @returns a number defining stencil operation to use when depth fails
  12527. */
  12528. Engine.prototype.getStencilOperationDepthFail = function () {
  12529. return this._stencilState.stencilOpDepthFail;
  12530. };
  12531. /**
  12532. * Gets the current stencil operation when stencil passes
  12533. * @returns a number defining stencil operation to use when stencil passes
  12534. */
  12535. Engine.prototype.getStencilOperationPass = function () {
  12536. return this._stencilState.stencilOpStencilDepthPass;
  12537. };
  12538. /**
  12539. * Sets the stencil operation to use when stencil fails
  12540. * @param operation defines the stencil operation to use when stencil fails
  12541. */
  12542. Engine.prototype.setStencilOperationFail = function (operation) {
  12543. this._stencilState.stencilOpStencilFail = operation;
  12544. };
  12545. /**
  12546. * Sets the stencil operation to use when depth fails
  12547. * @param operation defines the stencil operation to use when depth fails
  12548. */
  12549. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12550. this._stencilState.stencilOpDepthFail = operation;
  12551. };
  12552. /**
  12553. * Sets the stencil operation to use when stencil passes
  12554. * @param operation defines the stencil operation to use when stencil passes
  12555. */
  12556. Engine.prototype.setStencilOperationPass = function (operation) {
  12557. this._stencilState.stencilOpStencilDepthPass = operation;
  12558. };
  12559. /**
  12560. * Sets a boolean indicating if the dithering state is enabled or disabled
  12561. * @param value defines the dithering state
  12562. */
  12563. Engine.prototype.setDitheringState = function (value) {
  12564. if (value) {
  12565. this._gl.enable(this._gl.DITHER);
  12566. }
  12567. else {
  12568. this._gl.disable(this._gl.DITHER);
  12569. }
  12570. };
  12571. /**
  12572. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12573. * @param value defines the rasterizer state
  12574. */
  12575. Engine.prototype.setRasterizerState = function (value) {
  12576. if (value) {
  12577. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12578. }
  12579. else {
  12580. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12581. }
  12582. };
  12583. /**
  12584. * stop executing a render loop function and remove it from the execution array
  12585. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12586. */
  12587. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12588. if (!renderFunction) {
  12589. this._activeRenderLoops = [];
  12590. return;
  12591. }
  12592. var index = this._activeRenderLoops.indexOf(renderFunction);
  12593. if (index >= 0) {
  12594. this._activeRenderLoops.splice(index, 1);
  12595. }
  12596. };
  12597. /** @hidden */
  12598. Engine.prototype._renderLoop = function () {
  12599. if (!this._contextWasLost) {
  12600. var shouldRender = true;
  12601. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12602. shouldRender = false;
  12603. }
  12604. if (shouldRender) {
  12605. // Start new frame
  12606. this.beginFrame();
  12607. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12608. var renderFunction = this._activeRenderLoops[index];
  12609. renderFunction();
  12610. }
  12611. // Present
  12612. this.endFrame();
  12613. }
  12614. }
  12615. if (this._activeRenderLoops.length > 0) {
  12616. // Register new frame
  12617. var requester = null;
  12618. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12619. requester = this._vrDisplay;
  12620. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12621. }
  12622. else {
  12623. this._renderingQueueLaunched = false;
  12624. }
  12625. };
  12626. /**
  12627. * Register and execute a render loop. The engine can have more than one render function
  12628. * @param renderFunction defines the function to continuously execute
  12629. */
  12630. Engine.prototype.runRenderLoop = function (renderFunction) {
  12631. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12632. return;
  12633. }
  12634. this._activeRenderLoops.push(renderFunction);
  12635. if (!this._renderingQueueLaunched) {
  12636. this._renderingQueueLaunched = true;
  12637. this._bindedRenderFunction = this._renderLoop.bind(this);
  12638. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12639. }
  12640. };
  12641. /**
  12642. * Toggle full screen mode
  12643. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12644. * @param options defines an option object to be sent to the requestFullscreen function
  12645. */
  12646. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12647. if (this.isFullscreen) {
  12648. BABYLON.Tools.ExitFullscreen();
  12649. }
  12650. else {
  12651. this._pointerLockRequested = requestPointerLock;
  12652. if (this._renderingCanvas) {
  12653. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12654. }
  12655. }
  12656. };
  12657. /**
  12658. * Clear the current render buffer or the current render target (if any is set up)
  12659. * @param color defines the color to use
  12660. * @param backBuffer defines if the back buffer must be cleared
  12661. * @param depth defines if the depth buffer must be cleared
  12662. * @param stencil defines if the stencil buffer must be cleared
  12663. */
  12664. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12665. if (stencil === void 0) { stencil = false; }
  12666. this.applyStates();
  12667. var mode = 0;
  12668. if (backBuffer && color) {
  12669. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12670. mode |= this._gl.COLOR_BUFFER_BIT;
  12671. }
  12672. if (depth) {
  12673. this._gl.clearDepth(1.0);
  12674. mode |= this._gl.DEPTH_BUFFER_BIT;
  12675. }
  12676. if (stencil) {
  12677. this._gl.clearStencil(0);
  12678. mode |= this._gl.STENCIL_BUFFER_BIT;
  12679. }
  12680. this._gl.clear(mode);
  12681. };
  12682. /**
  12683. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12684. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12685. * @param y defines the y-coordinate of the corner of the clear rectangle
  12686. * @param width defines the width of the clear rectangle
  12687. * @param height defines the height of the clear rectangle
  12688. * @param clearColor defines the clear color
  12689. */
  12690. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12691. var gl = this._gl;
  12692. // Save state
  12693. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12694. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12695. // Change state
  12696. gl.enable(gl.SCISSOR_TEST);
  12697. gl.scissor(x, y, width, height);
  12698. // Clear
  12699. this.clear(clearColor, true, true, true);
  12700. // Restore state
  12701. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12702. if (curScissor === true) {
  12703. gl.enable(gl.SCISSOR_TEST);
  12704. }
  12705. else {
  12706. gl.disable(gl.SCISSOR_TEST);
  12707. }
  12708. };
  12709. /** @hidden */
  12710. Engine.prototype._viewport = function (x, y, width, height) {
  12711. if (x !== this._viewportCached.x ||
  12712. y !== this._viewportCached.y ||
  12713. width !== this._viewportCached.z ||
  12714. height !== this._viewportCached.w) {
  12715. this._viewportCached.x = x;
  12716. this._viewportCached.y = y;
  12717. this._viewportCached.z = width;
  12718. this._viewportCached.w = height;
  12719. this._gl.viewport(x, y, width, height);
  12720. }
  12721. };
  12722. /**
  12723. * Set the WebGL's viewport
  12724. * @param viewport defines the viewport element to be used
  12725. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12726. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12727. */
  12728. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12729. var width = requiredWidth || this.getRenderWidth();
  12730. var height = requiredHeight || this.getRenderHeight();
  12731. var x = viewport.x || 0;
  12732. var y = viewport.y || 0;
  12733. this._cachedViewport = viewport;
  12734. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12735. };
  12736. /**
  12737. * Directly set the WebGL Viewport
  12738. * @param x defines the x coordinate of the viewport (in screen space)
  12739. * @param y defines the y coordinate of the viewport (in screen space)
  12740. * @param width defines the width of the viewport (in screen space)
  12741. * @param height defines the height of the viewport (in screen space)
  12742. * @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
  12743. */
  12744. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12745. var currentViewport = this._cachedViewport;
  12746. this._cachedViewport = null;
  12747. this._viewport(x, y, width, height);
  12748. return currentViewport;
  12749. };
  12750. /**
  12751. * Begin a new frame
  12752. */
  12753. Engine.prototype.beginFrame = function () {
  12754. this.onBeginFrameObservable.notifyObservers(this);
  12755. this._measureFps();
  12756. };
  12757. /**
  12758. * Enf the current frame
  12759. */
  12760. Engine.prototype.endFrame = function () {
  12761. // Force a flush in case we are using a bad OS.
  12762. if (this._badOS) {
  12763. this.flushFramebuffer();
  12764. }
  12765. // Submit frame to the vr device, if enabled
  12766. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12767. // TODO: We should only submit the frame if we read frameData successfully.
  12768. this._vrDisplay.submitFrame();
  12769. }
  12770. this.onEndFrameObservable.notifyObservers(this);
  12771. };
  12772. /**
  12773. * Resize the view according to the canvas' size
  12774. */
  12775. Engine.prototype.resize = function () {
  12776. // We're not resizing the size of the canvas while in VR mode & presenting
  12777. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12778. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12779. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12780. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12781. }
  12782. };
  12783. /**
  12784. * Force a specific size of the canvas
  12785. * @param width defines the new canvas' width
  12786. * @param height defines the new canvas' height
  12787. */
  12788. Engine.prototype.setSize = function (width, height) {
  12789. if (!this._renderingCanvas) {
  12790. return;
  12791. }
  12792. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12793. return;
  12794. }
  12795. this._renderingCanvas.width = width;
  12796. this._renderingCanvas.height = height;
  12797. for (var index = 0; index < this.scenes.length; index++) {
  12798. var scene = this.scenes[index];
  12799. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12800. var cam = scene.cameras[camIndex];
  12801. cam._currentRenderId = 0;
  12802. }
  12803. }
  12804. if (this.onResizeObservable.hasObservers) {
  12805. this.onResizeObservable.notifyObservers(this);
  12806. }
  12807. };
  12808. // WebVR functions
  12809. /**
  12810. * Gets a boolean indicating if a webVR device was detected
  12811. * @returns true if a webVR device was detected
  12812. */
  12813. Engine.prototype.isVRDevicePresent = function () {
  12814. return !!this._vrDisplay;
  12815. };
  12816. /**
  12817. * Gets the current webVR device
  12818. * @returns the current webVR device (or null)
  12819. */
  12820. Engine.prototype.getVRDevice = function () {
  12821. return this._vrDisplay;
  12822. };
  12823. /**
  12824. * Initializes a webVR display and starts listening to display change events
  12825. * The onVRDisplayChangedObservable will be notified upon these changes
  12826. * @returns The onVRDisplayChangedObservable
  12827. */
  12828. Engine.prototype.initWebVR = function () {
  12829. this.initWebVRAsync();
  12830. return this.onVRDisplayChangedObservable;
  12831. };
  12832. /**
  12833. * Initializes a webVR display and starts listening to display change events
  12834. * The onVRDisplayChangedObservable will be notified upon these changes
  12835. * @returns A promise containing a VRDisplay and if vr is supported
  12836. */
  12837. Engine.prototype.initWebVRAsync = function () {
  12838. var _this = this;
  12839. var notifyObservers = function () {
  12840. var eventArgs = {
  12841. vrDisplay: _this._vrDisplay,
  12842. vrSupported: _this._vrSupported
  12843. };
  12844. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12845. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12846. };
  12847. if (!this._onVrDisplayConnect) {
  12848. this._onVrDisplayConnect = function (event) {
  12849. _this._vrDisplay = event.display;
  12850. notifyObservers();
  12851. };
  12852. this._onVrDisplayDisconnect = function () {
  12853. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12854. _this._vrDisplay = undefined;
  12855. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12856. notifyObservers();
  12857. };
  12858. this._onVrDisplayPresentChange = function () {
  12859. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12860. };
  12861. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12862. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12863. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12864. }
  12865. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12866. this._webVRInitPromise.then(notifyObservers);
  12867. return this._webVRInitPromise;
  12868. };
  12869. /**
  12870. * Call this function to switch to webVR mode
  12871. * Will do nothing if webVR is not supported or if there is no webVR device
  12872. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12873. */
  12874. Engine.prototype.enableVR = function () {
  12875. var _this = this;
  12876. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12877. var onResolved = function () {
  12878. _this.onVRRequestPresentComplete.notifyObservers(true);
  12879. _this._onVRFullScreenTriggered();
  12880. };
  12881. var onRejected = function () {
  12882. _this.onVRRequestPresentComplete.notifyObservers(false);
  12883. };
  12884. this.onVRRequestPresentStart.notifyObservers(this);
  12885. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12886. }
  12887. };
  12888. /**
  12889. * Call this function to leave webVR mode
  12890. * Will do nothing if webVR is not supported or if there is no webVR device
  12891. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12892. */
  12893. Engine.prototype.disableVR = function () {
  12894. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12895. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12896. }
  12897. };
  12898. Engine.prototype._getVRDisplaysAsync = function () {
  12899. var _this = this;
  12900. return new Promise(function (res, rej) {
  12901. if (navigator.getVRDisplays) {
  12902. navigator.getVRDisplays().then(function (devices) {
  12903. _this._vrSupported = true;
  12904. // note that devices may actually be an empty array. This is fine;
  12905. // we expect this._vrDisplay to be undefined in this case.
  12906. _this._vrDisplay = devices[0];
  12907. res({
  12908. vrDisplay: _this._vrDisplay,
  12909. vrSupported: _this._vrSupported
  12910. });
  12911. });
  12912. }
  12913. else {
  12914. _this._vrDisplay = undefined;
  12915. _this._vrSupported = false;
  12916. res({
  12917. vrDisplay: _this._vrDisplay,
  12918. vrSupported: _this._vrSupported
  12919. });
  12920. }
  12921. });
  12922. };
  12923. /**
  12924. * Binds the frame buffer to the specified texture.
  12925. * @param texture The texture to render to or null for the default canvas
  12926. * @param faceIndex The face of the texture to render to in case of cube texture
  12927. * @param requiredWidth The width of the target to render to
  12928. * @param requiredHeight The height of the target to render to
  12929. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12930. * @param depthStencilTexture The depth stencil texture to use to render
  12931. * @param lodLevel defines le lod level to bind to the frame buffer
  12932. */
  12933. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12934. if (lodLevel === void 0) { lodLevel = 0; }
  12935. if (this._currentRenderTarget) {
  12936. this.unBindFramebuffer(this._currentRenderTarget);
  12937. }
  12938. this._currentRenderTarget = texture;
  12939. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12940. var gl = this._gl;
  12941. if (texture.isCube) {
  12942. if (faceIndex === undefined) {
  12943. faceIndex = 0;
  12944. }
  12945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12946. if (depthStencilTexture) {
  12947. if (depthStencilTexture._generateStencilBuffer) {
  12948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12949. }
  12950. else {
  12951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12952. }
  12953. }
  12954. }
  12955. if (this._cachedViewport && !forceFullscreenViewport) {
  12956. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12957. }
  12958. else {
  12959. if (!requiredWidth) {
  12960. requiredWidth = texture.width;
  12961. if (lodLevel) {
  12962. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12963. }
  12964. }
  12965. if (!requiredHeight) {
  12966. requiredHeight = texture.height;
  12967. if (lodLevel) {
  12968. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12969. }
  12970. }
  12971. this._viewport(0, 0, requiredWidth, requiredHeight);
  12972. }
  12973. this.wipeCaches();
  12974. };
  12975. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12976. if (this._currentFramebuffer !== framebuffer) {
  12977. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12978. this._currentFramebuffer = framebuffer;
  12979. }
  12980. };
  12981. /**
  12982. * Unbind the current render target texture from the webGL context
  12983. * @param texture defines the render target texture to unbind
  12984. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12985. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12986. */
  12987. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12988. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12989. this._currentRenderTarget = null;
  12990. // If MSAA, we need to bitblt back to main texture
  12991. var gl = this._gl;
  12992. if (texture._MSAAFramebuffer) {
  12993. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12994. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12995. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12996. }
  12997. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12998. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12999. gl.generateMipmap(gl.TEXTURE_2D);
  13000. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13001. }
  13002. if (onBeforeUnbind) {
  13003. if (texture._MSAAFramebuffer) {
  13004. // Bind the correct framebuffer
  13005. this.bindUnboundFramebuffer(texture._framebuffer);
  13006. }
  13007. onBeforeUnbind();
  13008. }
  13009. this.bindUnboundFramebuffer(null);
  13010. };
  13011. /**
  13012. * Unbind a list of render target textures from the webGL context
  13013. * This is used only when drawBuffer extension or webGL2 are active
  13014. * @param textures defines the render target textures to unbind
  13015. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13016. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13017. */
  13018. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13019. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13020. this._currentRenderTarget = null;
  13021. // If MSAA, we need to bitblt back to main texture
  13022. var gl = this._gl;
  13023. if (textures[0]._MSAAFramebuffer) {
  13024. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13025. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13026. var attachments = textures[0]._attachments;
  13027. if (!attachments) {
  13028. attachments = new Array(textures.length);
  13029. textures[0]._attachments = attachments;
  13030. }
  13031. for (var i = 0; i < textures.length; i++) {
  13032. var texture = textures[i];
  13033. for (var j = 0; j < attachments.length; j++) {
  13034. attachments[j] = gl.NONE;
  13035. }
  13036. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13037. gl.readBuffer(attachments[i]);
  13038. gl.drawBuffers(attachments);
  13039. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13040. }
  13041. for (var i = 0; i < attachments.length; i++) {
  13042. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13043. }
  13044. gl.drawBuffers(attachments);
  13045. }
  13046. for (var i = 0; i < textures.length; i++) {
  13047. var texture = textures[i];
  13048. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13049. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13050. gl.generateMipmap(gl.TEXTURE_2D);
  13051. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13052. }
  13053. }
  13054. if (onBeforeUnbind) {
  13055. if (textures[0]._MSAAFramebuffer) {
  13056. // Bind the correct framebuffer
  13057. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13058. }
  13059. onBeforeUnbind();
  13060. }
  13061. this.bindUnboundFramebuffer(null);
  13062. };
  13063. /**
  13064. * Force the mipmap generation for the given render target texture
  13065. * @param texture defines the render target texture to use
  13066. */
  13067. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13068. if (texture.generateMipMaps) {
  13069. var gl = this._gl;
  13070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13071. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13073. }
  13074. };
  13075. /**
  13076. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13077. */
  13078. Engine.prototype.flushFramebuffer = function () {
  13079. this._gl.flush();
  13080. };
  13081. /**
  13082. * Unbind the current render target and bind the default framebuffer
  13083. */
  13084. Engine.prototype.restoreDefaultFramebuffer = function () {
  13085. if (this._currentRenderTarget) {
  13086. this.unBindFramebuffer(this._currentRenderTarget);
  13087. }
  13088. else {
  13089. this.bindUnboundFramebuffer(null);
  13090. }
  13091. if (this._cachedViewport) {
  13092. this.setViewport(this._cachedViewport);
  13093. }
  13094. this.wipeCaches();
  13095. };
  13096. // UBOs
  13097. /**
  13098. * Create an uniform buffer
  13099. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13100. * @param elements defines the content of the uniform buffer
  13101. * @returns the webGL uniform buffer
  13102. */
  13103. Engine.prototype.createUniformBuffer = function (elements) {
  13104. var ubo = this._gl.createBuffer();
  13105. if (!ubo) {
  13106. throw new Error("Unable to create uniform buffer");
  13107. }
  13108. this.bindUniformBuffer(ubo);
  13109. if (elements instanceof Float32Array) {
  13110. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13111. }
  13112. else {
  13113. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13114. }
  13115. this.bindUniformBuffer(null);
  13116. ubo.references = 1;
  13117. return ubo;
  13118. };
  13119. /**
  13120. * Create a dynamic uniform buffer
  13121. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13122. * @param elements defines the content of the uniform buffer
  13123. * @returns the webGL uniform buffer
  13124. */
  13125. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13126. var ubo = this._gl.createBuffer();
  13127. if (!ubo) {
  13128. throw new Error("Unable to create dynamic uniform buffer");
  13129. }
  13130. this.bindUniformBuffer(ubo);
  13131. if (elements instanceof Float32Array) {
  13132. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13133. }
  13134. else {
  13135. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13136. }
  13137. this.bindUniformBuffer(null);
  13138. ubo.references = 1;
  13139. return ubo;
  13140. };
  13141. /**
  13142. * Update an existing uniform buffer
  13143. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13144. * @param uniformBuffer defines the target uniform buffer
  13145. * @param elements defines the content to update
  13146. * @param offset defines the offset in the uniform buffer where update should start
  13147. * @param count defines the size of the data to update
  13148. */
  13149. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13150. this.bindUniformBuffer(uniformBuffer);
  13151. if (offset === undefined) {
  13152. offset = 0;
  13153. }
  13154. if (count === undefined) {
  13155. if (elements instanceof Float32Array) {
  13156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13157. }
  13158. else {
  13159. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13160. }
  13161. }
  13162. else {
  13163. if (elements instanceof Float32Array) {
  13164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13165. }
  13166. else {
  13167. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13168. }
  13169. }
  13170. this.bindUniformBuffer(null);
  13171. };
  13172. // VBOs
  13173. Engine.prototype._resetVertexBufferBinding = function () {
  13174. this.bindArrayBuffer(null);
  13175. this._cachedVertexBuffers = null;
  13176. };
  13177. /**
  13178. * Creates a vertex buffer
  13179. * @param data the data for the vertex buffer
  13180. * @returns the new WebGL static buffer
  13181. */
  13182. Engine.prototype.createVertexBuffer = function (data) {
  13183. var vbo = this._gl.createBuffer();
  13184. if (!vbo) {
  13185. throw new Error("Unable to create vertex buffer");
  13186. }
  13187. this.bindArrayBuffer(vbo);
  13188. if (data instanceof Array) {
  13189. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13190. }
  13191. else {
  13192. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13193. }
  13194. this._resetVertexBufferBinding();
  13195. vbo.references = 1;
  13196. return vbo;
  13197. };
  13198. /**
  13199. * Creates a dynamic vertex buffer
  13200. * @param data the data for the dynamic vertex buffer
  13201. * @returns the new WebGL dynamic buffer
  13202. */
  13203. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13204. var vbo = this._gl.createBuffer();
  13205. if (!vbo) {
  13206. throw new Error("Unable to create dynamic vertex buffer");
  13207. }
  13208. this.bindArrayBuffer(vbo);
  13209. if (data instanceof Array) {
  13210. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13211. }
  13212. else {
  13213. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13214. }
  13215. this._resetVertexBufferBinding();
  13216. vbo.references = 1;
  13217. return vbo;
  13218. };
  13219. /**
  13220. * Update a dynamic index buffer
  13221. * @param indexBuffer defines the target index buffer
  13222. * @param indices defines the data to update
  13223. * @param offset defines the offset in the target index buffer where update should start
  13224. */
  13225. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13226. if (offset === void 0) { offset = 0; }
  13227. // Force cache update
  13228. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13229. this.bindIndexBuffer(indexBuffer);
  13230. var arrayBuffer;
  13231. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13232. arrayBuffer = indices;
  13233. }
  13234. else {
  13235. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13236. }
  13237. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13238. this._resetIndexBufferBinding();
  13239. };
  13240. /**
  13241. * Updates a dynamic vertex buffer.
  13242. * @param vertexBuffer the vertex buffer to update
  13243. * @param data the data used to update the vertex buffer
  13244. * @param byteOffset the byte offset of the data
  13245. * @param byteLength the byte length of the data
  13246. */
  13247. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13248. this.bindArrayBuffer(vertexBuffer);
  13249. if (byteOffset === undefined) {
  13250. byteOffset = 0;
  13251. }
  13252. if (byteLength === undefined) {
  13253. if (data instanceof Array) {
  13254. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13255. }
  13256. else {
  13257. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13258. }
  13259. }
  13260. else {
  13261. if (data instanceof Array) {
  13262. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13263. }
  13264. else {
  13265. if (data instanceof ArrayBuffer) {
  13266. data = new Uint8Array(data, byteOffset, byteLength);
  13267. }
  13268. else {
  13269. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13270. }
  13271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13272. }
  13273. }
  13274. this._resetVertexBufferBinding();
  13275. };
  13276. Engine.prototype._resetIndexBufferBinding = function () {
  13277. this.bindIndexBuffer(null);
  13278. this._cachedIndexBuffer = null;
  13279. };
  13280. /**
  13281. * Creates a new index buffer
  13282. * @param indices defines the content of the index buffer
  13283. * @param updatable defines if the index buffer must be updatable
  13284. * @returns a new webGL buffer
  13285. */
  13286. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13287. var vbo = this._gl.createBuffer();
  13288. if (!vbo) {
  13289. throw new Error("Unable to create index buffer");
  13290. }
  13291. this.bindIndexBuffer(vbo);
  13292. // Check for 32 bits indices
  13293. var arrayBuffer;
  13294. var need32Bits = false;
  13295. if (indices instanceof Uint16Array) {
  13296. arrayBuffer = indices;
  13297. }
  13298. else {
  13299. //check 32 bit support
  13300. if (this._caps.uintIndices) {
  13301. if (indices instanceof Uint32Array) {
  13302. arrayBuffer = indices;
  13303. need32Bits = true;
  13304. }
  13305. else {
  13306. //number[] or Int32Array, check if 32 bit is necessary
  13307. for (var index = 0; index < indices.length; index++) {
  13308. if (indices[index] > 65535) {
  13309. need32Bits = true;
  13310. break;
  13311. }
  13312. }
  13313. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13314. }
  13315. }
  13316. else {
  13317. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13318. arrayBuffer = new Uint16Array(indices);
  13319. }
  13320. }
  13321. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13322. this._resetIndexBufferBinding();
  13323. vbo.references = 1;
  13324. vbo.is32Bits = need32Bits;
  13325. return vbo;
  13326. };
  13327. /**
  13328. * Bind a webGL buffer to the webGL context
  13329. * @param buffer defines the buffer to bind
  13330. */
  13331. Engine.prototype.bindArrayBuffer = function (buffer) {
  13332. if (!this._vaoRecordInProgress) {
  13333. this._unbindVertexArrayObject();
  13334. }
  13335. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13336. };
  13337. /**
  13338. * Bind an uniform buffer to the current webGL context
  13339. * @param buffer defines the buffer to bind
  13340. */
  13341. Engine.prototype.bindUniformBuffer = function (buffer) {
  13342. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13343. };
  13344. /**
  13345. * Bind a buffer to the current webGL context at a given location
  13346. * @param buffer defines the buffer to bind
  13347. * @param location defines the index where to bind the buffer
  13348. */
  13349. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13350. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13351. };
  13352. /**
  13353. * Bind a specific block at a given index in a specific shader program
  13354. * @param shaderProgram defines the shader program
  13355. * @param blockName defines the block name
  13356. * @param index defines the index where to bind the block
  13357. */
  13358. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13359. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13360. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13361. };
  13362. ;
  13363. Engine.prototype.bindIndexBuffer = function (buffer) {
  13364. if (!this._vaoRecordInProgress) {
  13365. this._unbindVertexArrayObject();
  13366. }
  13367. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13368. };
  13369. Engine.prototype.bindBuffer = function (buffer, target) {
  13370. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13371. this._gl.bindBuffer(target, buffer);
  13372. this._currentBoundBuffer[target] = buffer;
  13373. }
  13374. };
  13375. /**
  13376. * update the bound buffer with the given data
  13377. * @param data defines the data to update
  13378. */
  13379. Engine.prototype.updateArrayBuffer = function (data) {
  13380. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13381. };
  13382. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13383. var pointer = this._currentBufferPointers[indx];
  13384. var changed = false;
  13385. if (!pointer.active) {
  13386. changed = true;
  13387. pointer.active = true;
  13388. pointer.index = indx;
  13389. pointer.size = size;
  13390. pointer.type = type;
  13391. pointer.normalized = normalized;
  13392. pointer.stride = stride;
  13393. pointer.offset = offset;
  13394. pointer.buffer = buffer;
  13395. }
  13396. else {
  13397. if (pointer.buffer !== buffer) {
  13398. pointer.buffer = buffer;
  13399. changed = true;
  13400. }
  13401. if (pointer.size !== size) {
  13402. pointer.size = size;
  13403. changed = true;
  13404. }
  13405. if (pointer.type !== type) {
  13406. pointer.type = type;
  13407. changed = true;
  13408. }
  13409. if (pointer.normalized !== normalized) {
  13410. pointer.normalized = normalized;
  13411. changed = true;
  13412. }
  13413. if (pointer.stride !== stride) {
  13414. pointer.stride = stride;
  13415. changed = true;
  13416. }
  13417. if (pointer.offset !== offset) {
  13418. pointer.offset = offset;
  13419. changed = true;
  13420. }
  13421. }
  13422. if (changed || this._vaoRecordInProgress) {
  13423. this.bindArrayBuffer(buffer);
  13424. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13425. }
  13426. };
  13427. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13428. if (indexBuffer == null) {
  13429. return;
  13430. }
  13431. if (this._cachedIndexBuffer !== indexBuffer) {
  13432. this._cachedIndexBuffer = indexBuffer;
  13433. this.bindIndexBuffer(indexBuffer);
  13434. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13435. }
  13436. };
  13437. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13438. var attributes = effect.getAttributesNames();
  13439. if (!this._vaoRecordInProgress) {
  13440. this._unbindVertexArrayObject();
  13441. }
  13442. this.unbindAllAttributes();
  13443. for (var index = 0; index < attributes.length; index++) {
  13444. var order = effect.getAttributeLocation(index);
  13445. if (order >= 0) {
  13446. var vertexBuffer = vertexBuffers[attributes[index]];
  13447. if (!vertexBuffer) {
  13448. continue;
  13449. }
  13450. this._gl.enableVertexAttribArray(order);
  13451. if (!this._vaoRecordInProgress) {
  13452. this._vertexAttribArraysEnabled[order] = true;
  13453. }
  13454. var buffer = vertexBuffer.getBuffer();
  13455. if (buffer) {
  13456. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13457. if (vertexBuffer.getIsInstanced()) {
  13458. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13459. if (!this._vaoRecordInProgress) {
  13460. this._currentInstanceLocations.push(order);
  13461. this._currentInstanceBuffers.push(buffer);
  13462. }
  13463. }
  13464. }
  13465. }
  13466. }
  13467. };
  13468. /**
  13469. * Records a vertex array object
  13470. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13471. * @param vertexBuffers defines the list of vertex buffers to store
  13472. * @param indexBuffer defines the index buffer to store
  13473. * @param effect defines the effect to store
  13474. * @returns the new vertex array object
  13475. */
  13476. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13477. var vao = this._gl.createVertexArray();
  13478. this._vaoRecordInProgress = true;
  13479. this._gl.bindVertexArray(vao);
  13480. this._mustWipeVertexAttributes = true;
  13481. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13482. this.bindIndexBuffer(indexBuffer);
  13483. this._vaoRecordInProgress = false;
  13484. this._gl.bindVertexArray(null);
  13485. return vao;
  13486. };
  13487. /**
  13488. * Bind a specific vertex array object
  13489. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13490. * @param vertexArrayObject defines the vertex array object to bind
  13491. * @param indexBuffer defines the index buffer to bind
  13492. */
  13493. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13494. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13495. this._cachedVertexArrayObject = vertexArrayObject;
  13496. this._gl.bindVertexArray(vertexArrayObject);
  13497. this._cachedVertexBuffers = null;
  13498. this._cachedIndexBuffer = null;
  13499. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13500. this._mustWipeVertexAttributes = true;
  13501. }
  13502. };
  13503. /**
  13504. * Bind webGl buffers directly to the webGL context
  13505. * @param vertexBuffer defines the vertex buffer to bind
  13506. * @param indexBuffer defines the index buffer to bind
  13507. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13508. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13509. * @param effect defines the effect associated with the vertex buffer
  13510. */
  13511. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13512. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13513. this._cachedVertexBuffers = vertexBuffer;
  13514. this._cachedEffectForVertexBuffers = effect;
  13515. var attributesCount = effect.getAttributesCount();
  13516. this._unbindVertexArrayObject();
  13517. this.unbindAllAttributes();
  13518. var offset = 0;
  13519. for (var index = 0; index < attributesCount; index++) {
  13520. if (index < vertexDeclaration.length) {
  13521. var order = effect.getAttributeLocation(index);
  13522. if (order >= 0) {
  13523. this._gl.enableVertexAttribArray(order);
  13524. this._vertexAttribArraysEnabled[order] = true;
  13525. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13526. }
  13527. offset += vertexDeclaration[index] * 4;
  13528. }
  13529. }
  13530. }
  13531. this._bindIndexBufferWithCache(indexBuffer);
  13532. };
  13533. Engine.prototype._unbindVertexArrayObject = function () {
  13534. if (!this._cachedVertexArrayObject) {
  13535. return;
  13536. }
  13537. this._cachedVertexArrayObject = null;
  13538. this._gl.bindVertexArray(null);
  13539. };
  13540. /**
  13541. * Bind a list of vertex buffers to the webGL context
  13542. * @param vertexBuffers defines the list of vertex buffers to bind
  13543. * @param indexBuffer defines the index buffer to bind
  13544. * @param effect defines the effect associated with the vertex buffers
  13545. */
  13546. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13547. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13548. this._cachedVertexBuffers = vertexBuffers;
  13549. this._cachedEffectForVertexBuffers = effect;
  13550. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13551. }
  13552. this._bindIndexBufferWithCache(indexBuffer);
  13553. };
  13554. /**
  13555. * Unbind all instance attributes
  13556. */
  13557. Engine.prototype.unbindInstanceAttributes = function () {
  13558. var boundBuffer;
  13559. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13560. var instancesBuffer = this._currentInstanceBuffers[i];
  13561. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13562. boundBuffer = instancesBuffer;
  13563. this.bindArrayBuffer(instancesBuffer);
  13564. }
  13565. var offsetLocation = this._currentInstanceLocations[i];
  13566. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13567. }
  13568. this._currentInstanceBuffers.length = 0;
  13569. this._currentInstanceLocations.length = 0;
  13570. };
  13571. /**
  13572. * Release and free the memory of a vertex array object
  13573. * @param vao defines the vertex array object to delete
  13574. */
  13575. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13576. this._gl.deleteVertexArray(vao);
  13577. };
  13578. /** @hidden */
  13579. Engine.prototype._releaseBuffer = function (buffer) {
  13580. buffer.references--;
  13581. if (buffer.references === 0) {
  13582. this._gl.deleteBuffer(buffer);
  13583. return true;
  13584. }
  13585. return false;
  13586. };
  13587. /**
  13588. * Creates a webGL buffer to use with instanciation
  13589. * @param capacity defines the size of the buffer
  13590. * @returns the webGL buffer
  13591. */
  13592. Engine.prototype.createInstancesBuffer = function (capacity) {
  13593. var buffer = this._gl.createBuffer();
  13594. if (!buffer) {
  13595. throw new Error("Unable to create instance buffer");
  13596. }
  13597. buffer.capacity = capacity;
  13598. this.bindArrayBuffer(buffer);
  13599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13600. return buffer;
  13601. };
  13602. /**
  13603. * Delete a webGL buffer used with instanciation
  13604. * @param buffer defines the webGL buffer to delete
  13605. */
  13606. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13607. this._gl.deleteBuffer(buffer);
  13608. };
  13609. /**
  13610. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13611. * @param instancesBuffer defines the webGL buffer to update and bind
  13612. * @param data defines the data to store in the buffer
  13613. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13614. */
  13615. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13616. this.bindArrayBuffer(instancesBuffer);
  13617. if (data) {
  13618. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13619. }
  13620. if (offsetLocations[0].index !== undefined) {
  13621. var stride = 0;
  13622. for (var i = 0; i < offsetLocations.length; i++) {
  13623. var ai = offsetLocations[i];
  13624. stride += ai.attributeSize * 4;
  13625. }
  13626. for (var i = 0; i < offsetLocations.length; i++) {
  13627. var ai = offsetLocations[i];
  13628. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13629. this._gl.enableVertexAttribArray(ai.index);
  13630. this._vertexAttribArraysEnabled[ai.index] = true;
  13631. }
  13632. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13633. this._gl.vertexAttribDivisor(ai.index, 1);
  13634. this._currentInstanceLocations.push(ai.index);
  13635. this._currentInstanceBuffers.push(instancesBuffer);
  13636. }
  13637. }
  13638. else {
  13639. for (var index = 0; index < 4; index++) {
  13640. var offsetLocation = offsetLocations[index];
  13641. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13642. this._gl.enableVertexAttribArray(offsetLocation);
  13643. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13644. }
  13645. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13646. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13647. this._currentInstanceLocations.push(offsetLocation);
  13648. this._currentInstanceBuffers.push(instancesBuffer);
  13649. }
  13650. }
  13651. };
  13652. /**
  13653. * Apply all cached states (depth, culling, stencil and alpha)
  13654. */
  13655. Engine.prototype.applyStates = function () {
  13656. this._depthCullingState.apply(this._gl);
  13657. this._stencilState.apply(this._gl);
  13658. this._alphaState.apply(this._gl);
  13659. };
  13660. /**
  13661. * Send a draw order
  13662. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13663. * @param indexStart defines the starting index
  13664. * @param indexCount defines the number of index to draw
  13665. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13666. */
  13667. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13668. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13669. };
  13670. /**
  13671. * Draw a list of points
  13672. * @param verticesStart defines the index of first vertex to draw
  13673. * @param verticesCount defines the count of vertices to draw
  13674. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13675. */
  13676. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13677. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13678. };
  13679. /**
  13680. * Draw a list of unindexed primitives
  13681. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13682. * @param verticesStart defines the index of first vertex to draw
  13683. * @param verticesCount defines the count of vertices to draw
  13684. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13685. */
  13686. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13687. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13688. };
  13689. /**
  13690. * Draw a list of indexed primitives
  13691. * @param fillMode defines the primitive to use
  13692. * @param indexStart defines the starting index
  13693. * @param indexCount defines the number of index to draw
  13694. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13695. */
  13696. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13697. // Apply states
  13698. this.applyStates();
  13699. this._drawCalls.addCount(1, false);
  13700. // Render
  13701. var drawMode = this._drawMode(fillMode);
  13702. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13703. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13704. if (instancesCount) {
  13705. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13706. }
  13707. else {
  13708. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13709. }
  13710. };
  13711. /**
  13712. * Draw a list of unindexed primitives
  13713. * @param fillMode defines the primitive to use
  13714. * @param verticesStart defines the index of first vertex to draw
  13715. * @param verticesCount defines the count of vertices to draw
  13716. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13717. */
  13718. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13719. // Apply states
  13720. this.applyStates();
  13721. this._drawCalls.addCount(1, false);
  13722. var drawMode = this._drawMode(fillMode);
  13723. if (instancesCount) {
  13724. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13725. }
  13726. else {
  13727. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13728. }
  13729. };
  13730. Engine.prototype._drawMode = function (fillMode) {
  13731. switch (fillMode) {
  13732. // Triangle views
  13733. case BABYLON.Material.TriangleFillMode:
  13734. return this._gl.TRIANGLES;
  13735. case BABYLON.Material.PointFillMode:
  13736. return this._gl.POINTS;
  13737. case BABYLON.Material.WireFrameFillMode:
  13738. return this._gl.LINES;
  13739. // Draw modes
  13740. case BABYLON.Material.PointListDrawMode:
  13741. return this._gl.POINTS;
  13742. case BABYLON.Material.LineListDrawMode:
  13743. return this._gl.LINES;
  13744. case BABYLON.Material.LineLoopDrawMode:
  13745. return this._gl.LINE_LOOP;
  13746. case BABYLON.Material.LineStripDrawMode:
  13747. return this._gl.LINE_STRIP;
  13748. case BABYLON.Material.TriangleStripDrawMode:
  13749. return this._gl.TRIANGLE_STRIP;
  13750. case BABYLON.Material.TriangleFanDrawMode:
  13751. return this._gl.TRIANGLE_FAN;
  13752. default:
  13753. return this._gl.TRIANGLES;
  13754. }
  13755. };
  13756. // Shaders
  13757. /** @hidden */
  13758. Engine.prototype._releaseEffect = function (effect) {
  13759. if (this._compiledEffects[effect._key]) {
  13760. delete this._compiledEffects[effect._key];
  13761. this._deleteProgram(effect.getProgram());
  13762. }
  13763. };
  13764. /** @hidden */
  13765. Engine.prototype._deleteProgram = function (program) {
  13766. if (program) {
  13767. program.__SPECTOR_rebuildProgram = null;
  13768. if (program.transformFeedback) {
  13769. this.deleteTransformFeedback(program.transformFeedback);
  13770. program.transformFeedback = null;
  13771. }
  13772. this._gl.deleteProgram(program);
  13773. }
  13774. };
  13775. /**
  13776. * Create a new effect (used to store vertex/fragment shaders)
  13777. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13778. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13779. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13780. * @param samplers defines an array of string used to represent textures
  13781. * @param defines defines the string containing the defines to use to compile the shaders
  13782. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13783. * @param onCompiled defines a function to call when the effect creation is successful
  13784. * @param onError defines a function to call when the effect creation has failed
  13785. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13786. * @returns the new Effect
  13787. */
  13788. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13789. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13790. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13791. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13792. if (this._compiledEffects[name]) {
  13793. var compiledEffect = this._compiledEffects[name];
  13794. if (onCompiled && compiledEffect.isReady()) {
  13795. onCompiled(compiledEffect);
  13796. }
  13797. return compiledEffect;
  13798. }
  13799. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13800. effect._key = name;
  13801. this._compiledEffects[name] = effect;
  13802. return effect;
  13803. };
  13804. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13805. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13806. };
  13807. ;
  13808. Engine.prototype._compileRawShader = function (source, type) {
  13809. var gl = this._gl;
  13810. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13811. gl.shaderSource(shader, source);
  13812. gl.compileShader(shader);
  13813. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13814. var log = gl.getShaderInfoLog(shader);
  13815. if (log) {
  13816. throw new Error(log);
  13817. }
  13818. }
  13819. if (!shader) {
  13820. throw new Error("Something went wrong while compile the shader.");
  13821. }
  13822. return shader;
  13823. };
  13824. ;
  13825. /**
  13826. * Directly creates a webGL program
  13827. * @param vertexCode defines the vertex shader code to use
  13828. * @param fragmentCode defines the fragment shader code to use
  13829. * @param context defines the webGL context to use (if not set, the current one will be used)
  13830. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13831. * @returns the new webGL program
  13832. */
  13833. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13834. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13835. context = context || this._gl;
  13836. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13837. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13838. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13839. };
  13840. /**
  13841. * Creates a webGL program
  13842. * @param vertexCode defines the vertex shader code to use
  13843. * @param fragmentCode defines the fragment shader code to use
  13844. * @param defines defines the string containing the defines to use to compile the shaders
  13845. * @param context defines the webGL context to use (if not set, the current one will be used)
  13846. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13847. * @returns the new webGL program
  13848. */
  13849. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13850. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13851. context = context || this._gl;
  13852. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13853. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13854. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13855. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13856. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13857. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13858. return program;
  13859. };
  13860. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13861. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13862. var shaderProgram = context.createProgram();
  13863. if (!shaderProgram) {
  13864. throw new Error("Unable to create program");
  13865. }
  13866. context.attachShader(shaderProgram, vertexShader);
  13867. context.attachShader(shaderProgram, fragmentShader);
  13868. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13869. var transformFeedback = this.createTransformFeedback();
  13870. this.bindTransformFeedback(transformFeedback);
  13871. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13872. shaderProgram.transformFeedback = transformFeedback;
  13873. }
  13874. context.linkProgram(shaderProgram);
  13875. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13876. this.bindTransformFeedback(null);
  13877. }
  13878. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13879. if (!linked) {
  13880. var error = context.getProgramInfoLog(shaderProgram);
  13881. if (error) {
  13882. throw new Error(error);
  13883. }
  13884. }
  13885. if (this.validateShaderPrograms) {
  13886. context.validateProgram(shaderProgram);
  13887. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13888. if (!validated) {
  13889. var error = context.getProgramInfoLog(shaderProgram);
  13890. if (error) {
  13891. throw new Error(error);
  13892. }
  13893. }
  13894. }
  13895. context.deleteShader(vertexShader);
  13896. context.deleteShader(fragmentShader);
  13897. return shaderProgram;
  13898. };
  13899. /**
  13900. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13901. * @param shaderProgram defines the webGL program to use
  13902. * @param uniformsNames defines the list of uniform names
  13903. * @returns an array of webGL uniform locations
  13904. */
  13905. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13906. var results = new Array();
  13907. for (var index = 0; index < uniformsNames.length; index++) {
  13908. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13909. }
  13910. return results;
  13911. };
  13912. /**
  13913. * Gets the lsit of active attributes for a given webGL program
  13914. * @param shaderProgram defines the webGL program to use
  13915. * @param attributesNames defines the list of attribute names to get
  13916. * @returns an array of indices indicating the offset of each attribute
  13917. */
  13918. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13919. var results = [];
  13920. for (var index = 0; index < attributesNames.length; index++) {
  13921. try {
  13922. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13923. }
  13924. catch (e) {
  13925. results.push(-1);
  13926. }
  13927. }
  13928. return results;
  13929. };
  13930. /**
  13931. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13932. * @param effect defines the effect to activate
  13933. */
  13934. Engine.prototype.enableEffect = function (effect) {
  13935. if (!effect || effect === this._currentEffect) {
  13936. return;
  13937. }
  13938. // Use program
  13939. this.bindSamplers(effect);
  13940. this._currentEffect = effect;
  13941. if (effect.onBind) {
  13942. effect.onBind(effect);
  13943. }
  13944. if (effect._onBindObservable) {
  13945. effect._onBindObservable.notifyObservers(effect);
  13946. }
  13947. };
  13948. /**
  13949. * Set the value of an uniform to an array of int32
  13950. * @param uniform defines the webGL uniform location where to store the value
  13951. * @param array defines the array of int32 to store
  13952. */
  13953. Engine.prototype.setIntArray = function (uniform, array) {
  13954. if (!uniform)
  13955. return;
  13956. this._gl.uniform1iv(uniform, array);
  13957. };
  13958. /**
  13959. * Set the value of an uniform to an array of int32 (stored as vec2)
  13960. * @param uniform defines the webGL uniform location where to store the value
  13961. * @param array defines the array of int32 to store
  13962. */
  13963. Engine.prototype.setIntArray2 = function (uniform, array) {
  13964. if (!uniform || array.length % 2 !== 0)
  13965. return;
  13966. this._gl.uniform2iv(uniform, array);
  13967. };
  13968. /**
  13969. * Set the value of an uniform to an array of int32 (stored as vec3)
  13970. * @param uniform defines the webGL uniform location where to store the value
  13971. * @param array defines the array of int32 to store
  13972. */
  13973. Engine.prototype.setIntArray3 = function (uniform, array) {
  13974. if (!uniform || array.length % 3 !== 0)
  13975. return;
  13976. this._gl.uniform3iv(uniform, array);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to an array of int32 (stored as vec4)
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param array defines the array of int32 to store
  13982. */
  13983. Engine.prototype.setIntArray4 = function (uniform, array) {
  13984. if (!uniform || array.length % 4 !== 0)
  13985. return;
  13986. this._gl.uniform4iv(uniform, array);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of float32
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of float32 to store
  13992. */
  13993. Engine.prototype.setFloatArray = function (uniform, array) {
  13994. if (!uniform)
  13995. return;
  13996. this._gl.uniform1fv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of float32 (stored as vec2)
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of float32 to store
  14002. */
  14003. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14004. if (!uniform || array.length % 2 !== 0)
  14005. return;
  14006. this._gl.uniform2fv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of float32 (stored as vec3)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of float32 to store
  14012. */
  14013. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14014. if (!uniform || array.length % 3 !== 0)
  14015. return;
  14016. this._gl.uniform3fv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of float32 (stored as vec4)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param array defines the array of float32 to store
  14022. */
  14023. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14024. if (!uniform || array.length % 4 !== 0)
  14025. return;
  14026. this._gl.uniform4fv(uniform, array);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to an array of number
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param array defines the array of number to store
  14032. */
  14033. Engine.prototype.setArray = function (uniform, array) {
  14034. if (!uniform)
  14035. return;
  14036. this._gl.uniform1fv(uniform, array);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to an array of number (stored as vec2)
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param array defines the array of number to store
  14042. */
  14043. Engine.prototype.setArray2 = function (uniform, array) {
  14044. if (!uniform || array.length % 2 !== 0)
  14045. return;
  14046. this._gl.uniform2fv(uniform, array);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to an array of number (stored as vec3)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param array defines the array of number to store
  14052. */
  14053. Engine.prototype.setArray3 = function (uniform, array) {
  14054. if (!uniform || array.length % 3 !== 0)
  14055. return;
  14056. this._gl.uniform3fv(uniform, array);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to an array of number (stored as vec4)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param array defines the array of number to store
  14062. */
  14063. Engine.prototype.setArray4 = function (uniform, array) {
  14064. if (!uniform || array.length % 4 !== 0)
  14065. return;
  14066. this._gl.uniform4fv(uniform, array);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to an array of float32 (stored as matrices)
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param matrices defines the array of float32 to store
  14072. */
  14073. Engine.prototype.setMatrices = function (uniform, matrices) {
  14074. if (!uniform)
  14075. return;
  14076. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to a matrix
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param matrix defines the matrix to store
  14082. */
  14083. Engine.prototype.setMatrix = function (uniform, matrix) {
  14084. if (!uniform)
  14085. return;
  14086. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14087. };
  14088. /**
  14089. * Set the value of an uniform to a matrix (3x3)
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14092. */
  14093. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14094. if (!uniform)
  14095. return;
  14096. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14097. };
  14098. /**
  14099. * Set the value of an uniform to a matrix (2x2)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14102. */
  14103. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14104. if (!uniform)
  14105. return;
  14106. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to a number (int)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param value defines the int number to store
  14112. */
  14113. Engine.prototype.setInt = function (uniform, value) {
  14114. if (!uniform)
  14115. return;
  14116. this._gl.uniform1i(uniform, value);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to a number (float)
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param value defines the float number to store
  14122. */
  14123. Engine.prototype.setFloat = function (uniform, value) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform1f(uniform, value);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a vec2
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param x defines the 1st component of the value
  14132. * @param y defines the 2nd component of the value
  14133. */
  14134. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniform2f(uniform, x, y);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a vec3
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param x defines the 1st component of the value
  14143. * @param y defines the 2nd component of the value
  14144. * @param z defines the 3rd component of the value
  14145. */
  14146. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14147. if (!uniform)
  14148. return;
  14149. this._gl.uniform3f(uniform, x, y, z);
  14150. };
  14151. /**
  14152. * Set the value of an uniform to a boolean
  14153. * @param uniform defines the webGL uniform location where to store the value
  14154. * @param bool defines the boolean to store
  14155. */
  14156. Engine.prototype.setBool = function (uniform, bool) {
  14157. if (!uniform)
  14158. return;
  14159. this._gl.uniform1i(uniform, bool);
  14160. };
  14161. /**
  14162. * Set the value of an uniform to a vec4
  14163. * @param uniform defines the webGL uniform location where to store the value
  14164. * @param x defines the 1st component of the value
  14165. * @param y defines the 2nd component of the value
  14166. * @param z defines the 3rd component of the value
  14167. * @param w defines the 4th component of the value
  14168. */
  14169. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14170. if (!uniform)
  14171. return;
  14172. this._gl.uniform4f(uniform, x, y, z, w);
  14173. };
  14174. /**
  14175. * Set the value of an uniform to a Color3
  14176. * @param uniform defines the webGL uniform location where to store the value
  14177. * @param color3 defines the color to store
  14178. */
  14179. Engine.prototype.setColor3 = function (uniform, color3) {
  14180. if (!uniform)
  14181. return;
  14182. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to a Color3 and an alpha value
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param color3 defines the color to store
  14188. * @param alpha defines the alpha component to store
  14189. */
  14190. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14194. };
  14195. /**
  14196. * Sets a Color4 on a uniform variable
  14197. * @param uniform defines the uniform location
  14198. * @param color4 defines the value to be set
  14199. */
  14200. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14204. };
  14205. // States
  14206. /**
  14207. * Set various states to the webGL context
  14208. * @param culling defines backface culling state
  14209. * @param zOffset defines the value to apply to zOffset (0 by default)
  14210. * @param force defines if states must be applied even if cache is up to date
  14211. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14212. */
  14213. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14214. if (zOffset === void 0) { zOffset = 0; }
  14215. if (reverseSide === void 0) { reverseSide = false; }
  14216. // Culling
  14217. if (this._depthCullingState.cull !== culling || force) {
  14218. this._depthCullingState.cull = culling;
  14219. }
  14220. // Cull face
  14221. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14222. if (this._depthCullingState.cullFace !== cullFace || force) {
  14223. this._depthCullingState.cullFace = cullFace;
  14224. }
  14225. // Z offset
  14226. this.setZOffset(zOffset);
  14227. // Front face
  14228. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14229. if (this._depthCullingState.frontFace !== frontFace || force) {
  14230. this._depthCullingState.frontFace = frontFace;
  14231. }
  14232. };
  14233. /**
  14234. * Set the z offset to apply to current rendering
  14235. * @param value defines the offset to apply
  14236. */
  14237. Engine.prototype.setZOffset = function (value) {
  14238. this._depthCullingState.zOffset = value;
  14239. };
  14240. /**
  14241. * Gets the current value of the zOffset
  14242. * @returns the current zOffset state
  14243. */
  14244. Engine.prototype.getZOffset = function () {
  14245. return this._depthCullingState.zOffset;
  14246. };
  14247. /**
  14248. * Enable or disable depth buffering
  14249. * @param enable defines the state to set
  14250. */
  14251. Engine.prototype.setDepthBuffer = function (enable) {
  14252. this._depthCullingState.depthTest = enable;
  14253. };
  14254. /**
  14255. * Gets a boolean indicating if depth writing is enabled
  14256. * @returns the current depth writing state
  14257. */
  14258. Engine.prototype.getDepthWrite = function () {
  14259. return this._depthCullingState.depthMask;
  14260. };
  14261. /**
  14262. * Enable or disable depth writing
  14263. * @param enable defines the state to set
  14264. */
  14265. Engine.prototype.setDepthWrite = function (enable) {
  14266. this._depthCullingState.depthMask = enable;
  14267. };
  14268. /**
  14269. * Enable or disable color writing
  14270. * @param enable defines the state to set
  14271. */
  14272. Engine.prototype.setColorWrite = function (enable) {
  14273. this._gl.colorMask(enable, enable, enable, enable);
  14274. this._colorWrite = enable;
  14275. };
  14276. /**
  14277. * Gets a boolean indicating if color writing is enabled
  14278. * @returns the current color writing state
  14279. */
  14280. Engine.prototype.getColorWrite = function () {
  14281. return this._colorWrite;
  14282. };
  14283. /**
  14284. * Sets alpha constants used by some alpha blending modes
  14285. * @param r defines the red component
  14286. * @param g defines the green component
  14287. * @param b defines the blue component
  14288. * @param a defines the alpha component
  14289. */
  14290. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14291. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14292. };
  14293. /**
  14294. * Sets the current alpha mode
  14295. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14296. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14297. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14298. */
  14299. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14300. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14301. if (this._alphaMode === mode) {
  14302. return;
  14303. }
  14304. switch (mode) {
  14305. case Engine.ALPHA_DISABLE:
  14306. this._alphaState.alphaBlend = false;
  14307. break;
  14308. case Engine.ALPHA_PREMULTIPLIED:
  14309. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14310. this._alphaState.alphaBlend = true;
  14311. break;
  14312. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14314. this._alphaState.alphaBlend = true;
  14315. break;
  14316. case Engine.ALPHA_COMBINE:
  14317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14318. this._alphaState.alphaBlend = true;
  14319. break;
  14320. case Engine.ALPHA_ONEONE:
  14321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14322. this._alphaState.alphaBlend = true;
  14323. break;
  14324. case Engine.ALPHA_ADD:
  14325. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14326. this._alphaState.alphaBlend = true;
  14327. break;
  14328. case Engine.ALPHA_SUBTRACT:
  14329. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14330. this._alphaState.alphaBlend = true;
  14331. break;
  14332. case Engine.ALPHA_MULTIPLY:
  14333. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14334. this._alphaState.alphaBlend = true;
  14335. break;
  14336. case Engine.ALPHA_MAXIMIZED:
  14337. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14338. this._alphaState.alphaBlend = true;
  14339. break;
  14340. case Engine.ALPHA_INTERPOLATE:
  14341. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14342. this._alphaState.alphaBlend = true;
  14343. break;
  14344. case Engine.ALPHA_SCREENMODE:
  14345. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14346. this._alphaState.alphaBlend = true;
  14347. break;
  14348. }
  14349. if (!noDepthWriteChange) {
  14350. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14351. }
  14352. this._alphaMode = mode;
  14353. };
  14354. /**
  14355. * Gets the current alpha mode
  14356. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14357. * @returns the current alpha mode
  14358. */
  14359. Engine.prototype.getAlphaMode = function () {
  14360. return this._alphaMode;
  14361. };
  14362. // Textures
  14363. /**
  14364. * Clears the list of texture accessible through engine.
  14365. * This can help preventing texture load conflict due to name collision.
  14366. */
  14367. Engine.prototype.clearInternalTexturesCache = function () {
  14368. this._internalTexturesCache = [];
  14369. };
  14370. /**
  14371. * Force the entire cache to be cleared
  14372. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14373. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14374. */
  14375. Engine.prototype.wipeCaches = function (bruteForce) {
  14376. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14377. return;
  14378. }
  14379. this._currentEffect = null;
  14380. this._viewportCached.x = 0;
  14381. this._viewportCached.y = 0;
  14382. this._viewportCached.z = 0;
  14383. this._viewportCached.w = 0;
  14384. if (bruteForce) {
  14385. this.resetTextureCache();
  14386. this._currentProgram = null;
  14387. this._stencilState.reset();
  14388. this._depthCullingState.reset();
  14389. this.setDepthFunctionToLessOrEqual();
  14390. this._alphaState.reset();
  14391. this._unpackFlipYCached = null;
  14392. }
  14393. this._resetVertexBufferBinding();
  14394. this._cachedIndexBuffer = null;
  14395. this._cachedEffectForVertexBuffers = null;
  14396. this._unbindVertexArrayObject();
  14397. this.bindIndexBuffer(null);
  14398. };
  14399. /**
  14400. * Set the compressed texture format to use, based on the formats you have, and the formats
  14401. * supported by the hardware / browser.
  14402. *
  14403. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14404. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14405. * to API arguments needed to compressed textures. This puts the burden on the container
  14406. * generator to house the arcane code for determining these for current & future formats.
  14407. *
  14408. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14409. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14410. *
  14411. * Note: The result of this call is not taken into account when a texture is base64.
  14412. *
  14413. * @param formatsAvailable defines the list of those format families you have created
  14414. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14415. *
  14416. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14417. * @returns The extension selected.
  14418. */
  14419. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14420. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14421. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14422. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14423. return this._textureFormatInUse = this._texturesSupported[i];
  14424. }
  14425. }
  14426. }
  14427. // actively set format to nothing, to allow this to be called more than once
  14428. // and possibly fail the 2nd time
  14429. this._textureFormatInUse = null;
  14430. return null;
  14431. };
  14432. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14433. var gl = this._gl;
  14434. var magFilter = gl.NEAREST;
  14435. var minFilter = gl.NEAREST;
  14436. switch (samplingMode) {
  14437. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14438. magFilter = gl.LINEAR;
  14439. if (generateMipMaps) {
  14440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14441. }
  14442. else {
  14443. minFilter = gl.LINEAR;
  14444. }
  14445. break;
  14446. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14447. magFilter = gl.LINEAR;
  14448. if (generateMipMaps) {
  14449. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14450. }
  14451. else {
  14452. minFilter = gl.LINEAR;
  14453. }
  14454. break;
  14455. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14456. magFilter = gl.NEAREST;
  14457. if (generateMipMaps) {
  14458. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14459. }
  14460. else {
  14461. minFilter = gl.NEAREST;
  14462. }
  14463. break;
  14464. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14465. magFilter = gl.NEAREST;
  14466. if (generateMipMaps) {
  14467. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14468. }
  14469. else {
  14470. minFilter = gl.NEAREST;
  14471. }
  14472. break;
  14473. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14474. magFilter = gl.NEAREST;
  14475. if (generateMipMaps) {
  14476. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14477. }
  14478. else {
  14479. minFilter = gl.LINEAR;
  14480. }
  14481. break;
  14482. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14483. magFilter = gl.NEAREST;
  14484. if (generateMipMaps) {
  14485. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14486. }
  14487. else {
  14488. minFilter = gl.LINEAR;
  14489. }
  14490. break;
  14491. case Engine.TEXTURE_NEAREST_LINEAR:
  14492. magFilter = gl.NEAREST;
  14493. minFilter = gl.LINEAR;
  14494. break;
  14495. case Engine.TEXTURE_NEAREST_NEAREST:
  14496. magFilter = gl.NEAREST;
  14497. minFilter = gl.NEAREST;
  14498. break;
  14499. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14500. magFilter = gl.LINEAR;
  14501. if (generateMipMaps) {
  14502. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14503. }
  14504. else {
  14505. minFilter = gl.NEAREST;
  14506. }
  14507. break;
  14508. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14509. magFilter = gl.LINEAR;
  14510. if (generateMipMaps) {
  14511. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14512. }
  14513. else {
  14514. minFilter = gl.NEAREST;
  14515. }
  14516. break;
  14517. case Engine.TEXTURE_LINEAR_LINEAR:
  14518. magFilter = gl.LINEAR;
  14519. minFilter = gl.LINEAR;
  14520. break;
  14521. case Engine.TEXTURE_LINEAR_NEAREST:
  14522. magFilter = gl.LINEAR;
  14523. minFilter = gl.NEAREST;
  14524. break;
  14525. }
  14526. return {
  14527. min: minFilter,
  14528. mag: magFilter
  14529. };
  14530. };
  14531. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14532. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14533. var img;
  14534. var onload = function () {
  14535. loadedImages[index] = img;
  14536. loadedImages._internalCount++;
  14537. if (scene) {
  14538. scene._removePendingData(img);
  14539. }
  14540. if (loadedImages._internalCount === 6) {
  14541. onfinish(loadedImages);
  14542. }
  14543. };
  14544. var onerror = function (message, exception) {
  14545. if (scene) {
  14546. scene._removePendingData(img);
  14547. }
  14548. if (onErrorCallBack) {
  14549. onErrorCallBack(message, exception);
  14550. }
  14551. };
  14552. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14553. if (scene) {
  14554. scene._addPendingData(img);
  14555. }
  14556. };
  14557. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14558. if (onError === void 0) { onError = null; }
  14559. var loadedImages = [];
  14560. loadedImages._internalCount = 0;
  14561. for (var index = 0; index < 6; index++) {
  14562. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14563. }
  14564. };
  14565. ;
  14566. /** @hidden */
  14567. Engine.prototype._createTexture = function () {
  14568. var texture = this._gl.createTexture();
  14569. if (!texture) {
  14570. throw new Error("Unable to create texture");
  14571. }
  14572. return texture;
  14573. };
  14574. /**
  14575. * Usually called from BABYLON.Texture.ts.
  14576. * Passed information to create a WebGLTexture
  14577. * @param urlArg defines a value which contains one of the following:
  14578. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14579. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14580. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14581. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14582. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14583. * @param scene needed for loading to the correct scene
  14584. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14585. * @param onLoad optional callback to be called upon successful completion
  14586. * @param onError optional callback to be called upon failure
  14587. * @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
  14588. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14589. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14590. * @param forcedExtension defines the extension to use to pick the right loader
  14591. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14592. */
  14593. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14594. var _this = this;
  14595. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14596. if (onLoad === void 0) { onLoad = null; }
  14597. if (onError === void 0) { onError = null; }
  14598. if (buffer === void 0) { buffer = null; }
  14599. if (fallback === void 0) { fallback = null; }
  14600. if (format === void 0) { format = null; }
  14601. if (forcedExtension === void 0) { forcedExtension = null; }
  14602. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14603. var fromData = url.substr(0, 5) === "data:";
  14604. var fromBlob = url.substr(0, 5) === "blob:";
  14605. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14606. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14607. // establish the file extension, if possible
  14608. var lastDot = url.lastIndexOf('.');
  14609. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14610. var loader = null;
  14611. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14612. var availableLoader = _a[_i];
  14613. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14614. loader = availableLoader;
  14615. break;
  14616. }
  14617. }
  14618. if (loader) {
  14619. url = loader.transformUrl(url, this._textureFormatInUse);
  14620. }
  14621. if (scene) {
  14622. scene._addPendingData(texture);
  14623. }
  14624. texture.url = url;
  14625. texture.generateMipMaps = !noMipmap;
  14626. texture.samplingMode = samplingMode;
  14627. texture.invertY = invertY;
  14628. if (!this._doNotHandleContextLost) {
  14629. // Keep a link to the buffer only if we plan to handle context lost
  14630. texture._buffer = buffer;
  14631. }
  14632. var onLoadObserver = null;
  14633. if (onLoad && !fallback) {
  14634. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14635. }
  14636. if (!fallback)
  14637. this._internalTexturesCache.push(texture);
  14638. var onInternalError = function (message, exception) {
  14639. if (scene) {
  14640. scene._removePendingData(texture);
  14641. }
  14642. var customFallback = false;
  14643. if (loader) {
  14644. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14645. if (fallbackUrl) {
  14646. // Add Back
  14647. customFallback = true;
  14648. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14649. }
  14650. }
  14651. if (!customFallback) {
  14652. if (onLoadObserver) {
  14653. texture.onLoadedObservable.remove(onLoadObserver);
  14654. }
  14655. if (BABYLON.Tools.UseFallbackTexture) {
  14656. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14657. }
  14658. }
  14659. if (onError) {
  14660. onError(message || "Unknown error", exception);
  14661. }
  14662. };
  14663. // processing for non-image formats
  14664. if (loader) {
  14665. var callback = function (data) {
  14666. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14667. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14668. done();
  14669. return false;
  14670. }, samplingMode);
  14671. });
  14672. };
  14673. if (!buffer) {
  14674. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14675. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14676. });
  14677. }
  14678. else {
  14679. callback(buffer);
  14680. }
  14681. }
  14682. else {
  14683. var onload = function (img) {
  14684. if (fromBlob && !_this._doNotHandleContextLost) {
  14685. // We need to store the image if we need to rebuild the texture
  14686. // in case of a webgl context lost
  14687. texture._buffer = img;
  14688. }
  14689. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14690. var gl = _this._gl;
  14691. var isPot = (img.width === potWidth && img.height === potHeight);
  14692. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14693. if (isPot) {
  14694. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14695. return false;
  14696. }
  14697. var maxTextureSize = _this._caps.maxTextureSize;
  14698. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14699. _this._prepareWorkingCanvas();
  14700. if (!_this._workingCanvas || !_this._workingContext) {
  14701. return false;
  14702. }
  14703. _this._workingCanvas.width = potWidth;
  14704. _this._workingCanvas.height = potHeight;
  14705. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14706. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14707. texture.width = potWidth;
  14708. texture.height = potHeight;
  14709. return false;
  14710. }
  14711. else {
  14712. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14713. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14714. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14715. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14717. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14718. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14719. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14720. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14721. _this._releaseTexture(source_1);
  14722. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14723. continuationCallback();
  14724. });
  14725. }
  14726. return true;
  14727. }, samplingMode);
  14728. };
  14729. if (!fromData || isBase64) {
  14730. if (buffer instanceof HTMLImageElement) {
  14731. onload(buffer);
  14732. }
  14733. else {
  14734. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14735. }
  14736. }
  14737. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14738. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14739. }
  14740. else {
  14741. onload(buffer);
  14742. }
  14743. }
  14744. return texture;
  14745. };
  14746. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14747. var _this = this;
  14748. var rtt = this.createRenderTargetTexture({
  14749. width: destination.width,
  14750. height: destination.height,
  14751. }, {
  14752. generateMipMaps: false,
  14753. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14754. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14755. generateDepthBuffer: false,
  14756. generateStencilBuffer: false
  14757. });
  14758. if (!this._rescalePostProcess) {
  14759. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14760. }
  14761. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14762. _this._rescalePostProcess.onApply = function (effect) {
  14763. effect._bindTexture("textureSampler", source);
  14764. };
  14765. var hostingScene = scene;
  14766. if (!hostingScene) {
  14767. hostingScene = _this.scenes[_this.scenes.length - 1];
  14768. }
  14769. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14770. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14771. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14772. _this.unBindFramebuffer(rtt);
  14773. _this._releaseTexture(rtt);
  14774. if (onComplete) {
  14775. onComplete();
  14776. }
  14777. });
  14778. };
  14779. /**
  14780. * Update a raw texture
  14781. * @param texture defines the texture to update
  14782. * @param data defines the data to store in the texture
  14783. * @param format defines the format of the data
  14784. * @param invertY defines if data must be stored with Y axis inverted
  14785. * @param compression defines the compression used (null by default)
  14786. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14787. */
  14788. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14789. if (compression === void 0) { compression = null; }
  14790. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14791. if (!texture) {
  14792. return;
  14793. }
  14794. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14795. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14796. // babylon's internalFormat but gl's texImage2D format
  14797. var internalFormat = this._getInternalFormat(format);
  14798. var textureType = this._getWebGLTextureType(type);
  14799. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14800. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14801. if (!this._doNotHandleContextLost) {
  14802. texture._bufferView = data;
  14803. texture.format = format;
  14804. texture.type = type;
  14805. texture.invertY = invertY;
  14806. texture._compression = compression;
  14807. }
  14808. if (texture.width % 4 !== 0) {
  14809. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14810. }
  14811. if (compression && data) {
  14812. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14813. }
  14814. else {
  14815. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14816. }
  14817. if (texture.generateMipMaps) {
  14818. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14819. }
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14821. // this.resetTextureCache();
  14822. texture.isReady = true;
  14823. };
  14824. /**
  14825. * Creates a raw texture
  14826. * @param data defines the data to store in the texture
  14827. * @param width defines the width of the texture
  14828. * @param height defines the height of the texture
  14829. * @param format defines the format of the data
  14830. * @param generateMipMaps defines if the engine should generate the mip levels
  14831. * @param invertY defines if data must be stored with Y axis inverted
  14832. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14833. * @param compression defines the compression used (null by default)
  14834. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14835. * @returns the raw texture inside an InternalTexture
  14836. */
  14837. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14838. if (compression === void 0) { compression = null; }
  14839. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14840. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14841. texture.baseWidth = width;
  14842. texture.baseHeight = height;
  14843. texture.width = width;
  14844. texture.height = height;
  14845. texture.format = format;
  14846. texture.generateMipMaps = generateMipMaps;
  14847. texture.samplingMode = samplingMode;
  14848. texture.invertY = invertY;
  14849. texture._compression = compression;
  14850. texture.type = type;
  14851. if (!this._doNotHandleContextLost) {
  14852. texture._bufferView = data;
  14853. }
  14854. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14856. // Filters
  14857. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14859. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14860. if (generateMipMaps) {
  14861. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14862. }
  14863. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14864. this._internalTexturesCache.push(texture);
  14865. return texture;
  14866. };
  14867. /** @hidden */
  14868. Engine.prototype._unpackFlipY = function (value) {
  14869. if (this._unpackFlipYCached !== value) {
  14870. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14871. if (this.enableUnpackFlipYCached) {
  14872. this._unpackFlipYCached = value;
  14873. }
  14874. }
  14875. };
  14876. /** @hidden */
  14877. Engine.prototype._getUnpackAlignement = function () {
  14878. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14879. };
  14880. /**
  14881. * Creates a dynamic texture
  14882. * @param width defines the width of the texture
  14883. * @param height defines the height of the texture
  14884. * @param generateMipMaps defines if the engine should generate the mip levels
  14885. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14886. * @returns the dynamic texture inside an InternalTexture
  14887. */
  14888. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14889. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14890. texture.baseWidth = width;
  14891. texture.baseHeight = height;
  14892. if (generateMipMaps) {
  14893. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14894. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14895. }
  14896. // this.resetTextureCache();
  14897. texture.width = width;
  14898. texture.height = height;
  14899. texture.isReady = false;
  14900. texture.generateMipMaps = generateMipMaps;
  14901. texture.samplingMode = samplingMode;
  14902. this.updateTextureSamplingMode(samplingMode, texture);
  14903. this._internalTexturesCache.push(texture);
  14904. return texture;
  14905. };
  14906. /**
  14907. * Update the sampling mode of a given texture
  14908. * @param samplingMode defines the required sampling mode
  14909. * @param texture defines the texture to update
  14910. */
  14911. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14912. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14913. if (texture.isCube) {
  14914. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14915. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14916. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14917. }
  14918. else if (texture.is3D) {
  14919. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14920. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14921. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14922. }
  14923. else {
  14924. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14925. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14926. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14927. }
  14928. texture.samplingMode = samplingMode;
  14929. };
  14930. /**
  14931. * Update the content of a dynamic texture
  14932. * @param texture defines the texture to update
  14933. * @param canvas defines the canvas containing the source
  14934. * @param invertY defines if data must be stored with Y axis inverted
  14935. * @param premulAlpha defines if alpha is stored as premultiplied
  14936. * @param format defines the format of the data
  14937. */
  14938. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14939. if (premulAlpha === void 0) { premulAlpha = false; }
  14940. if (!texture) {
  14941. return;
  14942. }
  14943. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14944. this._unpackFlipY(invertY);
  14945. if (premulAlpha) {
  14946. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14947. }
  14948. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14949. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14950. if (texture.generateMipMaps) {
  14951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14952. }
  14953. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14954. if (premulAlpha) {
  14955. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14956. }
  14957. texture.isReady = true;
  14958. };
  14959. /**
  14960. * Update a video texture
  14961. * @param texture defines the texture to update
  14962. * @param video defines the video element to use
  14963. * @param invertY defines if data must be stored with Y axis inverted
  14964. */
  14965. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14966. if (!texture || texture._isDisabled) {
  14967. return;
  14968. }
  14969. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14970. this._unpackFlipY(!invertY); // Video are upside down by default
  14971. try {
  14972. // Testing video texture support
  14973. if (this._videoTextureSupported === undefined) {
  14974. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14975. if (this._gl.getError() !== 0) {
  14976. this._videoTextureSupported = false;
  14977. }
  14978. else {
  14979. this._videoTextureSupported = true;
  14980. }
  14981. }
  14982. // Copy video through the current working canvas if video texture is not supported
  14983. if (!this._videoTextureSupported) {
  14984. if (!texture._workingCanvas) {
  14985. texture._workingCanvas = document.createElement("canvas");
  14986. var context = texture._workingCanvas.getContext("2d");
  14987. if (!context) {
  14988. throw new Error("Unable to get 2d context");
  14989. }
  14990. texture._workingContext = context;
  14991. texture._workingCanvas.width = texture.width;
  14992. texture._workingCanvas.height = texture.height;
  14993. }
  14994. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14995. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14996. }
  14997. else {
  14998. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14999. }
  15000. if (texture.generateMipMaps) {
  15001. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15002. }
  15003. if (!wasPreviouslyBound) {
  15004. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15005. }
  15006. // this.resetTextureCache();
  15007. texture.isReady = true;
  15008. }
  15009. catch (ex) {
  15010. // Something unexpected
  15011. // Let's disable the texture
  15012. texture._isDisabled = true;
  15013. }
  15014. };
  15015. /**
  15016. * Updates a depth texture Comparison Mode and Function.
  15017. * If the comparison Function is equal to 0, the mode will be set to none.
  15018. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15019. * @param texture The texture to set the comparison function for
  15020. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15021. */
  15022. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15023. if (this.webGLVersion === 1) {
  15024. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15025. return;
  15026. }
  15027. var gl = this._gl;
  15028. if (texture.isCube) {
  15029. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15030. if (comparisonFunction === 0) {
  15031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15033. }
  15034. else {
  15035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15037. }
  15038. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15039. }
  15040. else {
  15041. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15042. if (comparisonFunction === 0) {
  15043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15045. }
  15046. else {
  15047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15049. }
  15050. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15051. }
  15052. texture._comparisonFunction = comparisonFunction;
  15053. };
  15054. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15055. var width = size.width || size;
  15056. var height = size.height || size;
  15057. internalTexture.baseWidth = width;
  15058. internalTexture.baseHeight = height;
  15059. internalTexture.width = width;
  15060. internalTexture.height = height;
  15061. internalTexture.isReady = true;
  15062. internalTexture.samples = 1;
  15063. internalTexture.generateMipMaps = false;
  15064. internalTexture._generateDepthBuffer = true;
  15065. internalTexture._generateStencilBuffer = generateStencil;
  15066. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15067. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15068. internalTexture._comparisonFunction = comparisonFunction;
  15069. var gl = this._gl;
  15070. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15071. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15072. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15073. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15074. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15075. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15076. if (comparisonFunction === 0) {
  15077. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15078. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15079. }
  15080. else {
  15081. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15082. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15083. }
  15084. };
  15085. /**
  15086. * Creates a depth stencil texture.
  15087. * This is only available in WebGL 2 or with the depth texture extension available.
  15088. * @param size The size of face edge in the texture.
  15089. * @param options The options defining the texture.
  15090. * @returns The texture
  15091. */
  15092. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15093. if (options.isCube) {
  15094. var width = size.width || size;
  15095. return this._createDepthStencilCubeTexture(width, options);
  15096. }
  15097. else {
  15098. return this._createDepthStencilTexture(size, options);
  15099. }
  15100. };
  15101. /**
  15102. * Creates a depth stencil texture.
  15103. * This is only available in WebGL 2 or with the depth texture extension available.
  15104. * @param size The size of face edge in the texture.
  15105. * @param options The options defining the texture.
  15106. * @returns The texture
  15107. */
  15108. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15109. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15110. if (!this._caps.depthTextureExtension) {
  15111. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15112. return internalTexture;
  15113. }
  15114. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15115. var gl = this._gl;
  15116. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15117. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15118. if (this.webGLVersion > 1) {
  15119. if (internalOptions.generateStencil) {
  15120. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15121. }
  15122. else {
  15123. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15124. }
  15125. }
  15126. else {
  15127. if (internalOptions.generateStencil) {
  15128. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15129. }
  15130. else {
  15131. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15132. }
  15133. }
  15134. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15135. return internalTexture;
  15136. };
  15137. /**
  15138. * Creates a depth stencil cube texture.
  15139. * This is only available in WebGL 2.
  15140. * @param size The size of face edge in the cube texture.
  15141. * @param options The options defining the cube texture.
  15142. * @returns The cube texture
  15143. */
  15144. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15145. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15146. internalTexture.isCube = true;
  15147. if (this.webGLVersion === 1) {
  15148. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15149. return internalTexture;
  15150. }
  15151. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15152. var gl = this._gl;
  15153. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15154. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15155. // Create the depth/stencil buffer
  15156. for (var face = 0; face < 6; face++) {
  15157. if (internalOptions.generateStencil) {
  15158. 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);
  15159. }
  15160. else {
  15161. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15162. }
  15163. }
  15164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15165. return internalTexture;
  15166. };
  15167. /**
  15168. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15169. * @param renderTarget The render target to set the frame buffer for
  15170. */
  15171. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15172. // Create the framebuffer
  15173. var internalTexture = renderTarget.getInternalTexture();
  15174. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15175. return;
  15176. }
  15177. var gl = this._gl;
  15178. var depthStencilTexture = renderTarget.depthStencilTexture;
  15179. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15180. if (depthStencilTexture.isCube) {
  15181. if (depthStencilTexture._generateStencilBuffer) {
  15182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15183. }
  15184. else {
  15185. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15186. }
  15187. }
  15188. else {
  15189. if (depthStencilTexture._generateStencilBuffer) {
  15190. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15191. }
  15192. else {
  15193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15194. }
  15195. }
  15196. this.bindUnboundFramebuffer(null);
  15197. };
  15198. /**
  15199. * Creates a new render target texture
  15200. * @param size defines the size of the texture
  15201. * @param options defines the options used to create the texture
  15202. * @returns a new render target texture stored in an InternalTexture
  15203. */
  15204. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15205. var fullOptions = new RenderTargetCreationOptions();
  15206. if (options !== undefined && typeof options === "object") {
  15207. fullOptions.generateMipMaps = options.generateMipMaps;
  15208. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15209. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15210. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15211. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15212. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15213. }
  15214. else {
  15215. fullOptions.generateMipMaps = options;
  15216. fullOptions.generateDepthBuffer = true;
  15217. fullOptions.generateStencilBuffer = false;
  15218. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15220. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15221. }
  15222. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15223. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15224. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15225. }
  15226. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15227. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15228. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15229. }
  15230. var gl = this._gl;
  15231. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15232. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15233. var width = size.width || size;
  15234. var height = size.height || size;
  15235. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15236. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15237. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15238. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15239. }
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15244. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15245. // Create the framebuffer
  15246. var currentFrameBuffer = this._currentFramebuffer;
  15247. var framebuffer = gl.createFramebuffer();
  15248. this.bindUnboundFramebuffer(framebuffer);
  15249. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15250. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15251. if (fullOptions.generateMipMaps) {
  15252. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15253. }
  15254. // Unbind
  15255. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15256. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15257. this.bindUnboundFramebuffer(currentFrameBuffer);
  15258. texture._framebuffer = framebuffer;
  15259. texture.baseWidth = width;
  15260. texture.baseHeight = height;
  15261. texture.width = width;
  15262. texture.height = height;
  15263. texture.isReady = true;
  15264. texture.samples = 1;
  15265. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15266. texture.samplingMode = fullOptions.samplingMode;
  15267. texture.type = fullOptions.type;
  15268. texture.format = fullOptions.format;
  15269. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15270. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15271. // this.resetTextureCache();
  15272. this._internalTexturesCache.push(texture);
  15273. return texture;
  15274. };
  15275. /**
  15276. * Create a multi render target texture
  15277. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15278. * @param size defines the size of the texture
  15279. * @param options defines the creation options
  15280. * @returns the cube texture as an InternalTexture
  15281. */
  15282. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15283. var generateMipMaps = false;
  15284. var generateDepthBuffer = true;
  15285. var generateStencilBuffer = false;
  15286. var generateDepthTexture = false;
  15287. var textureCount = 1;
  15288. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15289. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15290. var types = new Array();
  15291. var samplingModes = new Array();
  15292. if (options !== undefined) {
  15293. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15294. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15295. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15296. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15297. textureCount = options.textureCount || 1;
  15298. if (options.types) {
  15299. types = options.types;
  15300. }
  15301. if (options.samplingModes) {
  15302. samplingModes = options.samplingModes;
  15303. }
  15304. }
  15305. var gl = this._gl;
  15306. // Create the framebuffer
  15307. var framebuffer = gl.createFramebuffer();
  15308. this.bindUnboundFramebuffer(framebuffer);
  15309. var width = size.width || size;
  15310. var height = size.height || size;
  15311. var textures = [];
  15312. var attachments = [];
  15313. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15314. for (var i = 0; i < textureCount; i++) {
  15315. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15316. var type = types[i] || defaultType;
  15317. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15318. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15319. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15320. }
  15321. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15322. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15323. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15324. }
  15325. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15326. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15327. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15328. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15329. }
  15330. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15331. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15332. textures.push(texture);
  15333. attachments.push(attachment);
  15334. gl.activeTexture(gl["TEXTURE" + i]);
  15335. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15340. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15341. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15342. if (generateMipMaps) {
  15343. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15344. }
  15345. // Unbind
  15346. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15347. texture._framebuffer = framebuffer;
  15348. texture._depthStencilBuffer = depthStencilBuffer;
  15349. texture.baseWidth = width;
  15350. texture.baseHeight = height;
  15351. texture.width = width;
  15352. texture.height = height;
  15353. texture.isReady = true;
  15354. texture.samples = 1;
  15355. texture.generateMipMaps = generateMipMaps;
  15356. texture.samplingMode = samplingMode;
  15357. texture.type = type;
  15358. texture._generateDepthBuffer = generateDepthBuffer;
  15359. texture._generateStencilBuffer = generateStencilBuffer;
  15360. texture._attachments = attachments;
  15361. this._internalTexturesCache.push(texture);
  15362. }
  15363. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15364. // Depth texture
  15365. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15366. gl.activeTexture(gl.TEXTURE0);
  15367. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15372. 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);
  15373. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15374. depthTexture._framebuffer = framebuffer;
  15375. depthTexture.baseWidth = width;
  15376. depthTexture.baseHeight = height;
  15377. depthTexture.width = width;
  15378. depthTexture.height = height;
  15379. depthTexture.isReady = true;
  15380. depthTexture.samples = 1;
  15381. depthTexture.generateMipMaps = generateMipMaps;
  15382. depthTexture.samplingMode = gl.NEAREST;
  15383. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15384. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15385. textures.push(depthTexture);
  15386. this._internalTexturesCache.push(depthTexture);
  15387. }
  15388. gl.drawBuffers(attachments);
  15389. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15390. this.bindUnboundFramebuffer(null);
  15391. this.resetTextureCache();
  15392. return textures;
  15393. };
  15394. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15395. if (samples === void 0) { samples = 1; }
  15396. var depthStencilBuffer = null;
  15397. var gl = this._gl;
  15398. // Create the depth/stencil buffer
  15399. if (generateStencilBuffer) {
  15400. depthStencilBuffer = gl.createRenderbuffer();
  15401. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15402. if (samples > 1) {
  15403. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15404. }
  15405. else {
  15406. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15407. }
  15408. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15409. }
  15410. else if (generateDepthBuffer) {
  15411. depthStencilBuffer = gl.createRenderbuffer();
  15412. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15413. if (samples > 1) {
  15414. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15415. }
  15416. else {
  15417. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15418. }
  15419. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15420. }
  15421. return depthStencilBuffer;
  15422. };
  15423. /**
  15424. * Updates the sample count of a render target texture
  15425. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15426. * @param texture defines the texture to update
  15427. * @param samples defines the sample count to set
  15428. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15429. */
  15430. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15431. if (this.webGLVersion < 2 || !texture) {
  15432. return 1;
  15433. }
  15434. if (texture.samples === samples) {
  15435. return samples;
  15436. }
  15437. var gl = this._gl;
  15438. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15439. // Dispose previous render buffers
  15440. if (texture._depthStencilBuffer) {
  15441. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15442. texture._depthStencilBuffer = null;
  15443. }
  15444. if (texture._MSAAFramebuffer) {
  15445. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15446. texture._MSAAFramebuffer = null;
  15447. }
  15448. if (texture._MSAARenderBuffer) {
  15449. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15450. texture._MSAARenderBuffer = null;
  15451. }
  15452. if (samples > 1) {
  15453. var framebuffer = gl.createFramebuffer();
  15454. if (!framebuffer) {
  15455. throw new Error("Unable to create multi sampled framebuffer");
  15456. }
  15457. texture._MSAAFramebuffer = framebuffer;
  15458. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15459. var colorRenderbuffer = gl.createRenderbuffer();
  15460. if (!colorRenderbuffer) {
  15461. throw new Error("Unable to create multi sampled framebuffer");
  15462. }
  15463. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15464. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15465. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15466. texture._MSAARenderBuffer = colorRenderbuffer;
  15467. }
  15468. else {
  15469. this.bindUnboundFramebuffer(texture._framebuffer);
  15470. }
  15471. texture.samples = samples;
  15472. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15473. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15474. this.bindUnboundFramebuffer(null);
  15475. return samples;
  15476. };
  15477. /**
  15478. * Update the sample count for a given multiple render target texture
  15479. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15480. * @param textures defines the textures to update
  15481. * @param samples defines the sample count to set
  15482. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15483. */
  15484. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15485. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15486. return 1;
  15487. }
  15488. if (textures[0].samples === samples) {
  15489. return samples;
  15490. }
  15491. var gl = this._gl;
  15492. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15493. // Dispose previous render buffers
  15494. if (textures[0]._depthStencilBuffer) {
  15495. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15496. textures[0]._depthStencilBuffer = null;
  15497. }
  15498. if (textures[0]._MSAAFramebuffer) {
  15499. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15500. textures[0]._MSAAFramebuffer = null;
  15501. }
  15502. for (var i = 0; i < textures.length; i++) {
  15503. if (textures[i]._MSAARenderBuffer) {
  15504. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15505. textures[i]._MSAARenderBuffer = null;
  15506. }
  15507. }
  15508. if (samples > 1) {
  15509. var framebuffer = gl.createFramebuffer();
  15510. if (!framebuffer) {
  15511. throw new Error("Unable to create multi sampled framebuffer");
  15512. }
  15513. this.bindUnboundFramebuffer(framebuffer);
  15514. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15515. var attachments = [];
  15516. for (var i = 0; i < textures.length; i++) {
  15517. var texture = textures[i];
  15518. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15519. var colorRenderbuffer = gl.createRenderbuffer();
  15520. if (!colorRenderbuffer) {
  15521. throw new Error("Unable to create multi sampled framebuffer");
  15522. }
  15523. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15524. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15525. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15526. texture._MSAAFramebuffer = framebuffer;
  15527. texture._MSAARenderBuffer = colorRenderbuffer;
  15528. texture.samples = samples;
  15529. texture._depthStencilBuffer = depthStencilBuffer;
  15530. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15531. attachments.push(attachment);
  15532. }
  15533. gl.drawBuffers(attachments);
  15534. }
  15535. else {
  15536. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15537. }
  15538. this.bindUnboundFramebuffer(null);
  15539. return samples;
  15540. };
  15541. /** @hidden */
  15542. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15543. if (faceIndex === void 0) { faceIndex = 0; }
  15544. if (lod === void 0) { lod = 0; }
  15545. var gl = this._gl;
  15546. var target = gl.TEXTURE_2D;
  15547. if (texture.isCube) {
  15548. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15549. }
  15550. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15551. };
  15552. /** @hidden */
  15553. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15554. if (faceIndex === void 0) { faceIndex = 0; }
  15555. if (lod === void 0) { lod = 0; }
  15556. var gl = this._gl;
  15557. var textureType = this._getWebGLTextureType(texture.type);
  15558. var format = this._getInternalFormat(texture.format);
  15559. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15560. this._unpackFlipY(texture.invertY);
  15561. var target = gl.TEXTURE_2D;
  15562. if (texture.isCube) {
  15563. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15564. }
  15565. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15566. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15567. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15568. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15569. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15570. };
  15571. /** @hidden */
  15572. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15573. if (faceIndex === void 0) { faceIndex = 0; }
  15574. if (lod === void 0) { lod = 0; }
  15575. var gl = this._gl;
  15576. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15577. this._bindTextureDirectly(bindTarget, texture, true);
  15578. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15579. this._bindTextureDirectly(bindTarget, null, true);
  15580. };
  15581. /** @hidden */
  15582. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15583. if (faceIndex === void 0) { faceIndex = 0; }
  15584. if (lod === void 0) { lod = 0; }
  15585. var gl = this._gl;
  15586. var textureType = this._getWebGLTextureType(texture.type);
  15587. var format = this._getInternalFormat(texture.format);
  15588. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15589. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15590. this._bindTextureDirectly(bindTarget, texture, true);
  15591. this._unpackFlipY(texture.invertY);
  15592. var target = gl.TEXTURE_2D;
  15593. if (texture.isCube) {
  15594. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15595. }
  15596. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15597. this._bindTextureDirectly(bindTarget, null, true);
  15598. };
  15599. /**
  15600. * Creates a new render target cube texture
  15601. * @param size defines the size of the texture
  15602. * @param options defines the options used to create the texture
  15603. * @returns a new render target cube texture stored in an InternalTexture
  15604. */
  15605. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15606. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15607. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15608. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15609. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15610. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15611. }
  15612. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15613. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15614. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15615. }
  15616. var gl = this._gl;
  15617. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15618. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15619. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15620. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15621. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15622. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15623. }
  15624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15628. for (var face = 0; face < 6; face++) {
  15629. 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);
  15630. }
  15631. // Create the framebuffer
  15632. var framebuffer = gl.createFramebuffer();
  15633. this.bindUnboundFramebuffer(framebuffer);
  15634. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15635. // MipMaps
  15636. if (fullOptions.generateMipMaps) {
  15637. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15638. }
  15639. // Unbind
  15640. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15641. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15642. this.bindUnboundFramebuffer(null);
  15643. texture._framebuffer = framebuffer;
  15644. texture.width = size;
  15645. texture.height = size;
  15646. texture.isReady = true;
  15647. texture.isCube = true;
  15648. texture.samples = 1;
  15649. texture.generateMipMaps = fullOptions.generateMipMaps;
  15650. texture.samplingMode = fullOptions.samplingMode;
  15651. texture.type = fullOptions.type;
  15652. texture.format = fullOptions.format;
  15653. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15654. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15655. this._internalTexturesCache.push(texture);
  15656. return texture;
  15657. };
  15658. /**
  15659. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15660. * @param rootUrl defines the url where the file to load is located
  15661. * @param scene defines the current scene
  15662. * @param lodScale defines scale to apply to the mip map selection
  15663. * @param lodOffset defines offset to apply to the mip map selection
  15664. * @param onLoad defines an optional callback raised when the texture is loaded
  15665. * @param onError defines an optional callback raised if there is an issue to load the texture
  15666. * @param format defines the format of the data
  15667. * @param forcedExtension defines the extension to use to pick the right loader
  15668. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15669. * @returns the cube texture as an InternalTexture
  15670. */
  15671. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15672. var _this = this;
  15673. if (onLoad === void 0) { onLoad = null; }
  15674. if (onError === void 0) { onError = null; }
  15675. if (forcedExtension === void 0) { forcedExtension = null; }
  15676. if (createPolynomials === void 0) { createPolynomials = true; }
  15677. var callback = function (loadData) {
  15678. if (!loadData) {
  15679. if (onLoad) {
  15680. onLoad(null);
  15681. }
  15682. return;
  15683. }
  15684. var texture = loadData.texture;
  15685. if (!createPolynomials) {
  15686. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15687. }
  15688. else if (loadData.info.sphericalPolynomial) {
  15689. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15690. }
  15691. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15692. if (_this._caps.textureLOD) {
  15693. // Do not add extra process if texture lod is supported.
  15694. if (onLoad) {
  15695. onLoad(texture);
  15696. }
  15697. return;
  15698. }
  15699. var mipSlices = 3;
  15700. var gl = _this._gl;
  15701. var width = loadData.width;
  15702. if (!width) {
  15703. return;
  15704. }
  15705. var textures = [];
  15706. for (var i = 0; i < mipSlices; i++) {
  15707. //compute LOD from even spacing in smoothness (matching shader calculation)
  15708. var smoothness = i / (mipSlices - 1);
  15709. var roughness = 1 - smoothness;
  15710. var minLODIndex = lodOffset; // roughness = 0
  15711. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15712. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15713. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15714. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15715. glTextureFromLod.type = texture.type;
  15716. glTextureFromLod.format = texture.format;
  15717. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15718. glTextureFromLod.height = glTextureFromLod.width;
  15719. glTextureFromLod.isCube = true;
  15720. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15725. if (loadData.isDDS) {
  15726. var info = loadData.info;
  15727. var data = loadData.data;
  15728. _this._unpackFlipY(info.isCompressed);
  15729. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15730. }
  15731. else {
  15732. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15733. }
  15734. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15735. // Wrap in a base texture for easy binding.
  15736. var lodTexture = new BABYLON.BaseTexture(scene);
  15737. lodTexture.isCube = true;
  15738. lodTexture._texture = glTextureFromLod;
  15739. glTextureFromLod.isReady = true;
  15740. textures.push(lodTexture);
  15741. }
  15742. texture._lodTextureHigh = textures[2];
  15743. texture._lodTextureMid = textures[1];
  15744. texture._lodTextureLow = textures[0];
  15745. if (onLoad) {
  15746. onLoad(texture);
  15747. }
  15748. };
  15749. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15750. };
  15751. /**
  15752. * Creates a cube texture
  15753. * @param rootUrl defines the url where the files to load is located
  15754. * @param scene defines the current scene
  15755. * @param files defines the list of files to load (1 per face)
  15756. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15757. * @param onLoad defines an optional callback raised when the texture is loaded
  15758. * @param onError defines an optional callback raised if there is an issue to load the texture
  15759. * @param format defines the format of the data
  15760. * @param forcedExtension defines the extension to use to pick the right loader
  15761. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15762. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15763. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15764. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15765. * @returns the cube texture as an InternalTexture
  15766. */
  15767. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15768. var _this = this;
  15769. if (onLoad === void 0) { onLoad = null; }
  15770. if (onError === void 0) { onError = null; }
  15771. if (forcedExtension === void 0) { forcedExtension = null; }
  15772. if (createPolynomials === void 0) { createPolynomials = false; }
  15773. if (lodScale === void 0) { lodScale = 0; }
  15774. if (lodOffset === void 0) { lodOffset = 0; }
  15775. if (fallback === void 0) { fallback = null; }
  15776. var gl = this._gl;
  15777. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15778. texture.isCube = true;
  15779. texture.url = rootUrl;
  15780. texture.generateMipMaps = !noMipmap;
  15781. texture._lodGenerationScale = lodScale;
  15782. texture._lodGenerationOffset = lodOffset;
  15783. if (!this._doNotHandleContextLost) {
  15784. texture._extension = forcedExtension;
  15785. texture._files = files;
  15786. }
  15787. var lastDot = rootUrl.lastIndexOf('.');
  15788. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15789. var loader = null;
  15790. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15791. var availableLoader = _a[_i];
  15792. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15793. loader = availableLoader;
  15794. break;
  15795. }
  15796. }
  15797. var onInternalError = function (request, exception) {
  15798. if (loader) {
  15799. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15800. if (fallbackUrl) {
  15801. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15802. }
  15803. }
  15804. if (onError && request) {
  15805. onError(request.status + " " + request.statusText, exception);
  15806. }
  15807. };
  15808. if (loader) {
  15809. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15810. var onloaddata = function (data) {
  15811. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15812. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15813. };
  15814. if (files && files.length === 6) {
  15815. if (loader.supportCascades) {
  15816. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15817. }
  15818. else if (onError) {
  15819. onError("Textures type does not support cascades.");
  15820. }
  15821. }
  15822. else {
  15823. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15824. }
  15825. }
  15826. else {
  15827. if (!files) {
  15828. throw new Error("Cannot load cubemap because files were not defined");
  15829. }
  15830. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15831. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15832. var height = width;
  15833. _this._prepareWorkingCanvas();
  15834. if (!_this._workingCanvas || !_this._workingContext) {
  15835. return;
  15836. }
  15837. _this._workingCanvas.width = width;
  15838. _this._workingCanvas.height = height;
  15839. var faces = [
  15840. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15841. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15842. ];
  15843. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15844. _this._unpackFlipY(false);
  15845. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15846. for (var index = 0; index < faces.length; index++) {
  15847. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15848. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15849. }
  15850. if (!noMipmap) {
  15851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15852. }
  15853. _this._setCubeMapTextureParams(!noMipmap);
  15854. texture.width = width;
  15855. texture.height = height;
  15856. texture.isReady = true;
  15857. if (format) {
  15858. texture.format = format;
  15859. }
  15860. texture.onLoadedObservable.notifyObservers(texture);
  15861. texture.onLoadedObservable.clear();
  15862. if (onLoad) {
  15863. onLoad();
  15864. }
  15865. }, files, onError);
  15866. }
  15867. this._internalTexturesCache.push(texture);
  15868. return texture;
  15869. };
  15870. /**
  15871. * @hidden
  15872. */
  15873. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15874. var gl = this._gl;
  15875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15879. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15880. // this.resetTextureCache();
  15881. };
  15882. /**
  15883. * Update a raw cube texture
  15884. * @param texture defines the texture to udpdate
  15885. * @param data defines the data to store
  15886. * @param format defines the data format
  15887. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15888. * @param invertY defines if data must be stored with Y axis inverted
  15889. * @param compression defines the compression used (null by default)
  15890. * @param level defines which level of the texture to update
  15891. */
  15892. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15893. if (compression === void 0) { compression = null; }
  15894. if (level === void 0) { level = 0; }
  15895. texture._bufferViewArray = data;
  15896. texture.format = format;
  15897. texture.type = type;
  15898. texture.invertY = invertY;
  15899. texture._compression = compression;
  15900. var gl = this._gl;
  15901. var textureType = this._getWebGLTextureType(type);
  15902. var internalFormat = this._getInternalFormat(format);
  15903. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15904. var needConversion = false;
  15905. if (internalFormat === gl.RGB) {
  15906. internalFormat = gl.RGBA;
  15907. needConversion = true;
  15908. }
  15909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15910. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15911. if (texture.width % 4 !== 0) {
  15912. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15913. }
  15914. // Data are known to be in +X +Y +Z -X -Y -Z
  15915. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15916. var faceData = data[faceIndex];
  15917. if (compression) {
  15918. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15919. }
  15920. else {
  15921. if (needConversion) {
  15922. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15923. }
  15924. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15925. }
  15926. }
  15927. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15928. if (isPot && texture.generateMipMaps && level === 0) {
  15929. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15930. }
  15931. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15932. // this.resetTextureCache();
  15933. texture.isReady = true;
  15934. };
  15935. /**
  15936. * Creates a new raw cube texture
  15937. * @param data defines the array of data to use to create each face
  15938. * @param size defines the size of the textures
  15939. * @param format defines the format of the data
  15940. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15941. * @param generateMipMaps defines if the engine should generate the mip levels
  15942. * @param invertY defines if data must be stored with Y axis inverted
  15943. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15944. * @param compression defines the compression used (null by default)
  15945. * @returns the cube texture as an InternalTexture
  15946. */
  15947. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15948. if (compression === void 0) { compression = null; }
  15949. var gl = this._gl;
  15950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15951. texture.isCube = true;
  15952. texture.format = format;
  15953. texture.type = type;
  15954. if (!this._doNotHandleContextLost) {
  15955. texture._bufferViewArray = data;
  15956. }
  15957. var textureType = this._getWebGLTextureType(type);
  15958. var internalFormat = this._getInternalFormat(format);
  15959. if (internalFormat === gl.RGB) {
  15960. internalFormat = gl.RGBA;
  15961. }
  15962. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15963. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15964. generateMipMaps = false;
  15965. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15966. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15967. }
  15968. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15969. generateMipMaps = false;
  15970. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15971. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15972. }
  15973. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15974. generateMipMaps = false;
  15975. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15976. }
  15977. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15978. generateMipMaps = false;
  15979. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15980. }
  15981. var width = size;
  15982. var height = width;
  15983. texture.width = width;
  15984. texture.height = height;
  15985. // Double check on POT to generate Mips.
  15986. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15987. if (!isPot) {
  15988. generateMipMaps = false;
  15989. }
  15990. // Upload data if needed. The texture won't be ready until then.
  15991. if (data) {
  15992. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15993. }
  15994. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15995. // Filters
  15996. if (data && generateMipMaps) {
  15997. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15998. }
  15999. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16005. texture.generateMipMaps = generateMipMaps;
  16006. return texture;
  16007. };
  16008. /**
  16009. * Creates a new raw cube texture from a specified url
  16010. * @param url defines the url where the data is located
  16011. * @param scene defines the current scene
  16012. * @param size defines the size of the textures
  16013. * @param format defines the format of the data
  16014. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16015. * @param noMipmap defines if the engine should avoid generating the mip levels
  16016. * @param callback defines a callback used to extract texture data from loaded data
  16017. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16018. * @param onLoad defines a callback called when texture is loaded
  16019. * @param onError defines a callback called if there is an error
  16020. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16021. * @param invertY defines if data must be stored with Y axis inverted
  16022. * @returns the cube texture as an InternalTexture
  16023. */
  16024. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16025. var _this = this;
  16026. if (onLoad === void 0) { onLoad = null; }
  16027. if (onError === void 0) { onError = null; }
  16028. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16029. if (invertY === void 0) { invertY = false; }
  16030. var gl = this._gl;
  16031. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16032. scene._addPendingData(texture);
  16033. texture.url = url;
  16034. this._internalTexturesCache.push(texture);
  16035. var onerror = function (request, exception) {
  16036. scene._removePendingData(texture);
  16037. if (onError && request) {
  16038. onError(request.status + " " + request.statusText, exception);
  16039. }
  16040. };
  16041. var internalCallback = function (data) {
  16042. var width = texture.width;
  16043. var faceDataArrays = callback(data);
  16044. if (!faceDataArrays) {
  16045. return;
  16046. }
  16047. if (mipmapGenerator) {
  16048. var textureType = _this._getWebGLTextureType(type);
  16049. var internalFormat = _this._getInternalFormat(format);
  16050. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16051. var needConversion = false;
  16052. if (internalFormat === gl.RGB) {
  16053. internalFormat = gl.RGBA;
  16054. needConversion = true;
  16055. }
  16056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16057. _this._unpackFlipY(false);
  16058. var mipData = mipmapGenerator(faceDataArrays);
  16059. for (var level = 0; level < mipData.length; level++) {
  16060. var mipSize = width >> level;
  16061. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16062. var mipFaceData = mipData[level][faceIndex];
  16063. if (needConversion) {
  16064. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16065. }
  16066. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16067. }
  16068. }
  16069. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16070. }
  16071. else {
  16072. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16073. }
  16074. texture.isReady = true;
  16075. // this.resetTextureCache();
  16076. scene._removePendingData(texture);
  16077. if (onLoad) {
  16078. onLoad();
  16079. }
  16080. };
  16081. this._loadFile(url, function (data) {
  16082. internalCallback(data);
  16083. }, undefined, scene.database, true, onerror);
  16084. return texture;
  16085. };
  16086. ;
  16087. /**
  16088. * Update a raw 3D texture
  16089. * @param texture defines the texture to update
  16090. * @param data defines the data to store
  16091. * @param format defines the data format
  16092. * @param invertY defines if data must be stored with Y axis inverted
  16093. * @param compression defines the used compression (can be null)
  16094. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16095. */
  16096. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16097. if (compression === void 0) { compression = null; }
  16098. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16099. var internalType = this._getWebGLTextureType(textureType);
  16100. var internalFormat = this._getInternalFormat(format);
  16101. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16102. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16103. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16104. if (!this._doNotHandleContextLost) {
  16105. texture._bufferView = data;
  16106. texture.format = format;
  16107. texture.invertY = invertY;
  16108. texture._compression = compression;
  16109. }
  16110. if (texture.width % 4 !== 0) {
  16111. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16112. }
  16113. if (compression && data) {
  16114. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16115. }
  16116. else {
  16117. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16118. }
  16119. if (texture.generateMipMaps) {
  16120. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16121. }
  16122. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16123. // this.resetTextureCache();
  16124. texture.isReady = true;
  16125. };
  16126. /**
  16127. * Creates a new raw 3D texture
  16128. * @param data defines the data used to create the texture
  16129. * @param width defines the width of the texture
  16130. * @param height defines the height of the texture
  16131. * @param depth defines the depth of the texture
  16132. * @param format defines the format of the texture
  16133. * @param generateMipMaps defines if the engine must generate mip levels
  16134. * @param invertY defines if data must be stored with Y axis inverted
  16135. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16136. * @param compression defines the compressed used (can be null)
  16137. * @param textureType defines the compressed used (can be null)
  16138. * @returns a new raw 3D texture (stored in an InternalTexture)
  16139. */
  16140. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16141. if (compression === void 0) { compression = null; }
  16142. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16144. texture.baseWidth = width;
  16145. texture.baseHeight = height;
  16146. texture.baseDepth = depth;
  16147. texture.width = width;
  16148. texture.height = height;
  16149. texture.depth = depth;
  16150. texture.format = format;
  16151. texture.type = textureType;
  16152. texture.generateMipMaps = generateMipMaps;
  16153. texture.samplingMode = samplingMode;
  16154. texture.is3D = true;
  16155. if (!this._doNotHandleContextLost) {
  16156. texture._bufferView = data;
  16157. }
  16158. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16159. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16160. // Filters
  16161. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16162. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16164. if (generateMipMaps) {
  16165. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16166. }
  16167. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16168. this._internalTexturesCache.push(texture);
  16169. return texture;
  16170. };
  16171. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16172. var gl = this._gl;
  16173. if (!gl) {
  16174. return;
  16175. }
  16176. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16179. if (!noMipmap && !isCompressed) {
  16180. gl.generateMipmap(gl.TEXTURE_2D);
  16181. }
  16182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16183. // this.resetTextureCache();
  16184. if (scene) {
  16185. scene._removePendingData(texture);
  16186. }
  16187. texture.onLoadedObservable.notifyObservers(texture);
  16188. texture.onLoadedObservable.clear();
  16189. };
  16190. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16191. var _this = this;
  16192. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16193. var maxTextureSize = this.getCaps().maxTextureSize;
  16194. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16195. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16196. var gl = this._gl;
  16197. if (!gl) {
  16198. return;
  16199. }
  16200. if (!texture._webGLTexture) {
  16201. // this.resetTextureCache();
  16202. if (scene) {
  16203. scene._removePendingData(texture);
  16204. }
  16205. return;
  16206. }
  16207. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16208. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16209. texture.baseWidth = width;
  16210. texture.baseHeight = height;
  16211. texture.width = potWidth;
  16212. texture.height = potHeight;
  16213. texture.isReady = true;
  16214. if (processFunction(potWidth, potHeight, function () {
  16215. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16216. })) {
  16217. // Returning as texture needs extra async steps
  16218. return;
  16219. }
  16220. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16221. };
  16222. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16223. // Create new RGBA data container.
  16224. var rgbaData;
  16225. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16226. rgbaData = new Float32Array(width * height * 4);
  16227. }
  16228. else {
  16229. rgbaData = new Uint32Array(width * height * 4);
  16230. }
  16231. // Convert each pixel.
  16232. for (var x = 0; x < width; x++) {
  16233. for (var y = 0; y < height; y++) {
  16234. var index = (y * width + x) * 3;
  16235. var newIndex = (y * width + x) * 4;
  16236. // Map Old Value to new value.
  16237. rgbaData[newIndex + 0] = rgbData[index + 0];
  16238. rgbaData[newIndex + 1] = rgbData[index + 1];
  16239. rgbaData[newIndex + 2] = rgbData[index + 2];
  16240. // Add fully opaque alpha channel.
  16241. rgbaData[newIndex + 3] = 1;
  16242. }
  16243. }
  16244. return rgbaData;
  16245. };
  16246. /** @hidden */
  16247. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16248. var gl = this._gl;
  16249. if (texture._framebuffer) {
  16250. gl.deleteFramebuffer(texture._framebuffer);
  16251. texture._framebuffer = null;
  16252. }
  16253. if (texture._depthStencilBuffer) {
  16254. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16255. texture._depthStencilBuffer = null;
  16256. }
  16257. if (texture._MSAAFramebuffer) {
  16258. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16259. texture._MSAAFramebuffer = null;
  16260. }
  16261. if (texture._MSAARenderBuffer) {
  16262. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16263. texture._MSAARenderBuffer = null;
  16264. }
  16265. };
  16266. /** @hidden */
  16267. Engine.prototype._releaseTexture = function (texture) {
  16268. var gl = this._gl;
  16269. this._releaseFramebufferObjects(texture);
  16270. gl.deleteTexture(texture._webGLTexture);
  16271. // Unbind channels
  16272. this.unbindAllTextures();
  16273. var index = this._internalTexturesCache.indexOf(texture);
  16274. if (index !== -1) {
  16275. this._internalTexturesCache.splice(index, 1);
  16276. }
  16277. // Integrated fixed lod samplers.
  16278. if (texture._lodTextureHigh) {
  16279. texture._lodTextureHigh.dispose();
  16280. }
  16281. if (texture._lodTextureMid) {
  16282. texture._lodTextureMid.dispose();
  16283. }
  16284. if (texture._lodTextureLow) {
  16285. texture._lodTextureLow.dispose();
  16286. }
  16287. // Set output texture of post process to null if the texture has been released/disposed
  16288. this.scenes.forEach(function (scene) {
  16289. scene.postProcesses.forEach(function (postProcess) {
  16290. if (postProcess._outputTexture == texture) {
  16291. postProcess._outputTexture = null;
  16292. }
  16293. });
  16294. scene.cameras.forEach(function (camera) {
  16295. camera._postProcesses.forEach(function (postProcess) {
  16296. if (postProcess) {
  16297. if (postProcess._outputTexture == texture) {
  16298. postProcess._outputTexture = null;
  16299. }
  16300. }
  16301. });
  16302. });
  16303. });
  16304. };
  16305. Engine.prototype.setProgram = function (program) {
  16306. if (this._currentProgram !== program) {
  16307. this._gl.useProgram(program);
  16308. this._currentProgram = program;
  16309. }
  16310. };
  16311. /**
  16312. * Binds an effect to the webGL context
  16313. * @param effect defines the effect to bind
  16314. */
  16315. Engine.prototype.bindSamplers = function (effect) {
  16316. this.setProgram(effect.getProgram());
  16317. var samplers = effect.getSamplers();
  16318. for (var index = 0; index < samplers.length; index++) {
  16319. var uniform = effect.getUniform(samplers[index]);
  16320. if (uniform) {
  16321. this._boundUniforms[index] = uniform;
  16322. }
  16323. }
  16324. this._currentEffect = null;
  16325. };
  16326. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16327. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16328. return;
  16329. }
  16330. // Remove
  16331. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16332. // Bind last to it
  16333. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16334. // Bind to dummy
  16335. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16336. };
  16337. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16338. if (!internalTexture) {
  16339. return -1;
  16340. }
  16341. internalTexture._initialSlot = channel;
  16342. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16343. if (channel !== internalTexture._designatedSlot) {
  16344. this._textureCollisions.addCount(1, false);
  16345. }
  16346. }
  16347. else {
  16348. if (channel !== internalTexture._designatedSlot) {
  16349. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16350. return internalTexture._designatedSlot;
  16351. }
  16352. else {
  16353. // No slot for this texture, let's pick a new one (if we find a free slot)
  16354. if (this._nextFreeTextureSlots.length) {
  16355. return this._nextFreeTextureSlots[0];
  16356. }
  16357. // We need to recycle the oldest bound texture, sorry.
  16358. this._textureCollisions.addCount(1, false);
  16359. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16360. }
  16361. }
  16362. }
  16363. return channel;
  16364. };
  16365. Engine.prototype._linkTrackers = function (previous, next) {
  16366. previous.next = next;
  16367. next.previous = previous;
  16368. };
  16369. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16370. var currentSlot = internalTexture._designatedSlot;
  16371. if (currentSlot === -1) {
  16372. return -1;
  16373. }
  16374. internalTexture._designatedSlot = -1;
  16375. if (this.disableTextureBindingOptimization) {
  16376. return -1;
  16377. }
  16378. // Remove from bound list
  16379. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16380. // Free the slot
  16381. this._boundTexturesCache[currentSlot] = null;
  16382. this._nextFreeTextureSlots.push(currentSlot);
  16383. return currentSlot;
  16384. };
  16385. Engine.prototype._activateCurrentTexture = function () {
  16386. if (this._currentTextureChannel !== this._activeChannel) {
  16387. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16388. this._currentTextureChannel = this._activeChannel;
  16389. }
  16390. };
  16391. /** @hidden */
  16392. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16393. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16394. if (force === void 0) { force = false; }
  16395. var wasPreviouslyBound = false;
  16396. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16397. this._activeChannel = texture._designatedSlot;
  16398. }
  16399. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16400. var isTextureForRendering = texture && texture._initialSlot > -1;
  16401. if (currentTextureBound !== texture || force) {
  16402. if (currentTextureBound) {
  16403. this._removeDesignatedSlot(currentTextureBound);
  16404. }
  16405. this._activateCurrentTexture();
  16406. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16407. this._boundTexturesCache[this._activeChannel] = texture;
  16408. if (texture) {
  16409. if (!this.disableTextureBindingOptimization) {
  16410. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16411. if (slotIndex > -1) {
  16412. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16413. }
  16414. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16415. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16416. }
  16417. texture._designatedSlot = this._activeChannel;
  16418. }
  16419. }
  16420. else if (forTextureDataUpdate) {
  16421. wasPreviouslyBound = true;
  16422. this._activateCurrentTexture();
  16423. }
  16424. if (isTextureForRendering && !forTextureDataUpdate) {
  16425. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16426. }
  16427. return wasPreviouslyBound;
  16428. };
  16429. /** @hidden */
  16430. Engine.prototype._bindTexture = function (channel, texture) {
  16431. if (channel < 0) {
  16432. return;
  16433. }
  16434. if (texture) {
  16435. channel = this._getCorrectTextureChannel(channel, texture);
  16436. }
  16437. this._activeChannel = channel;
  16438. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16439. };
  16440. /**
  16441. * Sets a texture to the webGL context from a postprocess
  16442. * @param channel defines the channel to use
  16443. * @param postProcess defines the source postprocess
  16444. */
  16445. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16446. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16447. };
  16448. /**
  16449. * Binds the output of the passed in post process to the texture channel specified
  16450. * @param channel The channel the texture should be bound to
  16451. * @param postProcess The post process which's output should be bound
  16452. */
  16453. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16454. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16455. };
  16456. /**
  16457. * Unbind all textures from the webGL context
  16458. */
  16459. Engine.prototype.unbindAllTextures = function () {
  16460. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16461. this._activeChannel = channel;
  16462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16463. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16464. if (this.webGLVersion > 1) {
  16465. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16466. }
  16467. }
  16468. };
  16469. /**
  16470. * Sets a texture to the according uniform.
  16471. * @param channel The texture channel
  16472. * @param uniform The uniform to set
  16473. * @param texture The texture to apply
  16474. */
  16475. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16476. if (channel < 0) {
  16477. return;
  16478. }
  16479. if (uniform) {
  16480. this._boundUniforms[channel] = uniform;
  16481. }
  16482. this._setTexture(channel, texture);
  16483. };
  16484. /**
  16485. * Sets a depth stencil texture from a render target to the according uniform.
  16486. * @param channel The texture channel
  16487. * @param uniform The uniform to set
  16488. * @param texture The render target texture containing the depth stencil texture to apply
  16489. */
  16490. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16491. if (channel < 0) {
  16492. return;
  16493. }
  16494. if (uniform) {
  16495. this._boundUniforms[channel] = uniform;
  16496. }
  16497. if (!texture || !texture.depthStencilTexture) {
  16498. this._setTexture(channel, null);
  16499. }
  16500. else {
  16501. this._setTexture(channel, texture, false, true);
  16502. }
  16503. };
  16504. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16505. var uniform = this._boundUniforms[sourceSlot];
  16506. if (uniform._currentState === destination) {
  16507. return;
  16508. }
  16509. this._gl.uniform1i(uniform, destination);
  16510. uniform._currentState = destination;
  16511. };
  16512. Engine.prototype._getTextureWrapMode = function (mode) {
  16513. switch (mode) {
  16514. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16515. return this._gl.REPEAT;
  16516. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16517. return this._gl.CLAMP_TO_EDGE;
  16518. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16519. return this._gl.MIRRORED_REPEAT;
  16520. }
  16521. return this._gl.REPEAT;
  16522. };
  16523. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16524. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16525. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16526. // Not ready?
  16527. if (!texture) {
  16528. if (this._boundTexturesCache[channel] != null) {
  16529. this._activeChannel = channel;
  16530. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16532. if (this.webGLVersion > 1) {
  16533. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16534. }
  16535. }
  16536. return false;
  16537. }
  16538. // Video
  16539. if (texture.video) {
  16540. this._activeChannel = channel;
  16541. texture.update();
  16542. }
  16543. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16544. texture.delayLoad();
  16545. return false;
  16546. }
  16547. var internalTexture;
  16548. if (depthStencilTexture) {
  16549. internalTexture = texture.depthStencilTexture;
  16550. }
  16551. else if (texture.isReady()) {
  16552. internalTexture = texture.getInternalTexture();
  16553. }
  16554. else if (texture.isCube) {
  16555. internalTexture = this.emptyCubeTexture;
  16556. }
  16557. else if (texture.is3D) {
  16558. internalTexture = this.emptyTexture3D;
  16559. }
  16560. else {
  16561. internalTexture = this.emptyTexture;
  16562. }
  16563. if (!isPartOfTextureArray) {
  16564. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16565. }
  16566. var needToBind = true;
  16567. if (this._boundTexturesCache[channel] === internalTexture) {
  16568. this._moveBoundTextureOnTop(internalTexture);
  16569. if (!isPartOfTextureArray) {
  16570. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16571. }
  16572. needToBind = false;
  16573. }
  16574. this._activeChannel = channel;
  16575. if (internalTexture && internalTexture.is3D) {
  16576. if (needToBind) {
  16577. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16578. }
  16579. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16580. internalTexture._cachedWrapU = texture.wrapU;
  16581. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16582. }
  16583. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16584. internalTexture._cachedWrapV = texture.wrapV;
  16585. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16586. }
  16587. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16588. internalTexture._cachedWrapR = texture.wrapR;
  16589. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16590. }
  16591. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16592. }
  16593. else if (internalTexture && internalTexture.isCube) {
  16594. if (needToBind) {
  16595. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16596. }
  16597. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16598. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16599. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16600. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16601. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16602. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16603. }
  16604. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16605. }
  16606. else {
  16607. if (needToBind) {
  16608. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16609. }
  16610. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16611. internalTexture._cachedWrapU = texture.wrapU;
  16612. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16613. }
  16614. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16615. internalTexture._cachedWrapV = texture.wrapV;
  16616. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16617. }
  16618. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16619. }
  16620. return true;
  16621. };
  16622. /**
  16623. * Sets an array of texture to the webGL context
  16624. * @param channel defines the channel where the texture array must be set
  16625. * @param uniform defines the associated uniform location
  16626. * @param textures defines the array of textures to bind
  16627. */
  16628. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16629. if (channel < 0 || !uniform) {
  16630. return;
  16631. }
  16632. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16633. this._textureUnits = new Int32Array(textures.length);
  16634. }
  16635. for (var i = 0; i < textures.length; i++) {
  16636. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16637. }
  16638. this._gl.uniform1iv(uniform, this._textureUnits);
  16639. for (var index = 0; index < textures.length; index++) {
  16640. this._setTexture(this._textureUnits[index], textures[index], true);
  16641. }
  16642. };
  16643. /** @hidden */
  16644. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16645. var internalTexture = texture.getInternalTexture();
  16646. if (!internalTexture) {
  16647. return;
  16648. }
  16649. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16650. var value = texture.anisotropicFilteringLevel;
  16651. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16652. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16653. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16654. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16655. }
  16656. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16657. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16658. internalTexture._cachedAnisotropicFilteringLevel = value;
  16659. }
  16660. };
  16661. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16662. this._bindTextureDirectly(target, texture, true, true);
  16663. this._gl.texParameterf(target, parameter, value);
  16664. };
  16665. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16666. if (texture) {
  16667. this._bindTextureDirectly(target, texture, true, true);
  16668. }
  16669. this._gl.texParameteri(target, parameter, value);
  16670. };
  16671. /**
  16672. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16673. * @param x defines the x coordinate of the rectangle where pixels must be read
  16674. * @param y defines the y coordinate of the rectangle where pixels must be read
  16675. * @param width defines the width of the rectangle where pixels must be read
  16676. * @param height defines the height of the rectangle where pixels must be read
  16677. * @returns a Uint8Array containing RGBA colors
  16678. */
  16679. Engine.prototype.readPixels = function (x, y, width, height) {
  16680. var data = new Uint8Array(height * width * 4);
  16681. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16682. return data;
  16683. };
  16684. /**
  16685. * Add an externaly attached data from its key.
  16686. * This method call will fail and return false, if such key already exists.
  16687. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16688. * @param key the unique key that identifies the data
  16689. * @param data the data object to associate to the key for this Engine instance
  16690. * @return true if no such key were already present and the data was added successfully, false otherwise
  16691. */
  16692. Engine.prototype.addExternalData = function (key, data) {
  16693. if (!this._externalData) {
  16694. this._externalData = new BABYLON.StringDictionary();
  16695. }
  16696. return this._externalData.add(key, data);
  16697. };
  16698. /**
  16699. * Get an externaly attached data from its key
  16700. * @param key the unique key that identifies the data
  16701. * @return the associated data, if present (can be null), or undefined if not present
  16702. */
  16703. Engine.prototype.getExternalData = function (key) {
  16704. if (!this._externalData) {
  16705. this._externalData = new BABYLON.StringDictionary();
  16706. }
  16707. return this._externalData.get(key);
  16708. };
  16709. /**
  16710. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16711. * @param key the unique key that identifies the data
  16712. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16713. * @return the associated data, can be null if the factory returned null.
  16714. */
  16715. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16716. if (!this._externalData) {
  16717. this._externalData = new BABYLON.StringDictionary();
  16718. }
  16719. return this._externalData.getOrAddWithFactory(key, factory);
  16720. };
  16721. /**
  16722. * Remove an externaly attached data from the Engine instance
  16723. * @param key the unique key that identifies the data
  16724. * @return true if the data was successfully removed, false if it doesn't exist
  16725. */
  16726. Engine.prototype.removeExternalData = function (key) {
  16727. if (!this._externalData) {
  16728. this._externalData = new BABYLON.StringDictionary();
  16729. }
  16730. return this._externalData.remove(key);
  16731. };
  16732. /**
  16733. * Unbind all vertex attributes from the webGL context
  16734. */
  16735. Engine.prototype.unbindAllAttributes = function () {
  16736. if (this._mustWipeVertexAttributes) {
  16737. this._mustWipeVertexAttributes = false;
  16738. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16739. this._gl.disableVertexAttribArray(i);
  16740. this._vertexAttribArraysEnabled[i] = false;
  16741. this._currentBufferPointers[i].active = false;
  16742. }
  16743. return;
  16744. }
  16745. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16746. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16747. continue;
  16748. }
  16749. this._gl.disableVertexAttribArray(i);
  16750. this._vertexAttribArraysEnabled[i] = false;
  16751. this._currentBufferPointers[i].active = false;
  16752. }
  16753. };
  16754. /**
  16755. * 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
  16756. */
  16757. Engine.prototype.releaseEffects = function () {
  16758. for (var name in this._compiledEffects) {
  16759. this._deleteProgram(this._compiledEffects[name]._program);
  16760. }
  16761. this._compiledEffects = {};
  16762. };
  16763. /**
  16764. * Dispose and release all associated resources
  16765. */
  16766. Engine.prototype.dispose = function () {
  16767. this.hideLoadingUI();
  16768. this.stopRenderLoop();
  16769. // Release postProcesses
  16770. while (this.postProcesses.length) {
  16771. this.postProcesses[0].dispose();
  16772. }
  16773. // Empty texture
  16774. if (this._emptyTexture) {
  16775. this._releaseTexture(this._emptyTexture);
  16776. this._emptyTexture = null;
  16777. }
  16778. if (this._emptyCubeTexture) {
  16779. this._releaseTexture(this._emptyCubeTexture);
  16780. this._emptyCubeTexture = null;
  16781. }
  16782. // Rescale PP
  16783. if (this._rescalePostProcess) {
  16784. this._rescalePostProcess.dispose();
  16785. }
  16786. // Release scenes
  16787. while (this.scenes.length) {
  16788. this.scenes[0].dispose();
  16789. }
  16790. // Release audio engine
  16791. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16792. Engine.audioEngine.dispose();
  16793. }
  16794. // Release effects
  16795. this.releaseEffects();
  16796. // Unbind
  16797. this.unbindAllAttributes();
  16798. this._boundUniforms = [];
  16799. if (this._dummyFramebuffer) {
  16800. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16801. }
  16802. //WebVR
  16803. this.disableVR();
  16804. // Events
  16805. if (BABYLON.Tools.IsWindowObjectExist()) {
  16806. window.removeEventListener("blur", this._onBlur);
  16807. window.removeEventListener("focus", this._onFocus);
  16808. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16809. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16810. if (this._renderingCanvas) {
  16811. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16812. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16813. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16814. if (!this._doNotHandleContextLost) {
  16815. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16816. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16817. }
  16818. }
  16819. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16820. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16821. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16822. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16823. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16824. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16825. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16826. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16827. if (this._onVrDisplayConnect) {
  16828. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16829. if (this._onVrDisplayDisconnect) {
  16830. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16831. }
  16832. if (this._onVrDisplayPresentChange) {
  16833. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16834. }
  16835. this._onVrDisplayConnect = null;
  16836. this._onVrDisplayDisconnect = null;
  16837. }
  16838. }
  16839. // Remove from Instances
  16840. var index = Engine.Instances.indexOf(this);
  16841. if (index >= 0) {
  16842. Engine.Instances.splice(index, 1);
  16843. }
  16844. this._workingCanvas = null;
  16845. this._workingContext = null;
  16846. this._currentBufferPointers = [];
  16847. this._renderingCanvas = null;
  16848. this._currentProgram = null;
  16849. this._bindedRenderFunction = null;
  16850. this.onResizeObservable.clear();
  16851. this.onCanvasBlurObservable.clear();
  16852. this.onCanvasFocusObservable.clear();
  16853. this.onCanvasPointerOutObservable.clear();
  16854. this.onBeginFrameObservable.clear();
  16855. this.onEndFrameObservable.clear();
  16856. BABYLON.Effect.ResetCache();
  16857. // Abort active requests
  16858. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16859. var request = _a[_i];
  16860. request.abort();
  16861. }
  16862. };
  16863. // Loading screen
  16864. /**
  16865. * Display the loading screen
  16866. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16867. */
  16868. Engine.prototype.displayLoadingUI = function () {
  16869. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16870. return;
  16871. }
  16872. var loadingScreen = this.loadingScreen;
  16873. if (loadingScreen) {
  16874. loadingScreen.displayLoadingUI();
  16875. }
  16876. };
  16877. /**
  16878. * Hide the loading screen
  16879. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16880. */
  16881. Engine.prototype.hideLoadingUI = function () {
  16882. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16883. return;
  16884. }
  16885. var loadingScreen = this.loadingScreen;
  16886. if (loadingScreen) {
  16887. loadingScreen.hideLoadingUI();
  16888. }
  16889. };
  16890. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16891. /**
  16892. * Gets the current loading screen object
  16893. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16894. */
  16895. get: function () {
  16896. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16897. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16898. return this._loadingScreen;
  16899. },
  16900. /**
  16901. * Sets the current loading screen object
  16902. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16903. */
  16904. set: function (loadingScreen) {
  16905. this._loadingScreen = loadingScreen;
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16911. /**
  16912. * Sets the current loading screen text
  16913. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16914. */
  16915. set: function (text) {
  16916. this.loadingScreen.loadingUIText = text;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16922. /**
  16923. * Sets the current loading screen background color
  16924. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16925. */
  16926. set: function (color) {
  16927. this.loadingScreen.loadingUIBackgroundColor = color;
  16928. },
  16929. enumerable: true,
  16930. configurable: true
  16931. });
  16932. /**
  16933. * Attach a new callback raised when context lost event is fired
  16934. * @param callback defines the callback to call
  16935. */
  16936. Engine.prototype.attachContextLostEvent = function (callback) {
  16937. if (this._renderingCanvas) {
  16938. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16939. }
  16940. };
  16941. /**
  16942. * Attach a new callback raised when context restored event is fired
  16943. * @param callback defines the callback to call
  16944. */
  16945. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16946. if (this._renderingCanvas) {
  16947. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16948. }
  16949. };
  16950. /**
  16951. * Gets the source code of the vertex shader associated with a specific webGL program
  16952. * @param program defines the program to use
  16953. * @returns a string containing the source code of the vertex shader associated with the program
  16954. */
  16955. Engine.prototype.getVertexShaderSource = function (program) {
  16956. var shaders = this._gl.getAttachedShaders(program);
  16957. if (!shaders) {
  16958. return null;
  16959. }
  16960. return this._gl.getShaderSource(shaders[0]);
  16961. };
  16962. /**
  16963. * Gets the source code of the fragment shader associated with a specific webGL program
  16964. * @param program defines the program to use
  16965. * @returns a string containing the source code of the fragment shader associated with the program
  16966. */
  16967. Engine.prototype.getFragmentShaderSource = function (program) {
  16968. var shaders = this._gl.getAttachedShaders(program);
  16969. if (!shaders) {
  16970. return null;
  16971. }
  16972. return this._gl.getShaderSource(shaders[1]);
  16973. };
  16974. /**
  16975. * Get the current error code of the webGL context
  16976. * @returns the error code
  16977. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16978. */
  16979. Engine.prototype.getError = function () {
  16980. return this._gl.getError();
  16981. };
  16982. // FPS
  16983. /**
  16984. * Gets the current framerate
  16985. * @returns a number representing the framerate
  16986. */
  16987. Engine.prototype.getFps = function () {
  16988. return this._fps;
  16989. };
  16990. /**
  16991. * Gets the time spent between current and previous frame
  16992. * @returns a number representing the delta time in ms
  16993. */
  16994. Engine.prototype.getDeltaTime = function () {
  16995. return this._deltaTime;
  16996. };
  16997. Engine.prototype._measureFps = function () {
  16998. this._performanceMonitor.sampleFrame();
  16999. this._fps = this._performanceMonitor.averageFPS;
  17000. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17001. };
  17002. /** @hidden */
  17003. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17004. if (faceIndex === void 0) { faceIndex = -1; }
  17005. if (level === void 0) { level = 0; }
  17006. if (buffer === void 0) { buffer = null; }
  17007. var gl = this._gl;
  17008. if (!this._dummyFramebuffer) {
  17009. var dummy = gl.createFramebuffer();
  17010. if (!dummy) {
  17011. throw new Error("Unable to create dummy framebuffer");
  17012. }
  17013. this._dummyFramebuffer = dummy;
  17014. }
  17015. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17016. if (faceIndex > -1) {
  17017. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17018. }
  17019. else {
  17020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17021. }
  17022. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17023. switch (readType) {
  17024. case gl.UNSIGNED_BYTE:
  17025. if (!buffer) {
  17026. buffer = new Uint8Array(4 * width * height);
  17027. }
  17028. readType = gl.UNSIGNED_BYTE;
  17029. break;
  17030. default:
  17031. if (!buffer) {
  17032. buffer = new Float32Array(4 * width * height);
  17033. }
  17034. readType = gl.FLOAT;
  17035. break;
  17036. }
  17037. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17038. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17039. return buffer;
  17040. };
  17041. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17042. if (this._webGLVersion > 1) {
  17043. return this._caps.colorBufferFloat;
  17044. }
  17045. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17046. };
  17047. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17048. if (this._webGLVersion > 1) {
  17049. return this._caps.colorBufferFloat;
  17050. }
  17051. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17052. };
  17053. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17054. Engine.prototype._canRenderToFramebuffer = function (type) {
  17055. var gl = this._gl;
  17056. //clear existing errors
  17057. while (gl.getError() !== gl.NO_ERROR) { }
  17058. var successful = true;
  17059. var texture = gl.createTexture();
  17060. gl.bindTexture(gl.TEXTURE_2D, texture);
  17061. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17064. var fb = gl.createFramebuffer();
  17065. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17066. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17067. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17068. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17069. successful = successful && (gl.getError() === gl.NO_ERROR);
  17070. //try render by clearing frame buffer's color buffer
  17071. if (successful) {
  17072. gl.clear(gl.COLOR_BUFFER_BIT);
  17073. successful = successful && (gl.getError() === gl.NO_ERROR);
  17074. }
  17075. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17076. if (successful) {
  17077. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17078. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17079. var readFormat = gl.RGBA;
  17080. var readType = gl.UNSIGNED_BYTE;
  17081. var buffer = new Uint8Array(4);
  17082. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17083. successful = successful && (gl.getError() === gl.NO_ERROR);
  17084. }
  17085. //clean up
  17086. gl.deleteTexture(texture);
  17087. gl.deleteFramebuffer(fb);
  17088. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17089. //clear accumulated errors
  17090. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17091. return successful;
  17092. };
  17093. /** @hidden */
  17094. Engine.prototype._getWebGLTextureType = function (type) {
  17095. if (this._webGLVersion === 1) {
  17096. switch (type) {
  17097. case Engine.TEXTURETYPE_FLOAT:
  17098. return this._gl.FLOAT;
  17099. case Engine.TEXTURETYPE_HALF_FLOAT:
  17100. return this._gl.HALF_FLOAT_OES;
  17101. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17102. return this._gl.UNSIGNED_BYTE;
  17103. }
  17104. return this._gl.UNSIGNED_BYTE;
  17105. }
  17106. switch (type) {
  17107. case Engine.TEXTURETYPE_BYTE:
  17108. return this._gl.BYTE;
  17109. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17110. return this._gl.UNSIGNED_BYTE;
  17111. case Engine.TEXTURETYPE_SHORT:
  17112. return this._gl.SHORT;
  17113. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17114. return this._gl.UNSIGNED_SHORT;
  17115. case Engine.TEXTURETYPE_INT:
  17116. return this._gl.INT;
  17117. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17118. return this._gl.UNSIGNED_INT;
  17119. case Engine.TEXTURETYPE_FLOAT:
  17120. return this._gl.FLOAT;
  17121. case Engine.TEXTURETYPE_HALF_FLOAT:
  17122. return this._gl.HALF_FLOAT;
  17123. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17124. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17125. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17126. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17127. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17128. return this._gl.UNSIGNED_SHORT_5_6_5;
  17129. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17130. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17131. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17132. return this._gl.UNSIGNED_INT_24_8;
  17133. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17134. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17135. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17136. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17137. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17138. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17139. }
  17140. return this._gl.UNSIGNED_BYTE;
  17141. };
  17142. ;
  17143. Engine.prototype._getInternalFormat = function (format) {
  17144. var internalFormat = this._gl.RGBA;
  17145. switch (format) {
  17146. case Engine.TEXTUREFORMAT_ALPHA:
  17147. internalFormat = this._gl.ALPHA;
  17148. break;
  17149. case Engine.TEXTUREFORMAT_LUMINANCE:
  17150. internalFormat = this._gl.LUMINANCE;
  17151. break;
  17152. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17153. internalFormat = this._gl.LUMINANCE_ALPHA;
  17154. break;
  17155. case Engine.TEXTUREFORMAT_RED:
  17156. internalFormat = this._gl.RED;
  17157. break;
  17158. case Engine.TEXTUREFORMAT_RG:
  17159. internalFormat = this._gl.RG;
  17160. break;
  17161. case Engine.TEXTUREFORMAT_RGB:
  17162. internalFormat = this._gl.RGB;
  17163. break;
  17164. case Engine.TEXTUREFORMAT_RGBA:
  17165. internalFormat = this._gl.RGBA;
  17166. break;
  17167. }
  17168. if (this._webGLVersion > 1) {
  17169. switch (format) {
  17170. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17171. internalFormat = this._gl.RED_INTEGER;
  17172. break;
  17173. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17174. internalFormat = this._gl.RG_INTEGER;
  17175. break;
  17176. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17177. internalFormat = this._gl.RGB_INTEGER;
  17178. break;
  17179. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17180. internalFormat = this._gl.RGBA_INTEGER;
  17181. break;
  17182. }
  17183. }
  17184. return internalFormat;
  17185. };
  17186. /** @hidden */
  17187. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17188. if (this._webGLVersion === 1) {
  17189. if (format !== undefined) {
  17190. switch (format) {
  17191. case Engine.TEXTUREFORMAT_ALPHA:
  17192. return this._gl.ALPHA;
  17193. case Engine.TEXTUREFORMAT_LUMINANCE:
  17194. return this._gl.LUMINANCE;
  17195. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17196. return this._gl.LUMINANCE_ALPHA;
  17197. }
  17198. }
  17199. return this._gl.RGBA;
  17200. }
  17201. switch (type) {
  17202. case Engine.TEXTURETYPE_BYTE:
  17203. switch (format) {
  17204. case Engine.TEXTUREFORMAT_RED:
  17205. return this._gl.R8_SNORM;
  17206. case Engine.TEXTUREFORMAT_RG:
  17207. return this._gl.RG8_SNORM;
  17208. case Engine.TEXTUREFORMAT_RGB:
  17209. return this._gl.RGB8_SNORM;
  17210. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17211. return this._gl.R8I;
  17212. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17213. return this._gl.RG8I;
  17214. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17215. return this._gl.RGB8I;
  17216. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17217. return this._gl.RGBA8I;
  17218. default:
  17219. return this._gl.RGBA8_SNORM;
  17220. }
  17221. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17222. switch (format) {
  17223. case Engine.TEXTUREFORMAT_RED:
  17224. return this._gl.R8;
  17225. case Engine.TEXTUREFORMAT_RG:
  17226. return this._gl.RG8;
  17227. case Engine.TEXTUREFORMAT_RGB:
  17228. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17229. case Engine.TEXTUREFORMAT_RGBA:
  17230. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17231. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17232. return this._gl.R8UI;
  17233. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17234. return this._gl.RG8UI;
  17235. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17236. return this._gl.RGB8UI;
  17237. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17238. return this._gl.RGBA8UI;
  17239. default:
  17240. return this._gl.RGBA8;
  17241. }
  17242. case Engine.TEXTURETYPE_SHORT:
  17243. switch (format) {
  17244. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17245. return this._gl.R16I;
  17246. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17247. return this._gl.RG16I;
  17248. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17249. return this._gl.RGB16I;
  17250. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17251. return this._gl.RGBA16I;
  17252. default:
  17253. return this._gl.RGBA16I;
  17254. }
  17255. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17256. switch (format) {
  17257. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17258. return this._gl.R16UI;
  17259. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17260. return this._gl.RG16UI;
  17261. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17262. return this._gl.RGB16UI;
  17263. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17264. return this._gl.RGBA16UI;
  17265. default:
  17266. return this._gl.RGBA16UI;
  17267. }
  17268. case Engine.TEXTURETYPE_INT:
  17269. switch (format) {
  17270. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17271. return this._gl.R32I;
  17272. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17273. return this._gl.RG32I;
  17274. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17275. return this._gl.RGB32I;
  17276. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17277. return this._gl.RGBA32I;
  17278. default:
  17279. return this._gl.RGBA32I;
  17280. }
  17281. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17282. switch (format) {
  17283. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17284. return this._gl.R32UI;
  17285. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17286. return this._gl.RG32UI;
  17287. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17288. return this._gl.RGB32UI;
  17289. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17290. return this._gl.RGBA32UI;
  17291. default:
  17292. return this._gl.RGBA32UI;
  17293. }
  17294. case Engine.TEXTURETYPE_FLOAT:
  17295. switch (format) {
  17296. case Engine.TEXTUREFORMAT_RED:
  17297. return this._gl.R32F; // By default. Other possibility is R16F.
  17298. case Engine.TEXTUREFORMAT_RG:
  17299. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17300. case Engine.TEXTUREFORMAT_RGB:
  17301. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17302. case Engine.TEXTUREFORMAT_RGBA:
  17303. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17304. default:
  17305. return this._gl.RGBA32F;
  17306. }
  17307. case Engine.TEXTURETYPE_HALF_FLOAT:
  17308. switch (format) {
  17309. case Engine.TEXTUREFORMAT_RED:
  17310. return this._gl.R16F;
  17311. case Engine.TEXTUREFORMAT_RG:
  17312. return this._gl.RG16F;
  17313. case Engine.TEXTUREFORMAT_RGB:
  17314. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17315. case Engine.TEXTUREFORMAT_RGBA:
  17316. return this._gl.RGBA16F;
  17317. default:
  17318. return this._gl.RGBA16F;
  17319. }
  17320. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17321. return this._gl.RGB565;
  17322. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17323. return this._gl.R11F_G11F_B10F;
  17324. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17325. return this._gl.RGB9_E5;
  17326. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17327. return this._gl.RGBA4;
  17328. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17329. return this._gl.RGB5_A1;
  17330. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17331. switch (format) {
  17332. case Engine.TEXTUREFORMAT_RGBA:
  17333. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17334. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17335. return this._gl.RGB10_A2UI;
  17336. default:
  17337. return this._gl.RGB10_A2;
  17338. }
  17339. }
  17340. return this._gl.RGBA8;
  17341. };
  17342. ;
  17343. /** @hidden */
  17344. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17345. if (type === Engine.TEXTURETYPE_FLOAT) {
  17346. return this._gl.RGBA32F;
  17347. }
  17348. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17349. return this._gl.RGBA16F;
  17350. }
  17351. return this._gl.RGBA8;
  17352. };
  17353. ;
  17354. /** @hidden */
  17355. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17356. var _this = this;
  17357. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17358. this._activeRequests.push(request);
  17359. request.onCompleteObservable.add(function (request) {
  17360. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17361. });
  17362. return request;
  17363. };
  17364. /** @hidden */
  17365. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17366. var _this = this;
  17367. return new Promise(function (resolve, reject) {
  17368. _this._loadFile(url, function (data) {
  17369. resolve(data);
  17370. }, undefined, database, useArrayBuffer, function (request, exception) {
  17371. reject(exception);
  17372. });
  17373. });
  17374. };
  17375. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17376. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17377. var onload = function (data) {
  17378. loadedFiles[index] = data;
  17379. loadedFiles._internalCount++;
  17380. if (loadedFiles._internalCount === 6) {
  17381. onfinish(loadedFiles);
  17382. }
  17383. };
  17384. var onerror = function (request, exception) {
  17385. if (onErrorCallBack && request) {
  17386. onErrorCallBack(request.status + " " + request.statusText, exception);
  17387. }
  17388. };
  17389. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17390. };
  17391. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17392. if (onError === void 0) { onError = null; }
  17393. var loadedFiles = [];
  17394. loadedFiles._internalCount = 0;
  17395. for (var index = 0; index < 6; index++) {
  17396. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17397. }
  17398. };
  17399. // Statics
  17400. /**
  17401. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17402. * @returns true if the engine can be created
  17403. * @ignorenaming
  17404. */
  17405. Engine.isSupported = function () {
  17406. try {
  17407. var tempcanvas = document.createElement("canvas");
  17408. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17409. return gl != null && !!window.WebGLRenderingContext;
  17410. }
  17411. catch (e) {
  17412. return false;
  17413. }
  17414. };
  17415. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17416. Engine.ExceptionList = [
  17417. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17418. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17419. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17420. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17421. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17422. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17423. ];
  17424. /** Gets the list of created engines */
  17425. Engine.Instances = new Array();
  17426. /**
  17427. * Hidden
  17428. */
  17429. Engine._TextureLoaders = [];
  17430. // Const statics
  17431. /** Defines that alpha blending is disabled */
  17432. Engine.ALPHA_DISABLE = 0;
  17433. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17434. Engine.ALPHA_ADD = 1;
  17435. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17436. Engine.ALPHA_COMBINE = 2;
  17437. /** Defines that alpha blending to DEST - SRC * DEST */
  17438. Engine.ALPHA_SUBTRACT = 3;
  17439. /** Defines that alpha blending to SRC * DEST */
  17440. Engine.ALPHA_MULTIPLY = 4;
  17441. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17442. Engine.ALPHA_MAXIMIZED = 5;
  17443. /** Defines that alpha blending to SRC + DEST */
  17444. Engine.ALPHA_ONEONE = 6;
  17445. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17446. Engine.ALPHA_PREMULTIPLIED = 7;
  17447. /**
  17448. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17449. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17450. */
  17451. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17452. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17453. Engine.ALPHA_INTERPOLATE = 9;
  17454. /**
  17455. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17456. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17457. */
  17458. Engine.ALPHA_SCREENMODE = 10;
  17459. /** Defines that the ressource is not delayed*/
  17460. Engine.DELAYLOADSTATE_NONE = 0;
  17461. /** Defines that the ressource was successfully delay loaded */
  17462. Engine.DELAYLOADSTATE_LOADED = 1;
  17463. /** Defines that the ressource is currently delay loading */
  17464. Engine.DELAYLOADSTATE_LOADING = 2;
  17465. /** Defines that the ressource is delayed and has not started loading */
  17466. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17467. // Depht or Stencil test Constants.
  17468. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17469. Engine.NEVER = 0x0200;
  17470. /** 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 */
  17471. Engine.ALWAYS = 0x0207;
  17472. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17473. Engine.LESS = 0x0201;
  17474. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17475. Engine.EQUAL = 0x0202;
  17476. /** 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 */
  17477. Engine.LEQUAL = 0x0203;
  17478. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17479. Engine.GREATER = 0x0204;
  17480. /** 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 */
  17481. Engine.GEQUAL = 0x0206;
  17482. /** 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 */
  17483. Engine.NOTEQUAL = 0x0205;
  17484. // Stencil Actions Constants.
  17485. /** Passed to stencilOperation to specify that stencil value must be kept */
  17486. Engine.KEEP = 0x1E00;
  17487. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17488. Engine.REPLACE = 0x1E01;
  17489. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17490. Engine.INCR = 0x1E02;
  17491. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17492. Engine.DECR = 0x1E03;
  17493. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17494. Engine.INVERT = 0x150A;
  17495. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17496. Engine.INCR_WRAP = 0x8507;
  17497. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17498. Engine.DECR_WRAP = 0x8508;
  17499. /** Texture is not repeating outside of 0..1 UVs */
  17500. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17501. /** Texture is repeating outside of 0..1 UVs */
  17502. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17503. /** Texture is repeating and mirrored */
  17504. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17505. /** ALPHA */
  17506. Engine.TEXTUREFORMAT_ALPHA = 0;
  17507. /** LUMINANCE */
  17508. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17509. /** LUMINANCE_ALPHA */
  17510. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17511. /** RGB */
  17512. Engine.TEXTUREFORMAT_RGB = 4;
  17513. /** RGBA */
  17514. Engine.TEXTUREFORMAT_RGBA = 5;
  17515. /** RED */
  17516. Engine.TEXTUREFORMAT_RED = 6;
  17517. /** RED (2nd reference) */
  17518. Engine.TEXTUREFORMAT_R = 6;
  17519. /** RG */
  17520. Engine.TEXTUREFORMAT_RG = 7;
  17521. /** RED_INTEGER */
  17522. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17523. /** RED_INTEGER (2nd reference) */
  17524. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17525. /** RG_INTEGER */
  17526. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17527. /** RGB_INTEGER */
  17528. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17529. /** RGBA_INTEGER */
  17530. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17531. /** UNSIGNED_BYTE */
  17532. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17533. /** UNSIGNED_BYTE (2nd reference) */
  17534. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17535. /** FLOAT */
  17536. Engine.TEXTURETYPE_FLOAT = 1;
  17537. /** HALF_FLOAT */
  17538. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17539. /** BYTE */
  17540. Engine.TEXTURETYPE_BYTE = 3;
  17541. /** SHORT */
  17542. Engine.TEXTURETYPE_SHORT = 4;
  17543. /** UNSIGNED_SHORT */
  17544. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17545. /** INT */
  17546. Engine.TEXTURETYPE_INT = 6;
  17547. /** UNSIGNED_INT */
  17548. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17549. /** UNSIGNED_SHORT_4_4_4_4 */
  17550. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17551. /** UNSIGNED_SHORT_5_5_5_1 */
  17552. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17553. /** UNSIGNED_SHORT_5_6_5 */
  17554. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17555. /** UNSIGNED_INT_2_10_10_10_REV */
  17556. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17557. /** UNSIGNED_INT_24_8 */
  17558. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17559. /** UNSIGNED_INT_10F_11F_11F_REV */
  17560. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17561. /** UNSIGNED_INT_5_9_9_9_REV */
  17562. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17563. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17564. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17565. /** nearest is mag = nearest and min = nearest and mip = linear */
  17566. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17567. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17568. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17569. /** Trilinear is mag = linear and min = linear and mip = linear */
  17570. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17571. /** nearest is mag = nearest and min = nearest and mip = linear */
  17572. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17573. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17574. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17575. /** Trilinear is mag = linear and min = linear and mip = linear */
  17576. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17577. /** mag = nearest and min = nearest and mip = nearest */
  17578. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17579. /** mag = nearest and min = linear and mip = nearest */
  17580. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17581. /** mag = nearest and min = linear and mip = linear */
  17582. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17583. /** mag = nearest and min = linear and mip = none */
  17584. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17585. /** mag = nearest and min = nearest and mip = none */
  17586. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17587. /** mag = linear and min = nearest and mip = nearest */
  17588. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17589. /** mag = linear and min = nearest and mip = linear */
  17590. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17591. /** mag = linear and min = linear and mip = none */
  17592. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17593. /** mag = linear and min = nearest and mip = none */
  17594. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17595. /** Explicit coordinates mode */
  17596. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17597. /** Spherical coordinates mode */
  17598. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17599. /** Planar coordinates mode */
  17600. Engine.TEXTURE_PLANAR_MODE = 2;
  17601. /** Cubic coordinates mode */
  17602. Engine.TEXTURE_CUBIC_MODE = 3;
  17603. /** Projection coordinates mode */
  17604. Engine.TEXTURE_PROJECTION_MODE = 4;
  17605. /** Skybox coordinates mode */
  17606. Engine.TEXTURE_SKYBOX_MODE = 5;
  17607. /** Inverse Cubic coordinates mode */
  17608. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17609. /** Equirectangular coordinates mode */
  17610. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17611. /** Equirectangular Fixed coordinates mode */
  17612. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17613. /** Equirectangular Fixed Mirrored coordinates mode */
  17614. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17615. // Texture rescaling mode
  17616. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17617. Engine.SCALEMODE_FLOOR = 1;
  17618. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17619. Engine.SCALEMODE_NEAREST = 2;
  17620. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17621. Engine.SCALEMODE_CEILING = 3;
  17622. // Updatable statics so stick with vars here
  17623. /**
  17624. * Gets or sets the epsilon value used by collision engine
  17625. */
  17626. Engine.CollisionsEpsilon = 0.001;
  17627. /**
  17628. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17629. */
  17630. Engine.CodeRepository = "src/";
  17631. /**
  17632. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17633. */
  17634. Engine.ShadersRepository = "src/Shaders/";
  17635. return Engine;
  17636. }());
  17637. BABYLON.Engine = Engine;
  17638. })(BABYLON || (BABYLON = {}));
  17639. //# sourceMappingURL=babylon.engine.js.map
  17640. var BABYLON;
  17641. (function (BABYLON) {
  17642. /**
  17643. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17644. */
  17645. var Node = /** @class */ (function () {
  17646. /**
  17647. * Creates a new Node
  17648. * @param {string} name - the name and id to be given to this node
  17649. * @param {BABYLON.Scene} the scene this node will be added to
  17650. */
  17651. function Node(name, scene) {
  17652. if (scene === void 0) { scene = null; }
  17653. /**
  17654. * Gets or sets a string used to store user defined state for the node
  17655. */
  17656. this.state = "";
  17657. /**
  17658. * Gets or sets an object used to store user defined information for the node
  17659. */
  17660. this.metadata = null;
  17661. /**
  17662. * Gets or sets a boolean used to define if the node must be serialized
  17663. */
  17664. this.doNotSerialize = false;
  17665. /** @hidden */
  17666. this._isDisposed = false;
  17667. /**
  17668. * Gets a list of Animations associated with the node
  17669. */
  17670. this.animations = new Array();
  17671. this._ranges = {};
  17672. this._isEnabled = true;
  17673. this._isParentEnabled = true;
  17674. this._isReady = true;
  17675. /** @hidden */
  17676. this._currentRenderId = -1;
  17677. this._parentRenderId = -1;
  17678. this._childRenderId = -1;
  17679. /** @hidden */
  17680. this._worldMatrix = BABYLON.Matrix.Identity();
  17681. /** @hidden */
  17682. this._worldMatrixDeterminant = 0;
  17683. this._animationPropertiesOverride = null;
  17684. /**
  17685. * An event triggered when the mesh is disposed
  17686. */
  17687. this.onDisposeObservable = new BABYLON.Observable();
  17688. // Behaviors
  17689. this._behaviors = new Array();
  17690. this.name = name;
  17691. this.id = name;
  17692. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17693. this.uniqueId = this._scene.getUniqueId();
  17694. this._initCache();
  17695. this._scene.rootNodes.push(this);
  17696. }
  17697. /**
  17698. * Add a new node constructor
  17699. * @param type defines the type name of the node to construct
  17700. * @param constructorFunc defines the constructor function
  17701. */
  17702. Node.AddNodeConstructor = function (type, constructorFunc) {
  17703. this._NodeConstructors[type] = constructorFunc;
  17704. };
  17705. /**
  17706. * Returns a node constructor based on type name
  17707. * @param type defines the type name
  17708. * @param name defines the new node name
  17709. * @param scene defines the hosting scene
  17710. * @param options defines optional options to transmit to constructors
  17711. * @returns the new constructor or null
  17712. */
  17713. Node.Construct = function (type, name, scene, options) {
  17714. var constructorFunc = this._NodeConstructors[type];
  17715. if (!constructorFunc) {
  17716. return null;
  17717. }
  17718. return constructorFunc(name, scene, options);
  17719. };
  17720. /**
  17721. * Gets a boolean indicating if the node has been disposed
  17722. * @returns true if the node was disposed
  17723. */
  17724. Node.prototype.isDisposed = function () {
  17725. return this._isDisposed;
  17726. };
  17727. Object.defineProperty(Node.prototype, "parent", {
  17728. get: function () {
  17729. return this._parentNode;
  17730. },
  17731. /**
  17732. * Gets or sets the parent of the node
  17733. */
  17734. set: function (parent) {
  17735. if (this._parentNode === parent) {
  17736. return;
  17737. }
  17738. var previousParentNode = this._parentNode;
  17739. // Remove self from list of children of parent
  17740. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17741. var index = this._parentNode._children.indexOf(this);
  17742. if (index !== -1) {
  17743. this._parentNode._children.splice(index, 1);
  17744. }
  17745. if (!parent) {
  17746. // Need to add this node to the rootNodes
  17747. this._scene.rootNodes.push(this);
  17748. }
  17749. }
  17750. // Store new parent
  17751. this._parentNode = parent;
  17752. // Add as child to new parent
  17753. if (this._parentNode) {
  17754. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17755. this._parentNode._children = new Array();
  17756. }
  17757. this._parentNode._children.push(this);
  17758. if (!previousParentNode) {
  17759. // Need to remove from rootNodes
  17760. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17761. if (rootNodeIndex > -1) {
  17762. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17763. }
  17764. }
  17765. }
  17766. // Enabled state
  17767. this._syncParentEnabledState();
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17773. /**
  17774. * Gets or sets the animation properties override
  17775. */
  17776. get: function () {
  17777. if (!this._animationPropertiesOverride) {
  17778. return this._scene.animationPropertiesOverride;
  17779. }
  17780. return this._animationPropertiesOverride;
  17781. },
  17782. set: function (value) {
  17783. this._animationPropertiesOverride = value;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. /**
  17789. * Gets a string idenfifying the name of the class
  17790. * @returns "Node" string
  17791. */
  17792. Node.prototype.getClassName = function () {
  17793. return "Node";
  17794. };
  17795. Object.defineProperty(Node.prototype, "onDispose", {
  17796. /**
  17797. * Sets a callback that will be raised when the node will be disposed
  17798. */
  17799. set: function (callback) {
  17800. if (this._onDisposeObserver) {
  17801. this.onDisposeObservable.remove(this._onDisposeObserver);
  17802. }
  17803. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. /**
  17809. * Gets the scene of the node
  17810. * @returns a {BABYLON.Scene}
  17811. */
  17812. Node.prototype.getScene = function () {
  17813. return this._scene;
  17814. };
  17815. /**
  17816. * Gets the engine of the node
  17817. * @returns a {BABYLON.Engine}
  17818. */
  17819. Node.prototype.getEngine = function () {
  17820. return this._scene.getEngine();
  17821. };
  17822. /**
  17823. * Attach a behavior to the node
  17824. * @see http://doc.babylonjs.com/features/behaviour
  17825. * @param behavior defines the behavior to attach
  17826. * @returns the current Node
  17827. */
  17828. Node.prototype.addBehavior = function (behavior) {
  17829. var _this = this;
  17830. var index = this._behaviors.indexOf(behavior);
  17831. if (index !== -1) {
  17832. return this;
  17833. }
  17834. behavior.init();
  17835. if (this._scene.isLoading) {
  17836. // We defer the attach when the scene will be loaded
  17837. this._scene.onDataLoadedObservable.addOnce(function () {
  17838. behavior.attach(_this);
  17839. });
  17840. }
  17841. else {
  17842. behavior.attach(this);
  17843. }
  17844. this._behaviors.push(behavior);
  17845. return this;
  17846. };
  17847. /**
  17848. * Remove an attached behavior
  17849. * @see http://doc.babylonjs.com/features/behaviour
  17850. * @param behavior defines the behavior to attach
  17851. * @returns the current Node
  17852. */
  17853. Node.prototype.removeBehavior = function (behavior) {
  17854. var index = this._behaviors.indexOf(behavior);
  17855. if (index === -1) {
  17856. return this;
  17857. }
  17858. this._behaviors[index].detach();
  17859. this._behaviors.splice(index, 1);
  17860. return this;
  17861. };
  17862. Object.defineProperty(Node.prototype, "behaviors", {
  17863. /**
  17864. * Gets the list of attached behaviors
  17865. * @see http://doc.babylonjs.com/features/behaviour
  17866. */
  17867. get: function () {
  17868. return this._behaviors;
  17869. },
  17870. enumerable: true,
  17871. configurable: true
  17872. });
  17873. /**
  17874. * Gets an attached behavior by name
  17875. * @param name defines the name of the behavior to look for
  17876. * @see http://doc.babylonjs.com/features/behaviour
  17877. * @returns null if behavior was not found else the requested behavior
  17878. */
  17879. Node.prototype.getBehaviorByName = function (name) {
  17880. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17881. var behavior = _a[_i];
  17882. if (behavior.name === name) {
  17883. return behavior;
  17884. }
  17885. }
  17886. return null;
  17887. };
  17888. /**
  17889. * Returns the latest update of the World matrix
  17890. * @returns a Matrix
  17891. */
  17892. Node.prototype.getWorldMatrix = function () {
  17893. if (this._currentRenderId !== this._scene.getRenderId()) {
  17894. this.computeWorldMatrix();
  17895. }
  17896. return this._worldMatrix;
  17897. };
  17898. /** @hidden */
  17899. Node.prototype._getWorldMatrixDeterminant = function () {
  17900. return this._worldMatrixDeterminant;
  17901. };
  17902. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17903. /**
  17904. * Returns directly the latest state of the mesh World matrix.
  17905. * A Matrix is returned.
  17906. */
  17907. get: function () {
  17908. return this._worldMatrix;
  17909. },
  17910. enumerable: true,
  17911. configurable: true
  17912. });
  17913. // override it in derived class if you add new variables to the cache
  17914. // and call the parent class method
  17915. /** @hidden */
  17916. Node.prototype._initCache = function () {
  17917. this._cache = {};
  17918. this._cache.parent = undefined;
  17919. };
  17920. /** @hidden */
  17921. Node.prototype.updateCache = function (force) {
  17922. if (!force && this.isSynchronized())
  17923. return;
  17924. this._cache.parent = this.parent;
  17925. this._updateCache();
  17926. };
  17927. // override it in derived class if you add new variables to the cache
  17928. // and call the parent class method if !ignoreParentClass
  17929. /** @hidden */
  17930. Node.prototype._updateCache = function (ignoreParentClass) {
  17931. };
  17932. // override it in derived class if you add new variables to the cache
  17933. /** @hidden */
  17934. Node.prototype._isSynchronized = function () {
  17935. return true;
  17936. };
  17937. /** @hidden */
  17938. Node.prototype._markSyncedWithParent = function () {
  17939. if (this._parentNode) {
  17940. this._parentRenderId = this._parentNode._childRenderId;
  17941. }
  17942. };
  17943. /** @hidden */
  17944. Node.prototype.isSynchronizedWithParent = function () {
  17945. if (!this._parentNode) {
  17946. return true;
  17947. }
  17948. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17949. return false;
  17950. }
  17951. return this._parentNode.isSynchronized();
  17952. };
  17953. /** @hidden */
  17954. Node.prototype.isSynchronized = function () {
  17955. if (this._cache.parent != this._parentNode) {
  17956. this._cache.parent = this._parentNode;
  17957. return false;
  17958. }
  17959. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17960. return false;
  17961. }
  17962. return this._isSynchronized();
  17963. };
  17964. /**
  17965. * Is this node ready to be used/rendered
  17966. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17967. * @return true if the node is ready
  17968. */
  17969. Node.prototype.isReady = function (completeCheck) {
  17970. if (completeCheck === void 0) { completeCheck = false; }
  17971. return this._isReady;
  17972. };
  17973. /**
  17974. * Is this node enabled?
  17975. * 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
  17976. * @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
  17977. * @return whether this node (and its parent) is enabled
  17978. */
  17979. Node.prototype.isEnabled = function (checkAncestors) {
  17980. if (checkAncestors === void 0) { checkAncestors = true; }
  17981. if (checkAncestors === false) {
  17982. return this._isEnabled;
  17983. }
  17984. if (!this._isEnabled) {
  17985. return false;
  17986. }
  17987. return this._isParentEnabled;
  17988. };
  17989. /** @hidden */
  17990. Node.prototype._syncParentEnabledState = function () {
  17991. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17992. if (this._children) {
  17993. this._children.forEach(function (c) {
  17994. c._syncParentEnabledState(); // Force children to update accordingly
  17995. });
  17996. }
  17997. };
  17998. /**
  17999. * Set the enabled state of this node
  18000. * @param value defines the new enabled state
  18001. */
  18002. Node.prototype.setEnabled = function (value) {
  18003. this._isEnabled = value;
  18004. this._syncParentEnabledState();
  18005. };
  18006. /**
  18007. * Is this node a descendant of the given node?
  18008. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18009. * @param ancestor defines the parent node to inspect
  18010. * @returns a boolean indicating if this node is a descendant of the given node
  18011. */
  18012. Node.prototype.isDescendantOf = function (ancestor) {
  18013. if (this.parent) {
  18014. if (this.parent === ancestor) {
  18015. return true;
  18016. }
  18017. return this.parent.isDescendantOf(ancestor);
  18018. }
  18019. return false;
  18020. };
  18021. /** @hidden */
  18022. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18023. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18024. if (!this._children) {
  18025. return;
  18026. }
  18027. for (var index = 0; index < this._children.length; index++) {
  18028. var item = this._children[index];
  18029. if (!predicate || predicate(item)) {
  18030. results.push(item);
  18031. }
  18032. if (!directDescendantsOnly) {
  18033. item._getDescendants(results, false, predicate);
  18034. }
  18035. }
  18036. };
  18037. /**
  18038. * Will return all nodes that have this node as ascendant
  18039. * @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
  18040. * @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
  18041. * @return all children nodes of all types
  18042. */
  18043. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18044. var results = new Array();
  18045. this._getDescendants(results, directDescendantsOnly, predicate);
  18046. return results;
  18047. };
  18048. /**
  18049. * Get all child-meshes of this node
  18050. * @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
  18051. * @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
  18052. * @returns an array of {BABYLON.AbstractMesh}
  18053. */
  18054. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18055. var results = [];
  18056. this._getDescendants(results, directDescendantsOnly, function (node) {
  18057. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18058. });
  18059. return results;
  18060. };
  18061. /**
  18062. * Get all child-transformNodes of this node
  18063. * @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
  18064. * @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
  18065. * @returns an array of {BABYLON.TransformNode}
  18066. */
  18067. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18068. var results = [];
  18069. this._getDescendants(results, directDescendantsOnly, function (node) {
  18070. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18071. });
  18072. return results;
  18073. };
  18074. /**
  18075. * Get all direct children of this node
  18076. * @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
  18077. * @returns an array of {BABYLON.Node}
  18078. */
  18079. Node.prototype.getChildren = function (predicate) {
  18080. return this.getDescendants(true, predicate);
  18081. };
  18082. /** @hidden */
  18083. Node.prototype._setReady = function (state) {
  18084. if (state === this._isReady) {
  18085. return;
  18086. }
  18087. if (!state) {
  18088. this._isReady = false;
  18089. return;
  18090. }
  18091. if (this.onReady) {
  18092. this.onReady(this);
  18093. }
  18094. this._isReady = true;
  18095. };
  18096. /**
  18097. * Get an animation by name
  18098. * @param name defines the name of the animation to look for
  18099. * @returns null if not found else the requested animation
  18100. */
  18101. Node.prototype.getAnimationByName = function (name) {
  18102. for (var i = 0; i < this.animations.length; i++) {
  18103. var animation = this.animations[i];
  18104. if (animation.name === name) {
  18105. return animation;
  18106. }
  18107. }
  18108. return null;
  18109. };
  18110. /**
  18111. * Creates an animation range for this node
  18112. * @param name defines the name of the range
  18113. * @param from defines the starting key
  18114. * @param to defines the end key
  18115. */
  18116. Node.prototype.createAnimationRange = function (name, from, to) {
  18117. // check name not already in use
  18118. if (!this._ranges[name]) {
  18119. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18120. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18121. if (this.animations[i]) {
  18122. this.animations[i].createRange(name, from, to);
  18123. }
  18124. }
  18125. }
  18126. };
  18127. /**
  18128. * Delete a specific animation range
  18129. * @param name defines the name of the range to delete
  18130. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18131. */
  18132. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18133. if (deleteFrames === void 0) { deleteFrames = true; }
  18134. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18135. if (this.animations[i]) {
  18136. this.animations[i].deleteRange(name, deleteFrames);
  18137. }
  18138. }
  18139. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18140. };
  18141. /**
  18142. * Get an animation range by name
  18143. * @param name defines the name of the animation range to look for
  18144. * @returns null if not found else the requested animation range
  18145. */
  18146. Node.prototype.getAnimationRange = function (name) {
  18147. return this._ranges[name];
  18148. };
  18149. /**
  18150. * Will start the animation sequence
  18151. * @param name defines the range frames for animation sequence
  18152. * @param loop defines if the animation should loop (false by default)
  18153. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18154. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18155. * @returns the object created for this animation. If range does not exist, it will return null
  18156. */
  18157. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18158. var range = this.getAnimationRange(name);
  18159. if (!range) {
  18160. return null;
  18161. }
  18162. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18163. };
  18164. /**
  18165. * Serialize animation ranges into a JSON compatible object
  18166. * @returns serialization object
  18167. */
  18168. Node.prototype.serializeAnimationRanges = function () {
  18169. var serializationRanges = [];
  18170. for (var name in this._ranges) {
  18171. var localRange = this._ranges[name];
  18172. if (!localRange) {
  18173. continue;
  18174. }
  18175. var range = {};
  18176. range.name = name;
  18177. range.from = localRange.from;
  18178. range.to = localRange.to;
  18179. serializationRanges.push(range);
  18180. }
  18181. return serializationRanges;
  18182. };
  18183. /**
  18184. * Computes the world matrix of the node
  18185. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18186. * @returns the world matrix
  18187. */
  18188. Node.prototype.computeWorldMatrix = function (force) {
  18189. if (!this._worldMatrix) {
  18190. this._worldMatrix = BABYLON.Matrix.Identity();
  18191. }
  18192. return this._worldMatrix;
  18193. };
  18194. /**
  18195. * Releases resources associated with this node.
  18196. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18197. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18198. */
  18199. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18200. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18201. if (!doNotRecurse) {
  18202. var nodes = this.getDescendants(true);
  18203. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18204. var node = nodes_1[_i];
  18205. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18206. }
  18207. }
  18208. else {
  18209. var transformNodes = this.getChildTransformNodes(true);
  18210. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18211. var transformNode = transformNodes_1[_a];
  18212. transformNode.parent = null;
  18213. transformNode.computeWorldMatrix(true);
  18214. }
  18215. }
  18216. if (!this.parent) {
  18217. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18218. if (rootNodeIndex > -1) {
  18219. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18220. }
  18221. }
  18222. else {
  18223. this.parent = null;
  18224. }
  18225. // Callback
  18226. this.onDisposeObservable.notifyObservers(this);
  18227. this.onDisposeObservable.clear();
  18228. // Behaviors
  18229. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18230. var behavior = _c[_b];
  18231. behavior.detach();
  18232. }
  18233. this._behaviors = [];
  18234. this._isDisposed = true;
  18235. };
  18236. /**
  18237. * Parse animation range data from a serialization object and store them into a given node
  18238. * @param node defines where to store the animation ranges
  18239. * @param parsedNode defines the serialization object to read data from
  18240. * @param scene defines the hosting scene
  18241. */
  18242. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18243. if (parsedNode.ranges) {
  18244. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18245. var data = parsedNode.ranges[index];
  18246. node.createAnimationRange(data.name, data.from, data.to);
  18247. }
  18248. }
  18249. };
  18250. Node._NodeConstructors = {};
  18251. __decorate([
  18252. BABYLON.serialize()
  18253. ], Node.prototype, "name", void 0);
  18254. __decorate([
  18255. BABYLON.serialize()
  18256. ], Node.prototype, "id", void 0);
  18257. __decorate([
  18258. BABYLON.serialize()
  18259. ], Node.prototype, "uniqueId", void 0);
  18260. __decorate([
  18261. BABYLON.serialize()
  18262. ], Node.prototype, "state", void 0);
  18263. __decorate([
  18264. BABYLON.serialize()
  18265. ], Node.prototype, "metadata", void 0);
  18266. return Node;
  18267. }());
  18268. BABYLON.Node = Node;
  18269. })(BABYLON || (BABYLON = {}));
  18270. //# sourceMappingURL=babylon.node.js.map
  18271. var BABYLON;
  18272. (function (BABYLON) {
  18273. // This matrix is used as a value to reset the bounding box.
  18274. var _identityMatrix = BABYLON.Matrix.Identity();
  18275. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18276. var BoundingSphere = /** @class */ (function () {
  18277. /**
  18278. * Creates a new bounding sphere
  18279. * @param min defines the minimum vector (in local space)
  18280. * @param max defines the maximum vector (in local space)
  18281. */
  18282. function BoundingSphere(min, max) {
  18283. this.center = BABYLON.Vector3.Zero();
  18284. this.centerWorld = BABYLON.Vector3.Zero();
  18285. this.reConstruct(min, max);
  18286. }
  18287. /**
  18288. * Recreates the entire bounding sphere from scratch
  18289. * @param min defines the new minimum vector (in local space)
  18290. * @param max defines the new maximum vector (in local space)
  18291. */
  18292. BoundingSphere.prototype.reConstruct = function (min, max) {
  18293. this.minimum = min.clone();
  18294. this.maximum = max.clone();
  18295. var distance = BABYLON.Vector3.Distance(min, max);
  18296. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18297. this.radius = distance * 0.5;
  18298. this.centerWorld.set(0, 0, 0);
  18299. this._update(_identityMatrix);
  18300. };
  18301. /**
  18302. * Scale the current bounding sphere by applying a scale factor
  18303. * @param factor defines the scale factor to apply
  18304. * @returns the current bounding box
  18305. */
  18306. BoundingSphere.prototype.scale = function (factor) {
  18307. var newRadius = this.radius * factor;
  18308. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18309. var min = this.center.subtract(_tempRadiusVector);
  18310. var max = this.center.add(_tempRadiusVector);
  18311. this.reConstruct(min, max);
  18312. return this;
  18313. };
  18314. // Methods
  18315. /** @hidden */
  18316. BoundingSphere.prototype._update = function (world) {
  18317. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18318. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18319. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18320. };
  18321. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18322. for (var i = 0; i < 6; i++) {
  18323. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18324. return false;
  18325. }
  18326. return true;
  18327. };
  18328. BoundingSphere.prototype.intersectsPoint = function (point) {
  18329. var x = this.centerWorld.x - point.x;
  18330. var y = this.centerWorld.y - point.y;
  18331. var z = this.centerWorld.z - point.z;
  18332. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18333. if (this.radiusWorld < distance)
  18334. return false;
  18335. return true;
  18336. };
  18337. // Statics
  18338. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18339. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18340. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18341. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18342. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18343. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18344. return false;
  18345. return true;
  18346. };
  18347. return BoundingSphere;
  18348. }());
  18349. BABYLON.BoundingSphere = BoundingSphere;
  18350. })(BABYLON || (BABYLON = {}));
  18351. //# sourceMappingURL=babylon.boundingSphere.js.map
  18352. var BABYLON;
  18353. (function (BABYLON) {
  18354. /**
  18355. * Class used to store bounding box information
  18356. */
  18357. var BoundingBox = /** @class */ (function () {
  18358. /**
  18359. * Creates a new bounding box
  18360. * @param min defines the minimum vector (in local space)
  18361. * @param max defines the maximum vector (in local space)
  18362. */
  18363. function BoundingBox(min, max) {
  18364. /**
  18365. * Gets the 8 vectors representing the bounding box in world space
  18366. */
  18367. this.vectorsWorld = new Array();
  18368. this.reConstruct(min, max);
  18369. }
  18370. // Methods
  18371. /**
  18372. * Recreates the entire bounding box from scratch
  18373. * @param min defines the new minimum vector (in local space)
  18374. * @param max defines the new maximum vector (in local space)
  18375. */
  18376. BoundingBox.prototype.reConstruct = function (min, max) {
  18377. this.minimum = min.clone();
  18378. this.maximum = max.clone();
  18379. // Bounding vectors
  18380. this.vectors = [
  18381. this.minimum.clone(),
  18382. this.maximum.clone(),
  18383. this.minimum.clone(),
  18384. this.minimum.clone(),
  18385. this.minimum.clone(),
  18386. this.maximum.clone(),
  18387. this.maximum.clone(),
  18388. this.maximum.clone()
  18389. ];
  18390. this.vectors[2].x = this.maximum.x;
  18391. this.vectors[3].y = this.maximum.y;
  18392. this.vectors[4].z = this.maximum.z;
  18393. this.vectors[5].z = this.minimum.z;
  18394. this.vectors[6].x = this.minimum.x;
  18395. this.vectors[7].y = this.minimum.y;
  18396. // OBB
  18397. this.center = this.maximum.add(this.minimum).scale(0.5);
  18398. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18399. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18400. // World
  18401. for (var index = 0; index < this.vectors.length; index++) {
  18402. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18403. }
  18404. this.minimumWorld = BABYLON.Vector3.Zero();
  18405. this.maximumWorld = BABYLON.Vector3.Zero();
  18406. this.centerWorld = BABYLON.Vector3.Zero();
  18407. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18408. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18409. };
  18410. /**
  18411. * Scale the current bounding box by applying a scale factor
  18412. * @param factor defines the scale factor to apply
  18413. * @returns the current bounding box
  18414. */
  18415. BoundingBox.prototype.scale = function (factor) {
  18416. var diff = this.maximum.subtract(this.minimum);
  18417. var distance = diff.length() * factor;
  18418. diff.normalize();
  18419. var newRadius = diff.scale(distance / 2);
  18420. var min = this.center.subtract(newRadius);
  18421. var max = this.center.add(newRadius);
  18422. this.reConstruct(min, max);
  18423. return this;
  18424. };
  18425. /**
  18426. * Gets the world matrix of the bounding box
  18427. * @returns a matrix
  18428. */
  18429. BoundingBox.prototype.getWorldMatrix = function () {
  18430. return this._worldMatrix;
  18431. };
  18432. /**
  18433. * Sets the world matrix stored in the bounding box
  18434. * @param matrix defines the matrix to store
  18435. * @returns current bounding box
  18436. */
  18437. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18438. this._worldMatrix.copyFrom(matrix);
  18439. return this;
  18440. };
  18441. /** @hidden */
  18442. BoundingBox.prototype._update = function (world) {
  18443. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18444. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18445. for (var index = 0; index < this.vectors.length; index++) {
  18446. var v = this.vectorsWorld[index];
  18447. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18448. if (v.x < this.minimumWorld.x)
  18449. this.minimumWorld.x = v.x;
  18450. if (v.y < this.minimumWorld.y)
  18451. this.minimumWorld.y = v.y;
  18452. if (v.z < this.minimumWorld.z)
  18453. this.minimumWorld.z = v.z;
  18454. if (v.x > this.maximumWorld.x)
  18455. this.maximumWorld.x = v.x;
  18456. if (v.y > this.maximumWorld.y)
  18457. this.maximumWorld.y = v.y;
  18458. if (v.z > this.maximumWorld.z)
  18459. this.maximumWorld.z = v.z;
  18460. }
  18461. // Extend
  18462. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18463. this.extendSizeWorld.scaleInPlace(0.5);
  18464. // OBB
  18465. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18466. this.centerWorld.scaleInPlace(0.5);
  18467. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18468. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18469. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18470. this._worldMatrix = world;
  18471. };
  18472. /**
  18473. * Tests if the bounding box is intersecting the frustum planes
  18474. * @param frustumPlanes defines the frustum planes to test
  18475. * @returns true if there is an intersection
  18476. */
  18477. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18478. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18479. };
  18480. /**
  18481. * Tests if the bounding box is entirely inside the frustum planes
  18482. * @param frustumPlanes defines the frustum planes to test
  18483. * @returns true if there is an inclusion
  18484. */
  18485. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18486. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18487. };
  18488. /**
  18489. * Tests if a point is inside the bounding box
  18490. * @param point defines the point to test
  18491. * @returns true if the point is inside the bounding box
  18492. */
  18493. BoundingBox.prototype.intersectsPoint = function (point) {
  18494. var delta = -BABYLON.Epsilon;
  18495. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18496. return false;
  18497. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18498. return false;
  18499. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18500. return false;
  18501. return true;
  18502. };
  18503. /**
  18504. * Tests if the bounding box intersects with a bounding sphere
  18505. * @param sphere defines the sphere to test
  18506. * @returns true if there is an intersection
  18507. */
  18508. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18509. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18510. };
  18511. /**
  18512. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18513. * @param min defines the min vector to use
  18514. * @param max defines the max vector to use
  18515. * @returns true if there is an intersection
  18516. */
  18517. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18518. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18519. return false;
  18520. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18521. return false;
  18522. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18523. return false;
  18524. return true;
  18525. };
  18526. // Statics
  18527. /**
  18528. * Tests if two bounding boxes are intersections
  18529. * @param box0 defines the first box to test
  18530. * @param box1 defines the second box to test
  18531. * @returns true if there is an intersection
  18532. */
  18533. BoundingBox.Intersects = function (box0, box1) {
  18534. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18535. return false;
  18536. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18537. return false;
  18538. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18539. return false;
  18540. return true;
  18541. };
  18542. /**
  18543. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18544. * @param minPoint defines the minimum vector of the bounding box
  18545. * @param maxPoint defines the maximum vector of the bounding box
  18546. * @param sphereCenter defines the sphere center
  18547. * @param sphereRadius defines the sphere radius
  18548. * @returns true if there is an intersection
  18549. */
  18550. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18551. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18552. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18553. return (num <= (sphereRadius * sphereRadius));
  18554. };
  18555. /**
  18556. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18557. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18558. * @param frustumPlanes defines the frustum planes to test
  18559. * @return true if there is an inclusion
  18560. */
  18561. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18562. for (var p = 0; p < 6; p++) {
  18563. for (var i = 0; i < 8; i++) {
  18564. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18565. return false;
  18566. }
  18567. }
  18568. }
  18569. return true;
  18570. };
  18571. /**
  18572. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18573. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18574. * @param frustumPlanes defines the frustum planes to test
  18575. * @return true if there is an intersection
  18576. */
  18577. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18578. for (var p = 0; p < 6; p++) {
  18579. var inCount = 8;
  18580. for (var i = 0; i < 8; i++) {
  18581. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18582. --inCount;
  18583. }
  18584. else {
  18585. break;
  18586. }
  18587. }
  18588. if (inCount === 0)
  18589. return false;
  18590. }
  18591. return true;
  18592. };
  18593. return BoundingBox;
  18594. }());
  18595. BABYLON.BoundingBox = BoundingBox;
  18596. })(BABYLON || (BABYLON = {}));
  18597. //# sourceMappingURL=babylon.boundingBox.js.map
  18598. var BABYLON;
  18599. (function (BABYLON) {
  18600. var computeBoxExtents = function (axis, box) {
  18601. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18602. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18603. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18604. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18605. var r = r0 + r1 + r2;
  18606. return {
  18607. min: p - r,
  18608. max: p + r
  18609. };
  18610. };
  18611. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18612. var axisOverlap = function (axis, box0, box1) {
  18613. var result0 = computeBoxExtents(axis, box0);
  18614. var result1 = computeBoxExtents(axis, box1);
  18615. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18616. };
  18617. var BoundingInfo = /** @class */ (function () {
  18618. function BoundingInfo(minimum, maximum) {
  18619. this.minimum = minimum;
  18620. this.maximum = maximum;
  18621. this._isLocked = false;
  18622. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18623. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18624. }
  18625. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18626. get: function () {
  18627. return this._isLocked;
  18628. },
  18629. set: function (value) {
  18630. this._isLocked = value;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. // Methods
  18636. BoundingInfo.prototype.update = function (world) {
  18637. if (this._isLocked) {
  18638. return;
  18639. }
  18640. this.boundingBox._update(world);
  18641. this.boundingSphere._update(world);
  18642. };
  18643. /**
  18644. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18645. * @param center New center of the bounding info
  18646. * @param extend New extend of the bounding info
  18647. */
  18648. BoundingInfo.prototype.centerOn = function (center, extend) {
  18649. this.minimum = center.subtract(extend);
  18650. this.maximum = center.add(extend);
  18651. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18652. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18653. return this;
  18654. };
  18655. /**
  18656. * Scale the current bounding info by applying a scale factor
  18657. * @param factor defines the scale factor to apply
  18658. * @returns the current bounding info
  18659. */
  18660. BoundingInfo.prototype.scale = function (factor) {
  18661. this.boundingBox.scale(factor);
  18662. this.boundingSphere.scale(factor);
  18663. return this;
  18664. };
  18665. /**
  18666. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18667. * @param frustumPlanes defines the frustum to test
  18668. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18669. * @returns true if the bounding info is in the frustum planes
  18670. */
  18671. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18672. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18673. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18674. return false;
  18675. }
  18676. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18677. return true;
  18678. }
  18679. return this.boundingBox.isInFrustum(frustumPlanes);
  18680. };
  18681. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18682. /**
  18683. * Gets the world distance between the min and max points of the bounding box
  18684. */
  18685. get: function () {
  18686. var boundingBox = this.boundingBox;
  18687. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18688. return size.length();
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18694. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18695. };
  18696. /** @hidden */
  18697. BoundingInfo.prototype._checkCollision = function (collider) {
  18698. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18699. };
  18700. BoundingInfo.prototype.intersectsPoint = function (point) {
  18701. if (!this.boundingSphere.centerWorld) {
  18702. return false;
  18703. }
  18704. if (!this.boundingSphere.intersectsPoint(point)) {
  18705. return false;
  18706. }
  18707. if (!this.boundingBox.intersectsPoint(point)) {
  18708. return false;
  18709. }
  18710. return true;
  18711. };
  18712. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18713. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18714. return false;
  18715. }
  18716. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18717. return false;
  18718. }
  18719. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18720. return false;
  18721. }
  18722. if (!precise) {
  18723. return true;
  18724. }
  18725. var box0 = this.boundingBox;
  18726. var box1 = boundingInfo.boundingBox;
  18727. if (!axisOverlap(box0.directions[0], box0, box1))
  18728. return false;
  18729. if (!axisOverlap(box0.directions[1], box0, box1))
  18730. return false;
  18731. if (!axisOverlap(box0.directions[2], box0, box1))
  18732. return false;
  18733. if (!axisOverlap(box1.directions[0], box0, box1))
  18734. return false;
  18735. if (!axisOverlap(box1.directions[1], box0, box1))
  18736. return false;
  18737. if (!axisOverlap(box1.directions[2], box0, box1))
  18738. return false;
  18739. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18740. return false;
  18741. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18742. return false;
  18743. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18744. return false;
  18745. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18746. return false;
  18747. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18748. return false;
  18749. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18750. return false;
  18751. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18752. return false;
  18753. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18754. return false;
  18755. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18756. return false;
  18757. return true;
  18758. };
  18759. return BoundingInfo;
  18760. }());
  18761. BABYLON.BoundingInfo = BoundingInfo;
  18762. })(BABYLON || (BABYLON = {}));
  18763. //# sourceMappingURL=babylon.boundingInfo.js.map
  18764. var BABYLON;
  18765. (function (BABYLON) {
  18766. var TransformNode = /** @class */ (function (_super) {
  18767. __extends(TransformNode, _super);
  18768. function TransformNode(name, scene, isPure) {
  18769. if (scene === void 0) { scene = null; }
  18770. if (isPure === void 0) { isPure = true; }
  18771. var _this = _super.call(this, name, scene) || this;
  18772. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18773. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18774. _this._up = new BABYLON.Vector3(0, 1, 0);
  18775. _this._right = new BABYLON.Vector3(1, 0, 0);
  18776. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18777. // Properties
  18778. _this._position = BABYLON.Vector3.Zero();
  18779. _this._rotation = BABYLON.Vector3.Zero();
  18780. _this._scaling = BABYLON.Vector3.One();
  18781. _this._isDirty = false;
  18782. /**
  18783. * Set the billboard mode. Default is 0.
  18784. *
  18785. * | Value | Type | Description |
  18786. * | --- | --- | --- |
  18787. * | 0 | BILLBOARDMODE_NONE | |
  18788. * | 1 | BILLBOARDMODE_X | |
  18789. * | 2 | BILLBOARDMODE_Y | |
  18790. * | 4 | BILLBOARDMODE_Z | |
  18791. * | 7 | BILLBOARDMODE_ALL | |
  18792. *
  18793. */
  18794. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18795. _this.scalingDeterminant = 1;
  18796. _this.infiniteDistance = false;
  18797. /**
  18798. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18799. * By default the system will update normals to compensate
  18800. */
  18801. _this.ignoreNonUniformScaling = false;
  18802. _this._localWorld = BABYLON.Matrix.Zero();
  18803. _this._absolutePosition = BABYLON.Vector3.Zero();
  18804. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18805. _this._postMultiplyPivotMatrix = false;
  18806. _this._isWorldMatrixFrozen = false;
  18807. /**
  18808. * An event triggered after the world matrix is updated
  18809. */
  18810. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18811. _this._nonUniformScaling = false;
  18812. if (isPure) {
  18813. _this.getScene().addTransformNode(_this);
  18814. }
  18815. return _this;
  18816. }
  18817. /**
  18818. * Gets a string identifying the name of the class
  18819. * @returns "TransformNode" string
  18820. */
  18821. TransformNode.prototype.getClassName = function () {
  18822. return "TransformNode";
  18823. };
  18824. Object.defineProperty(TransformNode.prototype, "position", {
  18825. /**
  18826. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18827. */
  18828. get: function () {
  18829. return this._position;
  18830. },
  18831. set: function (newPosition) {
  18832. this._position = newPosition;
  18833. this._isDirty = true;
  18834. },
  18835. enumerable: true,
  18836. configurable: true
  18837. });
  18838. Object.defineProperty(TransformNode.prototype, "rotation", {
  18839. /**
  18840. * 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)).
  18841. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18842. */
  18843. get: function () {
  18844. return this._rotation;
  18845. },
  18846. set: function (newRotation) {
  18847. this._rotation = newRotation;
  18848. this._isDirty = true;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. Object.defineProperty(TransformNode.prototype, "scaling", {
  18854. /**
  18855. * 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)).
  18856. */
  18857. get: function () {
  18858. return this._scaling;
  18859. },
  18860. set: function (newScaling) {
  18861. this._scaling = newScaling;
  18862. this._isDirty = true;
  18863. },
  18864. enumerable: true,
  18865. configurable: true
  18866. });
  18867. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18868. /**
  18869. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18870. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18871. */
  18872. get: function () {
  18873. return this._rotationQuaternion;
  18874. },
  18875. set: function (quaternion) {
  18876. this._rotationQuaternion = quaternion;
  18877. //reset the rotation vector.
  18878. if (quaternion && this.rotation.length()) {
  18879. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18880. }
  18881. },
  18882. enumerable: true,
  18883. configurable: true
  18884. });
  18885. Object.defineProperty(TransformNode.prototype, "forward", {
  18886. /**
  18887. * The forward direction of that transform in world space.
  18888. */
  18889. get: function () {
  18890. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. Object.defineProperty(TransformNode.prototype, "up", {
  18896. /**
  18897. * The up direction of that transform in world space.
  18898. */
  18899. get: function () {
  18900. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. Object.defineProperty(TransformNode.prototype, "right", {
  18906. /**
  18907. * The right direction of that transform in world space.
  18908. */
  18909. get: function () {
  18910. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18911. },
  18912. enumerable: true,
  18913. configurable: true
  18914. });
  18915. /**
  18916. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18917. * Returns the TransformNode.
  18918. */
  18919. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18920. this._poseMatrix.copyFrom(matrix);
  18921. return this;
  18922. };
  18923. /**
  18924. * Returns the mesh Pose matrix.
  18925. * Returned object : Matrix
  18926. */
  18927. TransformNode.prototype.getPoseMatrix = function () {
  18928. return this._poseMatrix;
  18929. };
  18930. /** @hidden */
  18931. TransformNode.prototype._isSynchronized = function () {
  18932. if (this._isDirty) {
  18933. return false;
  18934. }
  18935. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18936. return false;
  18937. if (this._cache.pivotMatrixUpdated) {
  18938. return false;
  18939. }
  18940. if (this.infiniteDistance) {
  18941. return false;
  18942. }
  18943. if (!this._cache.position.equals(this._position))
  18944. return false;
  18945. if (this._rotationQuaternion) {
  18946. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18947. return false;
  18948. }
  18949. if (!this._cache.rotation.equals(this._rotation))
  18950. return false;
  18951. if (!this._cache.scaling.equals(this._scaling))
  18952. return false;
  18953. return true;
  18954. };
  18955. /** @hidden */
  18956. TransformNode.prototype._initCache = function () {
  18957. _super.prototype._initCache.call(this);
  18958. this._cache.localMatrixUpdated = false;
  18959. this._cache.position = BABYLON.Vector3.Zero();
  18960. this._cache.scaling = BABYLON.Vector3.Zero();
  18961. this._cache.rotation = BABYLON.Vector3.Zero();
  18962. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18963. this._cache.billboardMode = -1;
  18964. };
  18965. TransformNode.prototype.markAsDirty = function (property) {
  18966. if (property === "rotation") {
  18967. this.rotationQuaternion = null;
  18968. }
  18969. this._currentRenderId = Number.MAX_VALUE;
  18970. this._isDirty = true;
  18971. return this;
  18972. };
  18973. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18974. /**
  18975. * Returns the current mesh absolute position.
  18976. * Returns a Vector3.
  18977. */
  18978. get: function () {
  18979. return this._absolutePosition;
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. /**
  18985. * Sets a new matrix to apply before all other transformation
  18986. * @param matrix defines the transform matrix
  18987. * @returns the current TransformNode
  18988. */
  18989. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18990. return this.setPivotMatrix(matrix, false);
  18991. };
  18992. /**
  18993. * Sets a new pivot matrix to the current node
  18994. * @param matrix defines the new pivot matrix to use
  18995. * @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
  18996. * @returns the current TransformNode
  18997. */
  18998. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18999. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19000. this._pivotMatrix = matrix.clone();
  19001. this._cache.pivotMatrixUpdated = true;
  19002. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19003. if (this._postMultiplyPivotMatrix) {
  19004. if (!this._pivotMatrixInverse) {
  19005. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19006. }
  19007. else {
  19008. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19009. }
  19010. }
  19011. return this;
  19012. };
  19013. /**
  19014. * Returns the mesh pivot matrix.
  19015. * Default : Identity.
  19016. * A Matrix is returned.
  19017. */
  19018. TransformNode.prototype.getPivotMatrix = function () {
  19019. return this._pivotMatrix;
  19020. };
  19021. /**
  19022. * Prevents the World matrix to be computed any longer.
  19023. * Returns the TransformNode.
  19024. */
  19025. TransformNode.prototype.freezeWorldMatrix = function () {
  19026. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19027. this.computeWorldMatrix(true);
  19028. this._isWorldMatrixFrozen = true;
  19029. return this;
  19030. };
  19031. /**
  19032. * Allows back the World matrix computation.
  19033. * Returns the TransformNode.
  19034. */
  19035. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19036. this._isWorldMatrixFrozen = false;
  19037. this.computeWorldMatrix(true);
  19038. return this;
  19039. };
  19040. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19041. /**
  19042. * True if the World matrix has been frozen.
  19043. * Returns a boolean.
  19044. */
  19045. get: function () {
  19046. return this._isWorldMatrixFrozen;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. /**
  19052. * Retuns the mesh absolute position in the World.
  19053. * Returns a Vector3.
  19054. */
  19055. TransformNode.prototype.getAbsolutePosition = function () {
  19056. this.computeWorldMatrix();
  19057. return this._absolutePosition;
  19058. };
  19059. /**
  19060. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19061. * Returns the TransformNode.
  19062. */
  19063. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19064. if (!absolutePosition) {
  19065. return this;
  19066. }
  19067. var absolutePositionX;
  19068. var absolutePositionY;
  19069. var absolutePositionZ;
  19070. if (absolutePosition.x === undefined) {
  19071. if (arguments.length < 3) {
  19072. return this;
  19073. }
  19074. absolutePositionX = arguments[0];
  19075. absolutePositionY = arguments[1];
  19076. absolutePositionZ = arguments[2];
  19077. }
  19078. else {
  19079. absolutePositionX = absolutePosition.x;
  19080. absolutePositionY = absolutePosition.y;
  19081. absolutePositionZ = absolutePosition.z;
  19082. }
  19083. if (this.parent) {
  19084. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19085. invertParentWorldMatrix.invert();
  19086. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19087. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19088. }
  19089. else {
  19090. this.position.x = absolutePositionX;
  19091. this.position.y = absolutePositionY;
  19092. this.position.z = absolutePositionZ;
  19093. }
  19094. return this;
  19095. };
  19096. /**
  19097. * Sets the mesh position in its local space.
  19098. * Returns the TransformNode.
  19099. */
  19100. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19101. this.computeWorldMatrix();
  19102. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19103. return this;
  19104. };
  19105. /**
  19106. * Returns the mesh position in the local space from the current World matrix values.
  19107. * Returns a new Vector3.
  19108. */
  19109. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19110. this.computeWorldMatrix();
  19111. var invLocalWorldMatrix = this._localWorld.clone();
  19112. invLocalWorldMatrix.invert();
  19113. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19114. };
  19115. /**
  19116. * Translates the mesh along the passed Vector3 in its local space.
  19117. * Returns the TransformNode.
  19118. */
  19119. TransformNode.prototype.locallyTranslate = function (vector3) {
  19120. this.computeWorldMatrix(true);
  19121. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19122. return this;
  19123. };
  19124. /**
  19125. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19126. * @param targetPoint the position (must be in same space as current mesh) to look at
  19127. * @param yawCor optional yaw (y-axis) correction in radians
  19128. * @param pitchCor optional pitch (x-axis) correction in radians
  19129. * @param rollCor optional roll (z-axis) correction in radians
  19130. * @param space the choosen space of the target
  19131. * @returns the TransformNode.
  19132. */
  19133. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19134. if (yawCor === void 0) { yawCor = 0; }
  19135. if (pitchCor === void 0) { pitchCor = 0; }
  19136. if (rollCor === void 0) { rollCor = 0; }
  19137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19138. var dv = TransformNode._lookAtVectorCache;
  19139. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19140. targetPoint.subtractToRef(pos, dv);
  19141. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19142. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19143. var pitch = Math.atan2(dv.y, len);
  19144. if (this.rotationQuaternion) {
  19145. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19146. }
  19147. else {
  19148. this.rotation.x = pitch + pitchCor;
  19149. this.rotation.y = yaw + yawCor;
  19150. this.rotation.z = rollCor;
  19151. }
  19152. return this;
  19153. };
  19154. /**
  19155. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19156. * This Vector3 is expressed in the World space.
  19157. */
  19158. TransformNode.prototype.getDirection = function (localAxis) {
  19159. var result = BABYLON.Vector3.Zero();
  19160. this.getDirectionToRef(localAxis, result);
  19161. return result;
  19162. };
  19163. /**
  19164. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19165. * localAxis is expressed in the mesh local space.
  19166. * result is computed in the Wordl space from the mesh World matrix.
  19167. * Returns the TransformNode.
  19168. */
  19169. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19170. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19171. return this;
  19172. };
  19173. /**
  19174. * Sets a new pivot point to the current node
  19175. * @param point defines the new pivot point to use
  19176. * @param space defines if the point is in world or local space (local by default)
  19177. * @returns the current TransformNode
  19178. */
  19179. TransformNode.prototype.setPivotPoint = function (point, space) {
  19180. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19181. if (this.getScene().getRenderId() == 0) {
  19182. this.computeWorldMatrix(true);
  19183. }
  19184. var wm = this.getWorldMatrix();
  19185. if (space == BABYLON.Space.WORLD) {
  19186. var tmat = BABYLON.Tmp.Matrix[0];
  19187. wm.invertToRef(tmat);
  19188. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19189. }
  19190. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19191. };
  19192. /**
  19193. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19194. */
  19195. TransformNode.prototype.getPivotPoint = function () {
  19196. var point = BABYLON.Vector3.Zero();
  19197. this.getPivotPointToRef(point);
  19198. return point;
  19199. };
  19200. /**
  19201. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19202. * Returns the TransformNode.
  19203. */
  19204. TransformNode.prototype.getPivotPointToRef = function (result) {
  19205. result.x = -this._pivotMatrix.m[12];
  19206. result.y = -this._pivotMatrix.m[13];
  19207. result.z = -this._pivotMatrix.m[14];
  19208. return this;
  19209. };
  19210. /**
  19211. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19212. */
  19213. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19214. var point = BABYLON.Vector3.Zero();
  19215. this.getAbsolutePivotPointToRef(point);
  19216. return point;
  19217. };
  19218. /**
  19219. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19220. * Returns the TransformNode.
  19221. */
  19222. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19223. result.x = this._pivotMatrix.m[12];
  19224. result.y = this._pivotMatrix.m[13];
  19225. result.z = this._pivotMatrix.m[14];
  19226. this.getPivotPointToRef(result);
  19227. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19228. return this;
  19229. };
  19230. /**
  19231. * Defines the passed node as the parent of the current node.
  19232. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19233. * Returns the TransformNode.
  19234. */
  19235. TransformNode.prototype.setParent = function (node) {
  19236. if (!node && !this.parent) {
  19237. return this;
  19238. }
  19239. if (!node) {
  19240. var rotation = BABYLON.Tmp.Quaternion[0];
  19241. var position = BABYLON.Tmp.Vector3[0];
  19242. var scale = BABYLON.Tmp.Vector3[1];
  19243. if (this.parent && this.parent.computeWorldMatrix) {
  19244. this.parent.computeWorldMatrix(true);
  19245. }
  19246. this.computeWorldMatrix(true);
  19247. this.getWorldMatrix().decompose(scale, rotation, position);
  19248. if (this.rotationQuaternion) {
  19249. this.rotationQuaternion.copyFrom(rotation);
  19250. }
  19251. else {
  19252. rotation.toEulerAnglesToRef(this.rotation);
  19253. }
  19254. this.scaling.x = scale.x;
  19255. this.scaling.y = scale.y;
  19256. this.scaling.z = scale.z;
  19257. this.position.x = position.x;
  19258. this.position.y = position.y;
  19259. this.position.z = position.z;
  19260. }
  19261. else {
  19262. var rotation = BABYLON.Tmp.Quaternion[0];
  19263. var position = BABYLON.Tmp.Vector3[0];
  19264. var scale = BABYLON.Tmp.Vector3[1];
  19265. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19266. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19267. this.computeWorldMatrix(true);
  19268. node.computeWorldMatrix(true);
  19269. node.getWorldMatrix().invertToRef(invParentMatrix);
  19270. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19271. diffMatrix.decompose(scale, rotation, position);
  19272. if (this.rotationQuaternion) {
  19273. this.rotationQuaternion.copyFrom(rotation);
  19274. }
  19275. else {
  19276. rotation.toEulerAnglesToRef(this.rotation);
  19277. }
  19278. this.position.x = position.x;
  19279. this.position.y = position.y;
  19280. this.position.z = position.z;
  19281. this.scaling.x = scale.x;
  19282. this.scaling.y = scale.y;
  19283. this.scaling.z = scale.z;
  19284. }
  19285. this.parent = node;
  19286. return this;
  19287. };
  19288. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19289. get: function () {
  19290. return this._nonUniformScaling;
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. /** @hidden */
  19296. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19297. if (this._nonUniformScaling === value) {
  19298. return false;
  19299. }
  19300. this._nonUniformScaling = value;
  19301. return true;
  19302. };
  19303. /**
  19304. * Attach the current TransformNode to another TransformNode associated with a bone
  19305. * @param bone Bone affecting the TransformNode
  19306. * @param affectedTransformNode TransformNode associated with the bone
  19307. */
  19308. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19309. this._transformToBoneReferal = affectedTransformNode;
  19310. this.parent = bone;
  19311. if (bone.getWorldMatrix().determinant() < 0) {
  19312. this.scalingDeterminant *= -1;
  19313. }
  19314. return this;
  19315. };
  19316. TransformNode.prototype.detachFromBone = function () {
  19317. if (!this.parent) {
  19318. return this;
  19319. }
  19320. if (this.parent.getWorldMatrix().determinant() < 0) {
  19321. this.scalingDeterminant *= -1;
  19322. }
  19323. this._transformToBoneReferal = null;
  19324. this.parent = null;
  19325. return this;
  19326. };
  19327. /**
  19328. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19329. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19330. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19331. * The passed axis is also normalized.
  19332. * Returns the TransformNode.
  19333. */
  19334. TransformNode.prototype.rotate = function (axis, amount, space) {
  19335. axis.normalize();
  19336. if (!this.rotationQuaternion) {
  19337. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19338. this.rotation = BABYLON.Vector3.Zero();
  19339. }
  19340. var rotationQuaternion;
  19341. if (!space || space === BABYLON.Space.LOCAL) {
  19342. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19343. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19344. }
  19345. else {
  19346. if (this.parent) {
  19347. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19348. invertParentWorldMatrix.invert();
  19349. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19350. }
  19351. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19352. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19353. }
  19354. return this;
  19355. };
  19356. /**
  19357. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19358. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19359. * The passed axis is also normalized.
  19360. * Returns the TransformNode.
  19361. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19362. */
  19363. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19364. axis.normalize();
  19365. if (!this.rotationQuaternion) {
  19366. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19367. this.rotation.copyFromFloats(0, 0, 0);
  19368. }
  19369. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19370. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19371. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19372. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19373. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19374. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19375. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19376. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19377. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19378. return this;
  19379. };
  19380. /**
  19381. * Translates the mesh along the axis vector for the passed distance in the given space.
  19382. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19383. * Returns the TransformNode.
  19384. */
  19385. TransformNode.prototype.translate = function (axis, distance, space) {
  19386. var displacementVector = axis.scale(distance);
  19387. if (!space || space === BABYLON.Space.LOCAL) {
  19388. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19389. this.setPositionWithLocalVector(tempV3);
  19390. }
  19391. else {
  19392. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19393. }
  19394. return this;
  19395. };
  19396. /**
  19397. * Adds a rotation step to the mesh current rotation.
  19398. * x, y, z are Euler angles expressed in radians.
  19399. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19400. * This means this rotation is made in the mesh local space only.
  19401. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19402. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19403. * ```javascript
  19404. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19405. * ```
  19406. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19407. * 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.
  19408. * Returns the TransformNode.
  19409. */
  19410. TransformNode.prototype.addRotation = function (x, y, z) {
  19411. var rotationQuaternion;
  19412. if (this.rotationQuaternion) {
  19413. rotationQuaternion = this.rotationQuaternion;
  19414. }
  19415. else {
  19416. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19417. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19418. }
  19419. var accumulation = BABYLON.Tmp.Quaternion[0];
  19420. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19421. rotationQuaternion.multiplyInPlace(accumulation);
  19422. if (!this.rotationQuaternion) {
  19423. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19424. }
  19425. return this;
  19426. };
  19427. /**
  19428. * Computes the world matrix of the node
  19429. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19430. * @returns the world matrix
  19431. */
  19432. TransformNode.prototype.computeWorldMatrix = function (force) {
  19433. if (this._isWorldMatrixFrozen) {
  19434. return this._worldMatrix;
  19435. }
  19436. if (!force && this.isSynchronized()) {
  19437. this._currentRenderId = this.getScene().getRenderId();
  19438. return this._worldMatrix;
  19439. }
  19440. this._updateCache();
  19441. this._cache.position.copyFrom(this.position);
  19442. this._cache.scaling.copyFrom(this.scaling);
  19443. this._cache.pivotMatrixUpdated = false;
  19444. this._cache.billboardMode = this.billboardMode;
  19445. this._currentRenderId = this.getScene().getRenderId();
  19446. this._childRenderId = this.getScene().getRenderId();
  19447. this._isDirty = false;
  19448. // Scaling
  19449. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19450. // Rotation
  19451. //rotate, if quaternion is set and rotation was used
  19452. if (this.rotationQuaternion) {
  19453. var len = this.rotation.length();
  19454. if (len) {
  19455. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19456. this.rotation.copyFromFloats(0, 0, 0);
  19457. }
  19458. }
  19459. if (this.rotationQuaternion) {
  19460. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19461. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19462. }
  19463. else {
  19464. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19465. this._cache.rotation.copyFrom(this.rotation);
  19466. }
  19467. // Translation
  19468. var camera = this.getScene().activeCamera;
  19469. if (this.infiniteDistance && !this.parent && camera) {
  19470. var cameraWorldMatrix = camera.getWorldMatrix();
  19471. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19472. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19473. }
  19474. else {
  19475. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19476. }
  19477. // Composing transformations
  19478. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19479. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19480. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19481. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19482. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19483. // Need to decompose each rotation here
  19484. var currentPosition = BABYLON.Tmp.Vector3[3];
  19485. if (this.parent && this.parent.getWorldMatrix) {
  19486. if (this._transformToBoneReferal) {
  19487. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19488. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19489. }
  19490. else {
  19491. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19492. }
  19493. }
  19494. else {
  19495. currentPosition.copyFrom(this.position);
  19496. }
  19497. currentPosition.subtractInPlace(camera.globalPosition);
  19498. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19499. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19500. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19501. }
  19502. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19503. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19504. }
  19505. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19506. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19507. }
  19508. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19509. }
  19510. else {
  19511. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19512. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19513. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19514. }
  19515. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19516. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19517. }
  19518. // Post multiply inverse of pivotMatrix
  19519. if (this._postMultiplyPivotMatrix) {
  19520. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19521. }
  19522. // Local world
  19523. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19524. // Parent
  19525. if (this.parent && this.parent.getWorldMatrix) {
  19526. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19527. if (this._transformToBoneReferal) {
  19528. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19529. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19530. }
  19531. else {
  19532. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19533. }
  19534. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19535. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19536. this._worldMatrix.copyFrom(this._localWorld);
  19537. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19538. }
  19539. else {
  19540. if (this._transformToBoneReferal) {
  19541. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19542. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19543. }
  19544. else {
  19545. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19546. }
  19547. }
  19548. this._markSyncedWithParent();
  19549. }
  19550. else {
  19551. this._worldMatrix.copyFrom(this._localWorld);
  19552. }
  19553. // Normal matrix
  19554. if (!this.ignoreNonUniformScaling) {
  19555. if (this.scaling.isNonUniform) {
  19556. this._updateNonUniformScalingState(true);
  19557. }
  19558. else if (this.parent && this.parent._nonUniformScaling) {
  19559. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19560. }
  19561. else {
  19562. this._updateNonUniformScalingState(false);
  19563. }
  19564. }
  19565. else {
  19566. this._updateNonUniformScalingState(false);
  19567. }
  19568. this._afterComputeWorldMatrix();
  19569. // Absolute position
  19570. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19571. // Callbacks
  19572. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19573. if (!this._poseMatrix) {
  19574. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19575. }
  19576. // Cache the determinant
  19577. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19578. return this._worldMatrix;
  19579. };
  19580. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19581. };
  19582. /**
  19583. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19584. * @param func: callback function to add
  19585. *
  19586. * Returns the TransformNode.
  19587. */
  19588. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19589. this.onAfterWorldMatrixUpdateObservable.add(func);
  19590. return this;
  19591. };
  19592. /**
  19593. * Removes a registered callback function.
  19594. * Returns the TransformNode.
  19595. */
  19596. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19597. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19598. return this;
  19599. };
  19600. /**
  19601. * Clone the current transform node
  19602. * Returns the new transform node
  19603. * @param name Name of the new clone
  19604. * @param newParent New parent for the clone
  19605. * @param doNotCloneChildren Do not clone children hierarchy
  19606. */
  19607. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19608. var _this = this;
  19609. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19610. result.name = name;
  19611. result.id = name;
  19612. if (newParent) {
  19613. result.parent = newParent;
  19614. }
  19615. if (!doNotCloneChildren) {
  19616. // Children
  19617. var directDescendants = this.getDescendants(true);
  19618. for (var index = 0; index < directDescendants.length; index++) {
  19619. var child = directDescendants[index];
  19620. if (child.clone) {
  19621. child.clone(name + "." + child.name, result);
  19622. }
  19623. }
  19624. }
  19625. return result;
  19626. };
  19627. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19628. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19629. serializationObject.type = this.getClassName();
  19630. // Parent
  19631. if (this.parent) {
  19632. serializationObject.parentId = this.parent.id;
  19633. }
  19634. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19635. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19636. }
  19637. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19638. serializationObject.isEnabled = this.isEnabled();
  19639. // Parent
  19640. if (this.parent) {
  19641. serializationObject.parentId = this.parent.id;
  19642. }
  19643. return serializationObject;
  19644. };
  19645. // Statics
  19646. /**
  19647. * Returns a new TransformNode object parsed from the source provided.
  19648. * The parameter `parsedMesh` is the source.
  19649. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19650. */
  19651. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19652. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19653. if (BABYLON.Tags) {
  19654. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19655. }
  19656. if (parsedTransformNode.localMatrix) {
  19657. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19658. }
  19659. else if (parsedTransformNode.pivotMatrix) {
  19660. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19661. }
  19662. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19663. // Parent
  19664. if (parsedTransformNode.parentId) {
  19665. transformNode._waitingParentId = parsedTransformNode.parentId;
  19666. }
  19667. return transformNode;
  19668. };
  19669. /**
  19670. * Releases resources associated with this transform node.
  19671. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19672. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19673. */
  19674. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19675. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19676. // Animations
  19677. this.getScene().stopAnimation(this);
  19678. // Remove from scene
  19679. this.getScene().removeTransformNode(this);
  19680. this.onAfterWorldMatrixUpdateObservable.clear();
  19681. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19682. };
  19683. // Statics
  19684. TransformNode.BILLBOARDMODE_NONE = 0;
  19685. TransformNode.BILLBOARDMODE_X = 1;
  19686. TransformNode.BILLBOARDMODE_Y = 2;
  19687. TransformNode.BILLBOARDMODE_Z = 4;
  19688. TransformNode.BILLBOARDMODE_ALL = 7;
  19689. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19690. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19691. __decorate([
  19692. BABYLON.serializeAsVector3("position")
  19693. ], TransformNode.prototype, "_position", void 0);
  19694. __decorate([
  19695. BABYLON.serializeAsVector3("rotation")
  19696. ], TransformNode.prototype, "_rotation", void 0);
  19697. __decorate([
  19698. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19699. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19700. __decorate([
  19701. BABYLON.serializeAsVector3("scaling")
  19702. ], TransformNode.prototype, "_scaling", void 0);
  19703. __decorate([
  19704. BABYLON.serialize()
  19705. ], TransformNode.prototype, "billboardMode", void 0);
  19706. __decorate([
  19707. BABYLON.serialize()
  19708. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19709. __decorate([
  19710. BABYLON.serialize()
  19711. ], TransformNode.prototype, "infiniteDistance", void 0);
  19712. __decorate([
  19713. BABYLON.serialize()
  19714. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19715. return TransformNode;
  19716. }(BABYLON.Node));
  19717. BABYLON.TransformNode = TransformNode;
  19718. })(BABYLON || (BABYLON = {}));
  19719. //# sourceMappingURL=babylon.transformNode.js.map
  19720. var BABYLON;
  19721. (function (BABYLON) {
  19722. /**
  19723. * Class used to store all common mesh properties
  19724. */
  19725. var AbstractMesh = /** @class */ (function (_super) {
  19726. __extends(AbstractMesh, _super);
  19727. // Constructor
  19728. /**
  19729. * Creates a new AbstractMesh
  19730. * @param name defines the name of the mesh
  19731. * @param scene defines the hosting scene
  19732. */
  19733. function AbstractMesh(name, scene) {
  19734. if (scene === void 0) { scene = null; }
  19735. var _this = _super.call(this, name, scene, false) || this;
  19736. _this._facetNb = 0; // facet number
  19737. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19738. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19739. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19740. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19741. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19742. _this._subDiv = {
  19743. max: 1,
  19744. X: 1,
  19745. Y: 1,
  19746. Z: 1
  19747. };
  19748. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19749. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19750. /** Gets ot sets the culling strategy to use to find visible meshes */
  19751. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19752. // Events
  19753. /**
  19754. * An event triggered when this mesh collides with another one
  19755. */
  19756. _this.onCollideObservable = new BABYLON.Observable();
  19757. /**
  19758. * An event triggered when the collision's position changes
  19759. */
  19760. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19761. /**
  19762. * An event triggered when material is changed
  19763. */
  19764. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19765. // Properties
  19766. /**
  19767. * Gets or sets the orientation for POV movement & rotation
  19768. */
  19769. _this.definedFacingForward = true;
  19770. /**
  19771. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19772. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19773. * * 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.
  19774. * @see http://doc.babylonjs.com/features/occlusionquery
  19775. */
  19776. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19777. /**
  19778. * 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:
  19779. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19780. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19781. * * 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.
  19782. * @see http://doc.babylonjs.com/features/occlusionquery
  19783. */
  19784. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19785. /**
  19786. * 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.
  19787. * The default value is -1 which means don't break the query and wait till the result
  19788. * @see http://doc.babylonjs.com/features/occlusionquery
  19789. */
  19790. _this.occlusionRetryCount = -1;
  19791. /** @hidden */
  19792. _this._occlusionInternalRetryCounter = 0;
  19793. /** @hidden */
  19794. _this._isOccluded = false;
  19795. /** @hidden */
  19796. _this._isOcclusionQueryInProgress = false;
  19797. _this._visibility = 1.0;
  19798. /** Gets or sets the alpha index used to sort transparent meshes
  19799. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19800. */
  19801. _this.alphaIndex = Number.MAX_VALUE;
  19802. /**
  19803. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19804. */
  19805. _this.isVisible = true;
  19806. /**
  19807. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19808. */
  19809. _this.isPickable = true;
  19810. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19811. _this.showSubMeshesBoundingBox = false;
  19812. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19813. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19814. */
  19815. _this.isBlocker = false;
  19816. /**
  19817. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19818. */
  19819. _this.enablePointerMoveEvents = false;
  19820. /**
  19821. * Specifies the rendering group id for this mesh (0 by default)
  19822. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19823. */
  19824. _this.renderingGroupId = 0;
  19825. _this._receiveShadows = false;
  19826. /** Defines color to use when rendering outline */
  19827. _this.outlineColor = BABYLON.Color3.Red();
  19828. /** Define width to use when rendering outline */
  19829. _this.outlineWidth = 0.02;
  19830. /** Defines color to use when rendering overlay */
  19831. _this.overlayColor = BABYLON.Color3.Red();
  19832. /** Defines alpha to use when rendering overlay */
  19833. _this.overlayAlpha = 0.5;
  19834. _this._hasVertexAlpha = false;
  19835. _this._useVertexColors = true;
  19836. _this._computeBonesUsingShaders = true;
  19837. _this._numBoneInfluencers = 4;
  19838. _this._applyFog = true;
  19839. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19840. _this.useOctreeForRenderingSelection = true;
  19841. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19842. _this.useOctreeForPicking = true;
  19843. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19844. _this.useOctreeForCollisions = true;
  19845. _this._layerMask = 0x0FFFFFFF;
  19846. /**
  19847. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19848. */
  19849. _this.alwaysSelectAsActiveMesh = false;
  19850. /**
  19851. * Gets or sets the current action manager
  19852. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19853. */
  19854. _this.actionManager = null;
  19855. // Collisions
  19856. _this._checkCollisions = false;
  19857. _this._collisionMask = -1;
  19858. _this._collisionGroup = -1;
  19859. /**
  19860. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19861. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19862. */
  19863. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19864. /**
  19865. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19866. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19867. */
  19868. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19869. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19870. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19871. // Edges
  19872. /**
  19873. * Defines edge width used when edgesRenderer is enabled
  19874. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19875. */
  19876. _this.edgesWidth = 1;
  19877. /**
  19878. * Defines edge color used when edgesRenderer is enabled
  19879. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19880. */
  19881. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19882. // Cache
  19883. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19884. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19885. /** @hidden */
  19886. _this._renderId = 0;
  19887. /** @hidden */
  19888. _this._intersectionsInProgress = new Array();
  19889. /** @hidden */
  19890. _this._unIndexed = false;
  19891. /** @hidden */
  19892. _this._lightSources = new Array();
  19893. /**
  19894. * An event triggered when the mesh is rebuilt.
  19895. */
  19896. _this.onRebuildObservable = new BABYLON.Observable();
  19897. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19898. if (collidedMesh === void 0) { collidedMesh = null; }
  19899. //TODO move this to the collision coordinator!
  19900. if (_this.getScene().workerCollisions)
  19901. newPosition.multiplyInPlace(_this._collider._radius);
  19902. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19903. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19904. _this.position.addInPlace(_this._diffPositionForCollisions);
  19905. }
  19906. if (collidedMesh) {
  19907. _this.onCollideObservable.notifyObservers(collidedMesh);
  19908. }
  19909. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19910. };
  19911. _this.getScene().addMesh(_this);
  19912. _this._resyncLightSources();
  19913. return _this;
  19914. }
  19915. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19916. /**
  19917. * No billboard
  19918. */
  19919. get: function () {
  19920. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19926. /** Billboard on X axis */
  19927. get: function () {
  19928. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19934. /** Billboard on Y axis */
  19935. get: function () {
  19936. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19942. /** Billboard on Z axis */
  19943. get: function () {
  19944. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19950. /** Billboard on all axes */
  19951. get: function () {
  19952. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19958. /**
  19959. * Gets the number of facets in the mesh
  19960. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19961. */
  19962. get: function () {
  19963. return this._facetNb;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19969. /**
  19970. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19971. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19972. */
  19973. get: function () {
  19974. return this._partitioningSubdivisions;
  19975. },
  19976. set: function (nb) {
  19977. this._partitioningSubdivisions = nb;
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19983. /**
  19984. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19985. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19986. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19987. */
  19988. get: function () {
  19989. return this._partitioningBBoxRatio;
  19990. },
  19991. set: function (ratio) {
  19992. this._partitioningBBoxRatio = ratio;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19998. /**
  19999. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20000. * Works only for updatable meshes.
  20001. * Doesn't work with multi-materials
  20002. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20003. */
  20004. get: function () {
  20005. return this._facetDepthSort;
  20006. },
  20007. set: function (sort) {
  20008. this._facetDepthSort = sort;
  20009. },
  20010. enumerable: true,
  20011. configurable: true
  20012. });
  20013. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20014. /**
  20015. * The location (Vector3) where the facet depth sort must be computed from.
  20016. * By default, the active camera position.
  20017. * Used only when facet depth sort is enabled
  20018. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20019. */
  20020. get: function () {
  20021. return this._facetDepthSortFrom;
  20022. },
  20023. set: function (location) {
  20024. this._facetDepthSortFrom = location;
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20030. /**
  20031. * gets a boolean indicating if facetData is enabled
  20032. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20033. */
  20034. get: function () {
  20035. return this._facetDataEnabled;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. /** @hidden */
  20041. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20042. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20043. return false;
  20044. }
  20045. this._markSubMeshesAsMiscDirty();
  20046. return true;
  20047. };
  20048. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20049. /** Set a function to call when this mesh collides with another one */
  20050. set: function (callback) {
  20051. if (this._onCollideObserver) {
  20052. this.onCollideObservable.remove(this._onCollideObserver);
  20053. }
  20054. this._onCollideObserver = this.onCollideObservable.add(callback);
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20060. /** Set a function to call when the collision's position changes */
  20061. set: function (callback) {
  20062. if (this._onCollisionPositionChangeObserver) {
  20063. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20064. }
  20065. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20071. /**
  20072. * 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
  20073. * @see http://doc.babylonjs.com/features/occlusionquery
  20074. */
  20075. get: function () {
  20076. return this._isOccluded;
  20077. },
  20078. set: function (value) {
  20079. this._isOccluded = value;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20085. /**
  20086. * Flag to check the progress status of the query
  20087. * @see http://doc.babylonjs.com/features/occlusionquery
  20088. */
  20089. get: function () {
  20090. return this._isOcclusionQueryInProgress;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20096. /**
  20097. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20098. */
  20099. get: function () {
  20100. return this._visibility;
  20101. },
  20102. /**
  20103. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20104. */
  20105. set: function (value) {
  20106. if (this._visibility === value) {
  20107. return;
  20108. }
  20109. this._visibility = value;
  20110. this._markSubMeshesAsMiscDirty();
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(AbstractMesh.prototype, "material", {
  20116. /** Gets or sets current material */
  20117. get: function () {
  20118. return this._material;
  20119. },
  20120. set: function (value) {
  20121. if (this._material === value) {
  20122. return;
  20123. }
  20124. this._material = value;
  20125. if (this.onMaterialChangedObservable.hasObservers) {
  20126. this.onMaterialChangedObservable.notifyObservers(this);
  20127. }
  20128. if (!this.subMeshes) {
  20129. return;
  20130. }
  20131. this._unBindEffect();
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20137. /**
  20138. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20139. * @see http://doc.babylonjs.com/babylon101/shadows
  20140. */
  20141. get: function () {
  20142. return this._receiveShadows;
  20143. },
  20144. set: function (value) {
  20145. if (this._receiveShadows === value) {
  20146. return;
  20147. }
  20148. this._receiveShadows = value;
  20149. this._markSubMeshesAsLightDirty();
  20150. },
  20151. enumerable: true,
  20152. configurable: true
  20153. });
  20154. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20155. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20156. get: function () {
  20157. return this._hasVertexAlpha;
  20158. },
  20159. set: function (value) {
  20160. if (this._hasVertexAlpha === value) {
  20161. return;
  20162. }
  20163. this._hasVertexAlpha = value;
  20164. this._markSubMeshesAsAttributesDirty();
  20165. this._markSubMeshesAsMiscDirty();
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20171. /** 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) */
  20172. get: function () {
  20173. return this._useVertexColors;
  20174. },
  20175. set: function (value) {
  20176. if (this._useVertexColors === value) {
  20177. return;
  20178. }
  20179. this._useVertexColors = value;
  20180. this._markSubMeshesAsAttributesDirty();
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20186. /**
  20187. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20188. */
  20189. get: function () {
  20190. return this._computeBonesUsingShaders;
  20191. },
  20192. set: function (value) {
  20193. if (this._computeBonesUsingShaders === value) {
  20194. return;
  20195. }
  20196. this._computeBonesUsingShaders = value;
  20197. this._markSubMeshesAsAttributesDirty();
  20198. },
  20199. enumerable: true,
  20200. configurable: true
  20201. });
  20202. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20203. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20204. get: function () {
  20205. return this._numBoneInfluencers;
  20206. },
  20207. set: function (value) {
  20208. if (this._numBoneInfluencers === value) {
  20209. return;
  20210. }
  20211. this._numBoneInfluencers = value;
  20212. this._markSubMeshesAsAttributesDirty();
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20218. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20219. get: function () {
  20220. return this._applyFog;
  20221. },
  20222. set: function (value) {
  20223. if (this._applyFog === value) {
  20224. return;
  20225. }
  20226. this._applyFog = value;
  20227. this._markSubMeshesAsMiscDirty();
  20228. },
  20229. enumerable: true,
  20230. configurable: true
  20231. });
  20232. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20233. /**
  20234. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20235. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20236. */
  20237. get: function () {
  20238. return this._layerMask;
  20239. },
  20240. set: function (value) {
  20241. if (value === this._layerMask) {
  20242. return;
  20243. }
  20244. this._layerMask = value;
  20245. this._resyncLightSources();
  20246. },
  20247. enumerable: true,
  20248. configurable: true
  20249. });
  20250. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20251. /**
  20252. * Gets or sets a collision mask used to mask collisions (default is -1).
  20253. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20254. */
  20255. get: function () {
  20256. return this._collisionMask;
  20257. },
  20258. set: function (mask) {
  20259. this._collisionMask = !isNaN(mask) ? mask : -1;
  20260. },
  20261. enumerable: true,
  20262. configurable: true
  20263. });
  20264. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20265. /**
  20266. * Gets or sets the current collision group mask (-1 by default).
  20267. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20268. */
  20269. get: function () {
  20270. return this._collisionGroup;
  20271. },
  20272. set: function (mask) {
  20273. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20279. /** @hidden */
  20280. get: function () {
  20281. return null;
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20287. get: function () {
  20288. return this._skeleton;
  20289. },
  20290. /**
  20291. * Gets or sets a skeleton to apply skining transformations
  20292. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20293. */
  20294. set: function (value) {
  20295. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20296. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20297. }
  20298. if (value && value.needInitialSkinMatrix) {
  20299. value._registerMeshWithPoseMatrix(this);
  20300. }
  20301. this._skeleton = value;
  20302. if (!this._skeleton) {
  20303. this._bonesTransformMatrices = null;
  20304. }
  20305. this._markSubMeshesAsAttributesDirty();
  20306. },
  20307. enumerable: true,
  20308. configurable: true
  20309. });
  20310. /**
  20311. * Returns the string "AbstractMesh"
  20312. * @returns "AbstractMesh"
  20313. */
  20314. AbstractMesh.prototype.getClassName = function () {
  20315. return "AbstractMesh";
  20316. };
  20317. /**
  20318. * Gets a string representation of the current mesh
  20319. * @param fullDetails defines a boolean indicating if full details must be included
  20320. * @returns a string representation of the current mesh
  20321. */
  20322. AbstractMesh.prototype.toString = function (fullDetails) {
  20323. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20324. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20325. if (this._skeleton) {
  20326. ret += ", skeleton: " + this._skeleton.name;
  20327. }
  20328. if (fullDetails) {
  20329. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20330. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20331. }
  20332. return ret;
  20333. };
  20334. /** @hidden */
  20335. AbstractMesh.prototype._rebuild = function () {
  20336. this.onRebuildObservable.notifyObservers(this);
  20337. if (this._occlusionQuery) {
  20338. this._occlusionQuery = null;
  20339. }
  20340. if (!this.subMeshes) {
  20341. return;
  20342. }
  20343. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20344. var subMesh = _a[_i];
  20345. subMesh._rebuild();
  20346. }
  20347. };
  20348. /** @hidden */
  20349. AbstractMesh.prototype._resyncLightSources = function () {
  20350. this._lightSources.length = 0;
  20351. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20352. var light = _a[_i];
  20353. if (!light.isEnabled()) {
  20354. continue;
  20355. }
  20356. if (light.canAffectMesh(this)) {
  20357. this._lightSources.push(light);
  20358. }
  20359. }
  20360. this._markSubMeshesAsLightDirty();
  20361. };
  20362. /** @hidden */
  20363. AbstractMesh.prototype._resyncLighSource = function (light) {
  20364. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20365. var index = this._lightSources.indexOf(light);
  20366. if (index === -1) {
  20367. if (!isIn) {
  20368. return;
  20369. }
  20370. this._lightSources.push(light);
  20371. }
  20372. else {
  20373. if (isIn) {
  20374. return;
  20375. }
  20376. this._lightSources.splice(index, 1);
  20377. }
  20378. this._markSubMeshesAsLightDirty();
  20379. };
  20380. /** @hidden */
  20381. AbstractMesh.prototype._unBindEffect = function () {
  20382. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20383. var subMesh = _a[_i];
  20384. subMesh.setEffect(null);
  20385. }
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._removeLightSource = function (light) {
  20389. var index = this._lightSources.indexOf(light);
  20390. if (index === -1) {
  20391. return;
  20392. }
  20393. this._lightSources.splice(index, 1);
  20394. this._markSubMeshesAsLightDirty();
  20395. };
  20396. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20397. if (!this.subMeshes) {
  20398. return;
  20399. }
  20400. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20401. var subMesh = _a[_i];
  20402. if (subMesh._materialDefines) {
  20403. func(subMesh._materialDefines);
  20404. }
  20405. }
  20406. };
  20407. /** @hidden */
  20408. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20409. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20410. };
  20411. /** @hidden */
  20412. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20413. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20414. };
  20415. /** @hidden */
  20416. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20417. if (!this.subMeshes) {
  20418. return;
  20419. }
  20420. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20421. var subMesh = _a[_i];
  20422. var material = subMesh.getMaterial();
  20423. if (material) {
  20424. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20425. }
  20426. }
  20427. };
  20428. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20429. /**
  20430. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20431. */
  20432. get: function () {
  20433. return this._scaling;
  20434. },
  20435. set: function (newScaling) {
  20436. this._scaling = newScaling;
  20437. if (this.physicsImpostor) {
  20438. this.physicsImpostor.forceUpdate();
  20439. }
  20440. },
  20441. enumerable: true,
  20442. configurable: true
  20443. });
  20444. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20445. // Methods
  20446. /**
  20447. * Returns true if the mesh is blocked. Implemented by child classes
  20448. */
  20449. get: function () {
  20450. return false;
  20451. },
  20452. enumerable: true,
  20453. configurable: true
  20454. });
  20455. /**
  20456. * Returns the mesh itself by default. Implemented by child classes
  20457. * @param camera defines the camera to use to pick the right LOD level
  20458. * @returns the currentAbstractMesh
  20459. */
  20460. AbstractMesh.prototype.getLOD = function (camera) {
  20461. return this;
  20462. };
  20463. /**
  20464. * Returns 0 by default. Implemented by child classes
  20465. * @returns an integer
  20466. */
  20467. AbstractMesh.prototype.getTotalVertices = function () {
  20468. return 0;
  20469. };
  20470. /**
  20471. * Returns null by default. Implemented by child classes
  20472. * @returns null
  20473. */
  20474. AbstractMesh.prototype.getIndices = function () {
  20475. return null;
  20476. };
  20477. /**
  20478. * Returns the array of the requested vertex data kind. Implemented by child classes
  20479. * @param kind defines the vertex data kind to use
  20480. * @returns null
  20481. */
  20482. AbstractMesh.prototype.getVerticesData = function (kind) {
  20483. return null;
  20484. };
  20485. /**
  20486. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20487. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20488. * Note that a new underlying VertexBuffer object is created each call.
  20489. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20490. * @param kind defines vertex data kind:
  20491. * * BABYLON.VertexBuffer.PositionKind
  20492. * * BABYLON.VertexBuffer.UVKind
  20493. * * BABYLON.VertexBuffer.UV2Kind
  20494. * * BABYLON.VertexBuffer.UV3Kind
  20495. * * BABYLON.VertexBuffer.UV4Kind
  20496. * * BABYLON.VertexBuffer.UV5Kind
  20497. * * BABYLON.VertexBuffer.UV6Kind
  20498. * * BABYLON.VertexBuffer.ColorKind
  20499. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20500. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20501. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20502. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20503. * @param data defines the data source
  20504. * @param updatable defines if the data must be flagged as updatable (or static)
  20505. * @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
  20506. * @returns the current mesh
  20507. */
  20508. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20509. return this;
  20510. };
  20511. /**
  20512. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20513. * If the mesh has no geometry, it is simply returned as it is.
  20514. * @param kind defines vertex data kind:
  20515. * * BABYLON.VertexBuffer.PositionKind
  20516. * * BABYLON.VertexBuffer.UVKind
  20517. * * BABYLON.VertexBuffer.UV2Kind
  20518. * * BABYLON.VertexBuffer.UV3Kind
  20519. * * BABYLON.VertexBuffer.UV4Kind
  20520. * * BABYLON.VertexBuffer.UV5Kind
  20521. * * BABYLON.VertexBuffer.UV6Kind
  20522. * * BABYLON.VertexBuffer.ColorKind
  20523. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20524. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20525. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20526. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20527. * @param data defines the data source
  20528. * @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
  20529. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20530. * @returns the current mesh
  20531. */
  20532. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20533. return this;
  20534. };
  20535. /**
  20536. * Sets the mesh indices,
  20537. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20538. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20539. * @param totalVertices Defines the total number of vertices
  20540. * @returns the current mesh
  20541. */
  20542. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20543. return this;
  20544. };
  20545. /**
  20546. * Gets a boolean indicating if specific vertex data is present
  20547. * @param kind defines the vertex data kind to use
  20548. * @returns true is data kind is present
  20549. */
  20550. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20551. return false;
  20552. };
  20553. /**
  20554. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20555. * @returns a BoundingInfo
  20556. */
  20557. AbstractMesh.prototype.getBoundingInfo = function () {
  20558. if (this._masterMesh) {
  20559. return this._masterMesh.getBoundingInfo();
  20560. }
  20561. if (!this._boundingInfo) {
  20562. // this._boundingInfo is being created here
  20563. this._updateBoundingInfo();
  20564. }
  20565. // cannot be null.
  20566. return this._boundingInfo;
  20567. };
  20568. /**
  20569. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20570. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20571. * @returns the current mesh
  20572. */
  20573. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20574. if (includeDescendants === void 0) { includeDescendants = true; }
  20575. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20576. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20577. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20578. if (maxDimension === 0) {
  20579. return this;
  20580. }
  20581. var scale = 1 / maxDimension;
  20582. this.scaling.scaleInPlace(scale);
  20583. return this;
  20584. };
  20585. /**
  20586. * Overwrite the current bounding info
  20587. * @param boundingInfo defines the new bounding info
  20588. * @returns the current mesh
  20589. */
  20590. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20591. this._boundingInfo = boundingInfo;
  20592. return this;
  20593. };
  20594. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20595. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20596. get: function () {
  20597. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20598. },
  20599. enumerable: true,
  20600. configurable: true
  20601. });
  20602. /** @hidden */
  20603. AbstractMesh.prototype._preActivate = function () {
  20604. };
  20605. /** @hidden */
  20606. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20607. };
  20608. /** @hidden */
  20609. AbstractMesh.prototype._activate = function (renderId) {
  20610. this._renderId = renderId;
  20611. };
  20612. /**
  20613. * Gets the current world matrix
  20614. * @returns a Matrix
  20615. */
  20616. AbstractMesh.prototype.getWorldMatrix = function () {
  20617. if (this._masterMesh) {
  20618. return this._masterMesh.getWorldMatrix();
  20619. }
  20620. return _super.prototype.getWorldMatrix.call(this);
  20621. };
  20622. /** @hidden */
  20623. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20624. if (this._masterMesh) {
  20625. return this._masterMesh._getWorldMatrixDeterminant();
  20626. }
  20627. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20628. };
  20629. // ================================== Point of View Movement =================================
  20630. /**
  20631. * Perform relative position change from the point of view of behind the front of the mesh.
  20632. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20633. * Supports definition of mesh facing forward or backward
  20634. * @param amountRight defines the distance on the right axis
  20635. * @param amountUp defines the distance on the up axis
  20636. * @param amountForward defines the distance on the forward axis
  20637. * @returns the current mesh
  20638. */
  20639. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20640. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20641. return this;
  20642. };
  20643. /**
  20644. * Calculate relative position change from the point of view of behind the front of the mesh.
  20645. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20646. * Supports definition of mesh facing forward or backward
  20647. * @param amountRight defines the distance on the right axis
  20648. * @param amountUp defines the distance on the up axis
  20649. * @param amountForward defines the distance on the forward axis
  20650. * @returns the new displacement vector
  20651. */
  20652. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20653. var rotMatrix = new BABYLON.Matrix();
  20654. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20655. rotQuaternion.toRotationMatrix(rotMatrix);
  20656. var translationDelta = BABYLON.Vector3.Zero();
  20657. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20658. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20659. return translationDelta;
  20660. };
  20661. // ================================== Point of View Rotation =================================
  20662. /**
  20663. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20664. * Supports definition of mesh facing forward or backward
  20665. * @param flipBack defines the flip
  20666. * @param twirlClockwise defines the twirl
  20667. * @param tiltRight defines the tilt
  20668. * @returns the current mesh
  20669. */
  20670. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20671. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20672. return this;
  20673. };
  20674. /**
  20675. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20676. * Supports definition of mesh facing forward or backward.
  20677. * @param flipBack defines the flip
  20678. * @param twirlClockwise defines the twirl
  20679. * @param tiltRight defines the tilt
  20680. * @returns the new rotation vector
  20681. */
  20682. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20683. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20684. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20685. };
  20686. /**
  20687. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20688. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20689. * @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
  20690. * @returns the new bounding vectors
  20691. */
  20692. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20693. if (includeDescendants === void 0) { includeDescendants = true; }
  20694. if (predicate === void 0) { predicate = null; }
  20695. // Ensures that all world matrix will be recomputed.
  20696. this.getScene().incrementRenderId();
  20697. this.computeWorldMatrix(true);
  20698. var min;
  20699. var max;
  20700. var boundingInfo = this.getBoundingInfo();
  20701. if (!this.subMeshes) {
  20702. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20703. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20704. }
  20705. else {
  20706. min = boundingInfo.boundingBox.minimumWorld;
  20707. max = boundingInfo.boundingBox.maximumWorld;
  20708. }
  20709. if (includeDescendants) {
  20710. var descendants = this.getDescendants(false);
  20711. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20712. var descendant = descendants_1[_i];
  20713. var childMesh = descendant;
  20714. childMesh.computeWorldMatrix(true);
  20715. // Filters meshes based on custom predicate function.
  20716. if (predicate && !predicate(childMesh)) {
  20717. continue;
  20718. }
  20719. //make sure we have the needed params to get mix and max
  20720. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20721. continue;
  20722. }
  20723. var childBoundingInfo = childMesh.getBoundingInfo();
  20724. var boundingBox = childBoundingInfo.boundingBox;
  20725. var minBox = boundingBox.minimumWorld;
  20726. var maxBox = boundingBox.maximumWorld;
  20727. BABYLON.Tools.CheckExtends(minBox, min, max);
  20728. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20729. }
  20730. }
  20731. return {
  20732. min: min,
  20733. max: max
  20734. };
  20735. };
  20736. /** @hidden */
  20737. AbstractMesh.prototype._updateBoundingInfo = function () {
  20738. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20739. this._boundingInfo.update(this.worldMatrixFromCache);
  20740. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20741. return this;
  20742. };
  20743. /** @hidden */
  20744. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20745. if (!this.subMeshes) {
  20746. return this;
  20747. }
  20748. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20749. var subMesh = this.subMeshes[subIndex];
  20750. if (!subMesh.IsGlobal) {
  20751. subMesh.updateBoundingInfo(matrix);
  20752. }
  20753. }
  20754. return this;
  20755. };
  20756. /** @hidden */
  20757. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20758. // Bounding info
  20759. this._updateBoundingInfo();
  20760. };
  20761. /**
  20762. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20763. * A mesh is in the frustum if its bounding box intersects the frustum
  20764. * @param frustumPlanes defines the frustum to test
  20765. * @returns true if the mesh is in the frustum planes
  20766. */
  20767. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20768. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20769. };
  20770. /**
  20771. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20772. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20773. * @param frustumPlanes defines the frustum to test
  20774. * @returns true if the mesh is completely in the frustum planes
  20775. */
  20776. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20777. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20778. };
  20779. /**
  20780. * True if the mesh intersects another mesh or a SolidParticle object
  20781. * @param mesh defines a target mesh or SolidParticle to test
  20782. * @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)
  20783. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20784. * @returns true if there is an intersection
  20785. */
  20786. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20787. if (precise === void 0) { precise = false; }
  20788. if (!this._boundingInfo || !mesh._boundingInfo) {
  20789. return false;
  20790. }
  20791. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20792. return true;
  20793. }
  20794. if (includeDescendants) {
  20795. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20796. var child = _a[_i];
  20797. if (child.intersectsMesh(mesh, precise, true)) {
  20798. return true;
  20799. }
  20800. }
  20801. }
  20802. return false;
  20803. };
  20804. /**
  20805. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20806. * @param point defines the point to test
  20807. * @returns true if there is an intersection
  20808. */
  20809. AbstractMesh.prototype.intersectsPoint = function (point) {
  20810. if (!this._boundingInfo) {
  20811. return false;
  20812. }
  20813. return this._boundingInfo.intersectsPoint(point);
  20814. };
  20815. /**
  20816. * Gets the position of the current mesh in camera space
  20817. * @param camera defines the camera to use
  20818. * @returns a position
  20819. */
  20820. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20821. if (camera === void 0) { camera = null; }
  20822. if (!camera) {
  20823. camera = this.getScene().activeCamera;
  20824. }
  20825. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20826. };
  20827. /**
  20828. * Returns the distance from the mesh to the active camera
  20829. * @param camera defines the camera to use
  20830. * @returns the distance
  20831. */
  20832. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20833. if (camera === void 0) { camera = null; }
  20834. if (!camera) {
  20835. camera = this.getScene().activeCamera;
  20836. }
  20837. return this.absolutePosition.subtract(camera.position).length();
  20838. };
  20839. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20840. // Collisions
  20841. /**
  20842. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20843. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20844. */
  20845. get: function () {
  20846. return this._checkCollisions;
  20847. },
  20848. set: function (collisionEnabled) {
  20849. this._checkCollisions = collisionEnabled;
  20850. if (this.getScene().workerCollisions) {
  20851. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20852. }
  20853. },
  20854. enumerable: true,
  20855. configurable: true
  20856. });
  20857. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20858. /**
  20859. * Gets Collider object used to compute collisions (not physics)
  20860. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20861. */
  20862. get: function () {
  20863. return this._collider;
  20864. },
  20865. enumerable: true,
  20866. configurable: true
  20867. });
  20868. /**
  20869. * Move the mesh using collision engine
  20870. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20871. * @param displacement defines the requested displacement vector
  20872. * @returns the current mesh
  20873. */
  20874. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20875. var globalPosition = this.getAbsolutePosition();
  20876. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20877. if (!this._collider) {
  20878. this._collider = new BABYLON.Collider();
  20879. }
  20880. this._collider._radius = this.ellipsoid;
  20881. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20882. return this;
  20883. };
  20884. // Collisions
  20885. /** @hidden */
  20886. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20887. this._generatePointsArray();
  20888. if (!this._positions) {
  20889. return this;
  20890. }
  20891. // Transformation
  20892. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20893. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20894. subMesh._lastColliderWorldVertices = [];
  20895. subMesh._trianglePlanes = [];
  20896. var start = subMesh.verticesStart;
  20897. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20898. for (var i = start; i < end; i++) {
  20899. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20900. }
  20901. }
  20902. // Collide
  20903. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20904. if (collider.collisionFound) {
  20905. collider.collidedMesh = this;
  20906. }
  20907. return this;
  20908. };
  20909. /** @hidden */
  20910. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20911. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20912. var len = subMeshes.length;
  20913. for (var index = 0; index < len; index++) {
  20914. var subMesh = subMeshes.data[index];
  20915. // Bounding test
  20916. if (len > 1 && !subMesh._checkCollision(collider))
  20917. continue;
  20918. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20919. }
  20920. return this;
  20921. };
  20922. /** @hidden */
  20923. AbstractMesh.prototype._checkCollision = function (collider) {
  20924. // Bounding box test
  20925. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20926. return this;
  20927. // Transformation matrix
  20928. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20929. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20930. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20931. return this;
  20932. };
  20933. // Picking
  20934. /** @hidden */
  20935. AbstractMesh.prototype._generatePointsArray = function () {
  20936. return false;
  20937. };
  20938. /**
  20939. * Checks if the passed Ray intersects with the mesh
  20940. * @param ray defines the ray to use
  20941. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20942. * @returns the picking info
  20943. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20944. */
  20945. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20946. var pickingInfo = new BABYLON.PickingInfo();
  20947. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20948. return pickingInfo;
  20949. }
  20950. if (!this._generatePointsArray()) {
  20951. return pickingInfo;
  20952. }
  20953. var intersectInfo = null;
  20954. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  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.canIntersects(ray))
  20960. continue;
  20961. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20962. if (currentIntersectInfo) {
  20963. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20964. intersectInfo = currentIntersectInfo;
  20965. intersectInfo.subMeshId = index;
  20966. if (fastCheck) {
  20967. break;
  20968. }
  20969. }
  20970. }
  20971. }
  20972. if (intersectInfo) {
  20973. // Get picked point
  20974. var world = this.getWorldMatrix();
  20975. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20976. var direction = ray.direction.clone();
  20977. direction = direction.scale(intersectInfo.distance);
  20978. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20979. var pickedPoint = worldOrigin.add(worldDirection);
  20980. // Return result
  20981. pickingInfo.hit = true;
  20982. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20983. pickingInfo.pickedPoint = pickedPoint;
  20984. pickingInfo.pickedMesh = this;
  20985. pickingInfo.bu = intersectInfo.bu || 0;
  20986. pickingInfo.bv = intersectInfo.bv || 0;
  20987. pickingInfo.faceId = intersectInfo.faceId;
  20988. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20989. return pickingInfo;
  20990. }
  20991. return pickingInfo;
  20992. };
  20993. /**
  20994. * Clones the current mesh
  20995. * @param name defines the mesh name
  20996. * @param newParent defines the new mesh parent
  20997. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20998. * @returns the new mesh
  20999. */
  21000. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21001. return null;
  21002. };
  21003. /**
  21004. * Disposes all the submeshes of the current meshnp
  21005. * @returns the current mesh
  21006. */
  21007. AbstractMesh.prototype.releaseSubMeshes = function () {
  21008. if (this.subMeshes) {
  21009. while (this.subMeshes.length) {
  21010. this.subMeshes[0].dispose();
  21011. }
  21012. }
  21013. else {
  21014. this.subMeshes = new Array();
  21015. }
  21016. return this;
  21017. };
  21018. /**
  21019. * Releases resources associated with this abstract mesh.
  21020. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21021. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21022. */
  21023. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21024. var _this = this;
  21025. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21026. var index;
  21027. // Smart Array Retainers.
  21028. this.getScene().freeActiveMeshes();
  21029. this.getScene().freeRenderingGroups();
  21030. // Action manager
  21031. if (this.actionManager !== undefined && this.actionManager !== null) {
  21032. this.actionManager.dispose();
  21033. this.actionManager = null;
  21034. }
  21035. // Skeleton
  21036. this._skeleton = null;
  21037. // Intersections in progress
  21038. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21039. var other = this._intersectionsInProgress[index];
  21040. var pos = other._intersectionsInProgress.indexOf(this);
  21041. other._intersectionsInProgress.splice(pos, 1);
  21042. }
  21043. this._intersectionsInProgress = [];
  21044. // Lights
  21045. var lights = this.getScene().lights;
  21046. lights.forEach(function (light) {
  21047. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21048. if (meshIndex !== -1) {
  21049. light.includedOnlyMeshes.splice(meshIndex, 1);
  21050. }
  21051. meshIndex = light.excludedMeshes.indexOf(_this);
  21052. if (meshIndex !== -1) {
  21053. light.excludedMeshes.splice(meshIndex, 1);
  21054. }
  21055. // Shadow generators
  21056. var generator = light.getShadowGenerator();
  21057. if (generator) {
  21058. var shadowMap = generator.getShadowMap();
  21059. if (shadowMap && shadowMap.renderList) {
  21060. meshIndex = shadowMap.renderList.indexOf(_this);
  21061. if (meshIndex !== -1) {
  21062. shadowMap.renderList.splice(meshIndex, 1);
  21063. }
  21064. }
  21065. }
  21066. });
  21067. // SubMeshes
  21068. if (this.getClassName() !== "InstancedMesh") {
  21069. this.releaseSubMeshes();
  21070. }
  21071. // Query
  21072. var engine = this.getScene().getEngine();
  21073. if (this._occlusionQuery) {
  21074. this._isOcclusionQueryInProgress = false;
  21075. engine.deleteQuery(this._occlusionQuery);
  21076. this._occlusionQuery = null;
  21077. }
  21078. // Engine
  21079. engine.wipeCaches();
  21080. // Remove from scene
  21081. this.getScene().removeMesh(this);
  21082. if (disposeMaterialAndTextures) {
  21083. if (this.material) {
  21084. this.material.dispose(false, true);
  21085. }
  21086. }
  21087. if (!doNotRecurse) {
  21088. // Particles
  21089. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21090. if (this.getScene().particleSystems[index].emitter === this) {
  21091. this.getScene().particleSystems[index].dispose();
  21092. index--;
  21093. }
  21094. }
  21095. }
  21096. // facet data
  21097. if (this._facetDataEnabled) {
  21098. this.disableFacetData();
  21099. }
  21100. this.onAfterWorldMatrixUpdateObservable.clear();
  21101. this.onCollideObservable.clear();
  21102. this.onCollisionPositionChangeObservable.clear();
  21103. this.onRebuildObservable.clear();
  21104. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21105. };
  21106. /**
  21107. * Adds the passed mesh as a child to the current mesh
  21108. * @param mesh defines the child mesh
  21109. * @returns the current mesh
  21110. */
  21111. AbstractMesh.prototype.addChild = function (mesh) {
  21112. mesh.setParent(this);
  21113. return this;
  21114. };
  21115. /**
  21116. * Removes the passed mesh from the current mesh children list
  21117. * @param mesh defines the child mesh
  21118. * @returns the current mesh
  21119. */
  21120. AbstractMesh.prototype.removeChild = function (mesh) {
  21121. mesh.setParent(null);
  21122. return this;
  21123. };
  21124. // Facet data
  21125. /** @hidden */
  21126. AbstractMesh.prototype._initFacetData = function () {
  21127. if (!this._facetNormals) {
  21128. this._facetNormals = new Array();
  21129. }
  21130. if (!this._facetPositions) {
  21131. this._facetPositions = new Array();
  21132. }
  21133. if (!this._facetPartitioning) {
  21134. this._facetPartitioning = new Array();
  21135. }
  21136. this._facetNb = (this.getIndices().length / 3) | 0;
  21137. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21138. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21139. for (var f = 0; f < this._facetNb; f++) {
  21140. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21141. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21142. }
  21143. this._facetDataEnabled = true;
  21144. return this;
  21145. };
  21146. /**
  21147. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21148. * This method can be called within the render loop.
  21149. * 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
  21150. * @returns the current mesh
  21151. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21152. */
  21153. AbstractMesh.prototype.updateFacetData = function () {
  21154. if (!this._facetDataEnabled) {
  21155. this._initFacetData();
  21156. }
  21157. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21158. var indices = this.getIndices();
  21159. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21160. var bInfo = this.getBoundingInfo();
  21161. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21162. // init arrays, matrix and sort function on first call
  21163. this._facetDepthSortEnabled = true;
  21164. if (indices instanceof Uint16Array) {
  21165. this._depthSortedIndices = new Uint16Array(indices);
  21166. }
  21167. else if (indices instanceof Uint32Array) {
  21168. this._depthSortedIndices = new Uint32Array(indices);
  21169. }
  21170. else {
  21171. var needs32bits = false;
  21172. for (var i = 0; i < indices.length; i++) {
  21173. if (indices[i] > 65535) {
  21174. needs32bits = true;
  21175. break;
  21176. }
  21177. }
  21178. if (needs32bits) {
  21179. this._depthSortedIndices = new Uint32Array(indices);
  21180. }
  21181. else {
  21182. this._depthSortedIndices = new Uint16Array(indices);
  21183. }
  21184. }
  21185. this._facetDepthSortFunction = function (f1, f2) {
  21186. return (f2.sqDistance - f1.sqDistance);
  21187. };
  21188. if (!this._facetDepthSortFrom) {
  21189. var camera = this.getScene().activeCamera;
  21190. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21191. }
  21192. this._depthSortedFacets = [];
  21193. for (var f = 0; f < this._facetNb; f++) {
  21194. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21195. this._depthSortedFacets.push(depthSortedFacet);
  21196. }
  21197. this._invertedMatrix = BABYLON.Matrix.Identity();
  21198. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21199. }
  21200. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21201. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21202. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21203. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21204. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21205. this._subDiv.max = this._partitioningSubdivisions;
  21206. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21207. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21208. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21209. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21210. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21211. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21212. // set the parameters for ComputeNormals()
  21213. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21214. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21215. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21216. this._facetParameters.bInfo = bInfo;
  21217. this._facetParameters.bbSize = this._bbSize;
  21218. this._facetParameters.subDiv = this._subDiv;
  21219. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21220. this._facetParameters.depthSort = this._facetDepthSort;
  21221. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21222. this.computeWorldMatrix(true);
  21223. this._worldMatrix.invertToRef(this._invertedMatrix);
  21224. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21225. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21226. }
  21227. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21228. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21229. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21230. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21231. var l = (this._depthSortedIndices.length / 3) | 0;
  21232. for (var f = 0; f < l; f++) {
  21233. var sind = this._depthSortedFacets[f].ind;
  21234. this._depthSortedIndices[f * 3] = indices[sind];
  21235. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21236. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21237. }
  21238. this.updateIndices(this._depthSortedIndices);
  21239. }
  21240. return this;
  21241. };
  21242. /**
  21243. * Returns the facetLocalNormals array.
  21244. * The normals are expressed in the mesh local spac
  21245. * @returns an array of Vector3
  21246. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21247. */
  21248. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21249. if (!this._facetNormals) {
  21250. this.updateFacetData();
  21251. }
  21252. return this._facetNormals;
  21253. };
  21254. /**
  21255. * Returns the facetLocalPositions array.
  21256. * The facet positions are expressed in the mesh local space
  21257. * @returns an array of Vector3
  21258. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21259. */
  21260. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21261. if (!this._facetPositions) {
  21262. this.updateFacetData();
  21263. }
  21264. return this._facetPositions;
  21265. };
  21266. /**
  21267. * Returns the facetLocalPartioning array
  21268. * @returns an array of array of numbers
  21269. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21270. */
  21271. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21272. if (!this._facetPartitioning) {
  21273. this.updateFacetData();
  21274. }
  21275. return this._facetPartitioning;
  21276. };
  21277. /**
  21278. * Returns the i-th facet position in the world system.
  21279. * This method allocates a new Vector3 per call
  21280. * @param i defines the facet index
  21281. * @returns a new Vector3
  21282. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21283. */
  21284. AbstractMesh.prototype.getFacetPosition = function (i) {
  21285. var pos = BABYLON.Vector3.Zero();
  21286. this.getFacetPositionToRef(i, pos);
  21287. return pos;
  21288. };
  21289. /**
  21290. * Sets the reference Vector3 with the i-th facet position in the world system
  21291. * @param i defines the facet index
  21292. * @param ref defines the target vector
  21293. * @returns the current mesh
  21294. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21295. */
  21296. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21297. var localPos = (this.getFacetLocalPositions())[i];
  21298. var world = this.getWorldMatrix();
  21299. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21300. return this;
  21301. };
  21302. /**
  21303. * Returns the i-th facet normal in the world system.
  21304. * This method allocates a new Vector3 per call
  21305. * @param i defines the facet index
  21306. * @returns a new Vector3
  21307. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21308. */
  21309. AbstractMesh.prototype.getFacetNormal = function (i) {
  21310. var norm = BABYLON.Vector3.Zero();
  21311. this.getFacetNormalToRef(i, norm);
  21312. return norm;
  21313. };
  21314. /**
  21315. * Sets the reference Vector3 with the i-th facet normal in the world system
  21316. * @param i defines the facet index
  21317. * @param ref defines the target vector
  21318. * @returns the current mesh
  21319. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21320. */
  21321. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21322. var localNorm = (this.getFacetLocalNormals())[i];
  21323. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21324. return this;
  21325. };
  21326. /**
  21327. * 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)
  21328. * @param x defines x coordinate
  21329. * @param y defines y coordinate
  21330. * @param z defines z coordinate
  21331. * @returns the array of facet indexes
  21332. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21333. */
  21334. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21335. var bInfo = this.getBoundingInfo();
  21336. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21337. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21338. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21339. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21340. return null;
  21341. }
  21342. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21343. };
  21344. /**
  21345. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21346. * @param projected sets as the (x,y,z) world projection on the facet
  21347. * @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
  21348. * @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
  21349. * @param x defines x coordinate
  21350. * @param y defines y coordinate
  21351. * @param z defines z coordinate
  21352. * @returns the face index if found (or null instead)
  21353. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21354. */
  21355. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21356. if (checkFace === void 0) { checkFace = false; }
  21357. if (facing === void 0) { facing = true; }
  21358. var world = this.getWorldMatrix();
  21359. var invMat = BABYLON.Tmp.Matrix[5];
  21360. world.invertToRef(invMat);
  21361. var invVect = BABYLON.Tmp.Vector3[8];
  21362. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21363. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21364. if (projected) {
  21365. // tranform the local computed projected vector to world coordinates
  21366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21367. }
  21368. return closest;
  21369. };
  21370. /**
  21371. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21372. * @param projected sets as the (x,y,z) local projection on the facet
  21373. * @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
  21374. * @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
  21375. * @param x defines x coordinate
  21376. * @param y defines y coordinate
  21377. * @param z defines z coordinate
  21378. * @returns the face index if found (or null instead)
  21379. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21380. */
  21381. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21382. if (checkFace === void 0) { checkFace = false; }
  21383. if (facing === void 0) { facing = true; }
  21384. var closest = null;
  21385. var tmpx = 0.0;
  21386. var tmpy = 0.0;
  21387. var tmpz = 0.0;
  21388. var d = 0.0; // tmp dot facet normal * facet position
  21389. var t0 = 0.0;
  21390. var projx = 0.0;
  21391. var projy = 0.0;
  21392. var projz = 0.0;
  21393. // Get all the facets in the same partitioning block than (x, y, z)
  21394. var facetPositions = this.getFacetLocalPositions();
  21395. var facetNormals = this.getFacetLocalNormals();
  21396. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21397. if (!facetsInBlock) {
  21398. return null;
  21399. }
  21400. // Get the closest facet to (x, y, z)
  21401. var shortest = Number.MAX_VALUE; // init distance vars
  21402. var tmpDistance = shortest;
  21403. var fib; // current facet in the block
  21404. var norm; // current facet normal
  21405. var p0; // current facet barycenter position
  21406. // loop on all the facets in the current partitioning block
  21407. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21408. fib = facetsInBlock[idx];
  21409. norm = facetNormals[fib];
  21410. p0 = facetPositions[fib];
  21411. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21412. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21413. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21414. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21415. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21416. projx = x + norm.x * t0;
  21417. projy = y + norm.y * t0;
  21418. projz = z + norm.z * t0;
  21419. tmpx = projx - x;
  21420. tmpy = projy - y;
  21421. tmpz = projz - z;
  21422. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21423. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21424. shortest = tmpDistance;
  21425. closest = fib;
  21426. if (projected) {
  21427. projected.x = projx;
  21428. projected.y = projy;
  21429. projected.z = projz;
  21430. }
  21431. }
  21432. }
  21433. }
  21434. return closest;
  21435. };
  21436. /**
  21437. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21438. * @returns the parameters
  21439. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21440. */
  21441. AbstractMesh.prototype.getFacetDataParameters = function () {
  21442. return this._facetParameters;
  21443. };
  21444. /**
  21445. * Disables the feature FacetData and frees the related memory
  21446. * @returns the current mesh
  21447. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21448. */
  21449. AbstractMesh.prototype.disableFacetData = function () {
  21450. if (this._facetDataEnabled) {
  21451. this._facetDataEnabled = false;
  21452. this._facetPositions = new Array();
  21453. this._facetNormals = new Array();
  21454. this._facetPartitioning = new Array();
  21455. this._facetParameters = null;
  21456. this._depthSortedIndices = new Uint32Array(0);
  21457. }
  21458. return this;
  21459. };
  21460. /**
  21461. * Updates the AbstractMesh indices array
  21462. * @param indices defines the data source
  21463. * @returns the current mesh
  21464. */
  21465. AbstractMesh.prototype.updateIndices = function (indices) {
  21466. return this;
  21467. };
  21468. /**
  21469. * Creates new normals data for the mesh
  21470. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21471. * @returns the current mesh
  21472. */
  21473. AbstractMesh.prototype.createNormals = function (updatable) {
  21474. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21475. var indices = this.getIndices();
  21476. var normals;
  21477. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21478. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21479. }
  21480. else {
  21481. normals = [];
  21482. }
  21483. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21484. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21485. return this;
  21486. };
  21487. /**
  21488. * Align the mesh with a normal
  21489. * @param normal defines the normal to use
  21490. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21491. * @returns the current mesh
  21492. */
  21493. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21494. if (!upDirection) {
  21495. upDirection = BABYLON.Axis.Y;
  21496. }
  21497. var axisX = BABYLON.Tmp.Vector3[0];
  21498. var axisZ = BABYLON.Tmp.Vector3[1];
  21499. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21500. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21501. if (this.rotationQuaternion) {
  21502. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21503. }
  21504. else {
  21505. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21506. }
  21507. return this;
  21508. };
  21509. /** @hidden */
  21510. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21511. this._isOccluded = false;
  21512. };
  21513. /** No occlusion */
  21514. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21515. /** Occlusion set to optimisitic */
  21516. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21517. /** Occlusion set to strict */
  21518. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21519. /** Use an accurante occlusion algorithm */
  21520. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21521. /** Use a conservative occlusion algorithm */
  21522. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21523. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21524. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21525. /** Culling strategy with bounding sphere only and then frustum culling */
  21526. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21527. return AbstractMesh;
  21528. }(BABYLON.TransformNode));
  21529. BABYLON.AbstractMesh = AbstractMesh;
  21530. })(BABYLON || (BABYLON = {}));
  21531. //# sourceMappingURL=babylon.abstractMesh.js.map
  21532. var BABYLON;
  21533. (function (BABYLON) {
  21534. /**
  21535. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21536. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21537. * 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.
  21538. */
  21539. var Light = /** @class */ (function (_super) {
  21540. __extends(Light, _super);
  21541. /**
  21542. * Creates a Light object in the scene.
  21543. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21544. * @param name The firendly name of the light
  21545. * @param scene The scene the light belongs too
  21546. */
  21547. function Light(name, scene) {
  21548. var _this = _super.call(this, name, scene) || this;
  21549. /**
  21550. * Diffuse gives the basic color to an object.
  21551. */
  21552. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21553. /**
  21554. * Specular produces a highlight color on an object.
  21555. * Note: This is note affecting PBR materials.
  21556. */
  21557. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21558. /**
  21559. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21560. * falling off base on range or angle.
  21561. * This can be set to any values in Light.FALLOFF_x.
  21562. *
  21563. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21564. * other types of materials.
  21565. */
  21566. _this.falloffType = Light.FALLOFF_DEFAULT;
  21567. /**
  21568. * Strength of the light.
  21569. * Note: By default it is define in the framework own unit.
  21570. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21571. */
  21572. _this.intensity = 1.0;
  21573. _this._range = Number.MAX_VALUE;
  21574. _this._inverseSquaredRange = 0;
  21575. /**
  21576. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21577. * of light.
  21578. */
  21579. _this._photometricScale = 1.0;
  21580. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21581. _this._radius = 0.00001;
  21582. /**
  21583. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21584. * exceeding the number allowed of the materials.
  21585. */
  21586. _this.renderPriority = 0;
  21587. _this._shadowEnabled = true;
  21588. _this._excludeWithLayerMask = 0;
  21589. _this._includeOnlyWithLayerMask = 0;
  21590. _this._lightmapMode = 0;
  21591. /**
  21592. * @hidden Internal use only.
  21593. */
  21594. _this._excludedMeshesIds = new Array();
  21595. /**
  21596. * @hidden Internal use only.
  21597. */
  21598. _this._includedOnlyMeshesIds = new Array();
  21599. _this.getScene().addLight(_this);
  21600. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21601. _this._buildUniformLayout();
  21602. _this.includedOnlyMeshes = new Array();
  21603. _this.excludedMeshes = new Array();
  21604. _this._resyncMeshes();
  21605. return _this;
  21606. }
  21607. Object.defineProperty(Light.prototype, "range", {
  21608. /**
  21609. * Defines how far from the source the light is impacting in scene units.
  21610. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21611. */
  21612. get: function () {
  21613. return this._range;
  21614. },
  21615. /**
  21616. * Defines how far from the source the light is impacting in scene units.
  21617. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21618. */
  21619. set: function (value) {
  21620. this._range = value;
  21621. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light.prototype, "intensityMode", {
  21627. /**
  21628. * Gets the photometric scale used to interpret the intensity.
  21629. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21630. */
  21631. get: function () {
  21632. return this._intensityMode;
  21633. },
  21634. /**
  21635. * Sets the photometric scale used to interpret the intensity.
  21636. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21637. */
  21638. set: function (value) {
  21639. this._intensityMode = value;
  21640. this._computePhotometricScale();
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. ;
  21646. ;
  21647. Object.defineProperty(Light.prototype, "radius", {
  21648. /**
  21649. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21650. */
  21651. get: function () {
  21652. return this._radius;
  21653. },
  21654. /**
  21655. * sets the light radius used by PBR Materials to simulate soft area lights.
  21656. */
  21657. set: function (value) {
  21658. this._radius = value;
  21659. this._computePhotometricScale();
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. ;
  21665. ;
  21666. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21667. /**
  21668. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21669. * the current shadow generator.
  21670. */
  21671. get: function () {
  21672. return this._shadowEnabled;
  21673. },
  21674. /**
  21675. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21676. * the current shadow generator.
  21677. */
  21678. set: function (value) {
  21679. if (this._shadowEnabled === value) {
  21680. return;
  21681. }
  21682. this._shadowEnabled = value;
  21683. this._markMeshesAsLightDirty();
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21689. /**
  21690. * Gets the only meshes impacted by this light.
  21691. */
  21692. get: function () {
  21693. return this._includedOnlyMeshes;
  21694. },
  21695. /**
  21696. * Sets the only meshes impacted by this light.
  21697. */
  21698. set: function (value) {
  21699. this._includedOnlyMeshes = value;
  21700. this._hookArrayForIncludedOnly(value);
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21706. /**
  21707. * Gets the meshes not impacted by this light.
  21708. */
  21709. get: function () {
  21710. return this._excludedMeshes;
  21711. },
  21712. /**
  21713. * Sets the meshes not impacted by this light.
  21714. */
  21715. set: function (value) {
  21716. this._excludedMeshes = value;
  21717. this._hookArrayForExcluded(value);
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21723. /**
  21724. * Gets the layer id use to find what meshes are not impacted by the light.
  21725. * Inactive if 0
  21726. */
  21727. get: function () {
  21728. return this._excludeWithLayerMask;
  21729. },
  21730. /**
  21731. * Sets the layer id use to find what meshes are not impacted by the light.
  21732. * Inactive if 0
  21733. */
  21734. set: function (value) {
  21735. this._excludeWithLayerMask = value;
  21736. this._resyncMeshes();
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21742. /**
  21743. * Gets the layer id use to find what meshes are impacted by the light.
  21744. * Inactive if 0
  21745. */
  21746. get: function () {
  21747. return this._includeOnlyWithLayerMask;
  21748. },
  21749. /**
  21750. * Sets the layer id use to find what meshes are impacted by the light.
  21751. * Inactive if 0
  21752. */
  21753. set: function (value) {
  21754. this._includeOnlyWithLayerMask = value;
  21755. this._resyncMeshes();
  21756. },
  21757. enumerable: true,
  21758. configurable: true
  21759. });
  21760. Object.defineProperty(Light.prototype, "lightmapMode", {
  21761. /**
  21762. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21763. */
  21764. get: function () {
  21765. return this._lightmapMode;
  21766. },
  21767. /**
  21768. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21769. */
  21770. set: function (value) {
  21771. if (this._lightmapMode === value) {
  21772. return;
  21773. }
  21774. this._lightmapMode = value;
  21775. this._markMeshesAsLightDirty();
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. /**
  21781. * Returns the string "Light".
  21782. * @returns the class name
  21783. */
  21784. Light.prototype.getClassName = function () {
  21785. return "Light";
  21786. };
  21787. /**
  21788. * Converts the light information to a readable string for debug purpose.
  21789. * @param fullDetails Supports for multiple levels of logging within scene loading
  21790. * @returns the human readable light info
  21791. */
  21792. Light.prototype.toString = function (fullDetails) {
  21793. var ret = "Name: " + this.name;
  21794. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21795. if (this.animations) {
  21796. for (var i = 0; i < this.animations.length; i++) {
  21797. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21798. }
  21799. }
  21800. if (fullDetails) {
  21801. }
  21802. return ret;
  21803. };
  21804. /** @hidden */
  21805. Light.prototype._syncParentEnabledState = function () {
  21806. _super.prototype._syncParentEnabledState.call(this);
  21807. this._resyncMeshes();
  21808. };
  21809. /**
  21810. * Set the enabled state of this node.
  21811. * @param value - the new enabled state
  21812. */
  21813. Light.prototype.setEnabled = function (value) {
  21814. _super.prototype.setEnabled.call(this, value);
  21815. this._resyncMeshes();
  21816. };
  21817. /**
  21818. * Returns the Light associated shadow generator if any.
  21819. * @return the associated shadow generator.
  21820. */
  21821. Light.prototype.getShadowGenerator = function () {
  21822. return this._shadowGenerator;
  21823. };
  21824. /**
  21825. * Returns a Vector3, the absolute light position in the World.
  21826. * @returns the world space position of the light
  21827. */
  21828. Light.prototype.getAbsolutePosition = function () {
  21829. return BABYLON.Vector3.Zero();
  21830. };
  21831. /**
  21832. * Specifies if the light will affect the passed mesh.
  21833. * @param mesh The mesh to test against the light
  21834. * @return true the mesh is affected otherwise, false.
  21835. */
  21836. Light.prototype.canAffectMesh = function (mesh) {
  21837. if (!mesh) {
  21838. return true;
  21839. }
  21840. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21841. return false;
  21842. }
  21843. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21844. return false;
  21845. }
  21846. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21847. return false;
  21848. }
  21849. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21850. return false;
  21851. }
  21852. return true;
  21853. };
  21854. /**
  21855. * Sort function to order lights for rendering.
  21856. * @param a First Light object to compare to second.
  21857. * @param b Second Light object to compare first.
  21858. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21859. */
  21860. Light.CompareLightsPriority = function (a, b) {
  21861. //shadow-casting lights have priority over non-shadow-casting lights
  21862. //the renderPrioirty is a secondary sort criterion
  21863. if (a.shadowEnabled !== b.shadowEnabled) {
  21864. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21865. }
  21866. return b.renderPriority - a.renderPriority;
  21867. };
  21868. /**
  21869. * Releases resources associated with this node.
  21870. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21871. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21872. */
  21873. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21874. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21875. if (this._shadowGenerator) {
  21876. this._shadowGenerator.dispose();
  21877. this._shadowGenerator = null;
  21878. }
  21879. // Animations
  21880. this.getScene().stopAnimation(this);
  21881. // Remove from meshes
  21882. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21883. var mesh = _a[_i];
  21884. mesh._removeLightSource(this);
  21885. }
  21886. this._uniformBuffer.dispose();
  21887. // Remove from scene
  21888. this.getScene().removeLight(this);
  21889. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21890. };
  21891. /**
  21892. * Returns the light type ID (integer).
  21893. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21894. */
  21895. Light.prototype.getTypeID = function () {
  21896. return 0;
  21897. };
  21898. /**
  21899. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21900. * @returns the scaled intensity in intensity mode unit
  21901. */
  21902. Light.prototype.getScaledIntensity = function () {
  21903. return this._photometricScale * this.intensity;
  21904. };
  21905. /**
  21906. * Returns a new Light object, named "name", from the current one.
  21907. * @param name The name of the cloned light
  21908. * @returns the new created light
  21909. */
  21910. Light.prototype.clone = function (name) {
  21911. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21912. if (!constructor) {
  21913. return null;
  21914. }
  21915. return BABYLON.SerializationHelper.Clone(constructor, this);
  21916. };
  21917. /**
  21918. * Serializes the current light into a Serialization object.
  21919. * @returns the serialized object.
  21920. */
  21921. Light.prototype.serialize = function () {
  21922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21923. // Type
  21924. serializationObject.type = this.getTypeID();
  21925. // Parent
  21926. if (this.parent) {
  21927. serializationObject.parentId = this.parent.id;
  21928. }
  21929. // Inclusion / exclusions
  21930. if (this.excludedMeshes.length > 0) {
  21931. serializationObject.excludedMeshesIds = [];
  21932. this.excludedMeshes.forEach(function (mesh) {
  21933. serializationObject.excludedMeshesIds.push(mesh.id);
  21934. });
  21935. }
  21936. if (this.includedOnlyMeshes.length > 0) {
  21937. serializationObject.includedOnlyMeshesIds = [];
  21938. this.includedOnlyMeshes.forEach(function (mesh) {
  21939. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21940. });
  21941. }
  21942. // Animations
  21943. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21944. serializationObject.ranges = this.serializeAnimationRanges();
  21945. return serializationObject;
  21946. };
  21947. /**
  21948. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21949. * This new light is named "name" and added to the passed scene.
  21950. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21951. * @param name The friendly name of the light
  21952. * @param scene The scene the new light will belong to
  21953. * @returns the constructor function
  21954. */
  21955. Light.GetConstructorFromName = function (type, name, scene) {
  21956. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21957. if (constructorFunc) {
  21958. return constructorFunc;
  21959. }
  21960. // Default to no light for none present once.
  21961. return null;
  21962. };
  21963. /**
  21964. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21965. * @param parsedLight The JSON representation of the light
  21966. * @param scene The scene to create the parsed light in
  21967. * @returns the created light after parsing
  21968. */
  21969. Light.Parse = function (parsedLight, scene) {
  21970. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21971. if (!constructor) {
  21972. return null;
  21973. }
  21974. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21975. // Inclusion / exclusions
  21976. if (parsedLight.excludedMeshesIds) {
  21977. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21978. }
  21979. if (parsedLight.includedOnlyMeshesIds) {
  21980. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21981. }
  21982. // Parent
  21983. if (parsedLight.parentId) {
  21984. light._waitingParentId = parsedLight.parentId;
  21985. }
  21986. // Animations
  21987. if (parsedLight.animations) {
  21988. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21989. var parsedAnimation = parsedLight.animations[animationIndex];
  21990. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21991. }
  21992. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21993. }
  21994. if (parsedLight.autoAnimate) {
  21995. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21996. }
  21997. return light;
  21998. };
  21999. Light.prototype._hookArrayForExcluded = function (array) {
  22000. var _this = this;
  22001. var oldPush = array.push;
  22002. array.push = function () {
  22003. var items = [];
  22004. for (var _i = 0; _i < arguments.length; _i++) {
  22005. items[_i] = arguments[_i];
  22006. }
  22007. var result = oldPush.apply(array, items);
  22008. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22009. var item = items_1[_a];
  22010. item._resyncLighSource(_this);
  22011. }
  22012. return result;
  22013. };
  22014. var oldSplice = array.splice;
  22015. array.splice = function (index, deleteCount) {
  22016. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22017. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22018. var item = deleted_1[_i];
  22019. item._resyncLighSource(_this);
  22020. }
  22021. return deleted;
  22022. };
  22023. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22024. var item = array_1[_i];
  22025. item._resyncLighSource(this);
  22026. }
  22027. };
  22028. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22029. var _this = this;
  22030. var oldPush = array.push;
  22031. array.push = function () {
  22032. var items = [];
  22033. for (var _i = 0; _i < arguments.length; _i++) {
  22034. items[_i] = arguments[_i];
  22035. }
  22036. var result = oldPush.apply(array, items);
  22037. _this._resyncMeshes();
  22038. return result;
  22039. };
  22040. var oldSplice = array.splice;
  22041. array.splice = function (index, deleteCount) {
  22042. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22043. _this._resyncMeshes();
  22044. return deleted;
  22045. };
  22046. this._resyncMeshes();
  22047. };
  22048. Light.prototype._resyncMeshes = function () {
  22049. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22050. var mesh = _a[_i];
  22051. mesh._resyncLighSource(this);
  22052. }
  22053. };
  22054. /**
  22055. * Forces the meshes to update their light related information in their rendering used effects
  22056. * @hidden Internal Use Only
  22057. */
  22058. Light.prototype._markMeshesAsLightDirty = function () {
  22059. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22060. var mesh = _a[_i];
  22061. if (mesh._lightSources.indexOf(this) !== -1) {
  22062. mesh._markSubMeshesAsLightDirty();
  22063. }
  22064. }
  22065. };
  22066. /**
  22067. * Recomputes the cached photometric scale if needed.
  22068. */
  22069. Light.prototype._computePhotometricScale = function () {
  22070. this._photometricScale = this._getPhotometricScale();
  22071. this.getScene().resetCachedMaterial();
  22072. };
  22073. /**
  22074. * Returns the Photometric Scale according to the light type and intensity mode.
  22075. */
  22076. Light.prototype._getPhotometricScale = function () {
  22077. var photometricScale = 0.0;
  22078. var lightTypeID = this.getTypeID();
  22079. //get photometric mode
  22080. var photometricMode = this.intensityMode;
  22081. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22082. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22083. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22084. }
  22085. else {
  22086. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22087. }
  22088. }
  22089. //compute photometric scale
  22090. switch (lightTypeID) {
  22091. case Light.LIGHTTYPEID_POINTLIGHT:
  22092. case Light.LIGHTTYPEID_SPOTLIGHT:
  22093. switch (photometricMode) {
  22094. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22095. photometricScale = 1.0 / (4.0 * Math.PI);
  22096. break;
  22097. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22098. photometricScale = 1.0;
  22099. break;
  22100. case Light.INTENSITYMODE_LUMINANCE:
  22101. photometricScale = this.radius * this.radius;
  22102. break;
  22103. }
  22104. break;
  22105. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22106. switch (photometricMode) {
  22107. case Light.INTENSITYMODE_ILLUMINANCE:
  22108. photometricScale = 1.0;
  22109. break;
  22110. case Light.INTENSITYMODE_LUMINANCE:
  22111. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22112. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22113. var apexAngleRadians = this.radius;
  22114. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22115. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22116. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22117. photometricScale = solidAngle;
  22118. break;
  22119. }
  22120. break;
  22121. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22122. // No fall off in hemisperic light.
  22123. photometricScale = 1.0;
  22124. break;
  22125. }
  22126. return photometricScale;
  22127. };
  22128. /**
  22129. * Reorder the light in the scene according to their defined priority.
  22130. * @hidden Internal Use Only
  22131. */
  22132. Light.prototype._reorderLightsInScene = function () {
  22133. var scene = this.getScene();
  22134. if (this._renderPriority != 0) {
  22135. scene.requireLightSorting = true;
  22136. }
  22137. this.getScene().sortLightsByPriority();
  22138. };
  22139. /**
  22140. * Falloff Default: light is falling off following the material specification:
  22141. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22142. */
  22143. Light.FALLOFF_DEFAULT = 0;
  22144. /**
  22145. * Falloff Physical: light is falling off following the inverse squared distance law.
  22146. */
  22147. Light.FALLOFF_PHYSICAL = 1;
  22148. /**
  22149. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22150. * to enhance interoperability with other engines.
  22151. */
  22152. Light.FALLOFF_GLTF = 2;
  22153. /**
  22154. * Falloff Standard: light is falling off like in the standard material
  22155. * to enhance interoperability with other materials.
  22156. */
  22157. Light.FALLOFF_STANDARD = 3;
  22158. //lightmapMode Consts
  22159. /**
  22160. * If every light affecting the material is in this lightmapMode,
  22161. * material.lightmapTexture adds or multiplies
  22162. * (depends on material.useLightmapAsShadowmap)
  22163. * after every other light calculations.
  22164. */
  22165. Light.LIGHTMAP_DEFAULT = 0;
  22166. /**
  22167. * material.lightmapTexture as only diffuse lighting from this light
  22168. * adds only specular lighting from this light
  22169. * adds dynamic shadows
  22170. */
  22171. Light.LIGHTMAP_SPECULAR = 1;
  22172. /**
  22173. * material.lightmapTexture as only lighting
  22174. * no light calculation from this light
  22175. * only adds dynamic shadows from this light
  22176. */
  22177. Light.LIGHTMAP_SHADOWSONLY = 2;
  22178. // Intensity Mode Consts
  22179. /**
  22180. * Each light type uses the default quantity according to its type:
  22181. * point/spot lights use luminous intensity
  22182. * directional lights use illuminance
  22183. */
  22184. Light.INTENSITYMODE_AUTOMATIC = 0;
  22185. /**
  22186. * lumen (lm)
  22187. */
  22188. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22189. /**
  22190. * candela (lm/sr)
  22191. */
  22192. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22193. /**
  22194. * lux (lm/m^2)
  22195. */
  22196. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22197. /**
  22198. * nit (cd/m^2)
  22199. */
  22200. Light.INTENSITYMODE_LUMINANCE = 4;
  22201. // Light types ids const.
  22202. /**
  22203. * Light type const id of the point light.
  22204. */
  22205. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22206. /**
  22207. * Light type const id of the directional light.
  22208. */
  22209. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22210. /**
  22211. * Light type const id of the spot light.
  22212. */
  22213. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22214. /**
  22215. * Light type const id of the hemispheric light.
  22216. */
  22217. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22218. __decorate([
  22219. BABYLON.serializeAsColor3()
  22220. ], Light.prototype, "diffuse", void 0);
  22221. __decorate([
  22222. BABYLON.serializeAsColor3()
  22223. ], Light.prototype, "specular", void 0);
  22224. __decorate([
  22225. BABYLON.serialize()
  22226. ], Light.prototype, "falloffType", void 0);
  22227. __decorate([
  22228. BABYLON.serialize()
  22229. ], Light.prototype, "intensity", void 0);
  22230. __decorate([
  22231. BABYLON.serialize()
  22232. ], Light.prototype, "range", null);
  22233. __decorate([
  22234. BABYLON.serialize()
  22235. ], Light.prototype, "intensityMode", null);
  22236. __decorate([
  22237. BABYLON.serialize()
  22238. ], Light.prototype, "radius", null);
  22239. __decorate([
  22240. BABYLON.serialize()
  22241. ], Light.prototype, "_renderPriority", void 0);
  22242. __decorate([
  22243. BABYLON.expandToProperty("_reorderLightsInScene")
  22244. ], Light.prototype, "renderPriority", void 0);
  22245. __decorate([
  22246. BABYLON.serialize("shadowEnabled")
  22247. ], Light.prototype, "_shadowEnabled", void 0);
  22248. __decorate([
  22249. BABYLON.serialize("excludeWithLayerMask")
  22250. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22251. __decorate([
  22252. BABYLON.serialize("includeOnlyWithLayerMask")
  22253. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22254. __decorate([
  22255. BABYLON.serialize("lightmapMode")
  22256. ], Light.prototype, "_lightmapMode", void 0);
  22257. return Light;
  22258. }(BABYLON.Node));
  22259. BABYLON.Light = Light;
  22260. })(BABYLON || (BABYLON = {}));
  22261. //# sourceMappingURL=babylon.light.js.map
  22262. var BABYLON;
  22263. (function (BABYLON) {
  22264. /**
  22265. * This is the base class of all the camera used in the application.
  22266. * @see http://doc.babylonjs.com/features/cameras
  22267. */
  22268. var Camera = /** @class */ (function (_super) {
  22269. __extends(Camera, _super);
  22270. /**
  22271. * Instantiates a new camera object.
  22272. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22273. * @see http://doc.babylonjs.com/features/cameras
  22274. * @param name Defines the name of the camera in the scene
  22275. * @param position Defines the position of the camera
  22276. * @param scene Defines the scene the camera belongs too
  22277. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22278. */
  22279. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22280. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22281. var _this = _super.call(this, name, scene) || this;
  22282. /**
  22283. * The vector the camera should consider as up.
  22284. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22285. */
  22286. _this.upVector = BABYLON.Vector3.Up();
  22287. /**
  22288. * Define the current limit on the left side for an orthographic camera
  22289. * In scene unit
  22290. */
  22291. _this.orthoLeft = null;
  22292. /**
  22293. * Define the current limit on the right side for an orthographic camera
  22294. * In scene unit
  22295. */
  22296. _this.orthoRight = null;
  22297. /**
  22298. * Define the current limit on the bottom side for an orthographic camera
  22299. * In scene unit
  22300. */
  22301. _this.orthoBottom = null;
  22302. /**
  22303. * Define the current limit on the top side for an orthographic camera
  22304. * In scene unit
  22305. */
  22306. _this.orthoTop = null;
  22307. /**
  22308. * Field Of View is set in Radians. (default is 0.8)
  22309. */
  22310. _this.fov = 0.8;
  22311. /**
  22312. * Define the minimum distance the camera can see from.
  22313. * This is important to note that the depth buffer are not infinite and the closer it starts
  22314. * the more your scene might encounter depth fighting issue.
  22315. */
  22316. _this.minZ = 1;
  22317. /**
  22318. * Define the maximum distance the camera can see to.
  22319. * This is important to note that the depth buffer are not infinite and the further it end
  22320. * the more your scene might encounter depth fighting issue.
  22321. */
  22322. _this.maxZ = 10000.0;
  22323. /**
  22324. * Define the default inertia of the camera.
  22325. * This helps giving a smooth feeling to the camera movement.
  22326. */
  22327. _this.inertia = 0.9;
  22328. /**
  22329. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22330. */
  22331. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22332. /**
  22333. * Define wether the camera is intermediate.
  22334. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22335. */
  22336. _this.isIntermediate = false;
  22337. /**
  22338. * Define the viewport of the camera.
  22339. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22340. */
  22341. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22342. /**
  22343. * Restricts the camera to viewing objects with the same layerMask.
  22344. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22345. */
  22346. _this.layerMask = 0x0FFFFFFF;
  22347. /**
  22348. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22349. */
  22350. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22351. /**
  22352. * Rig mode of the camera.
  22353. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22354. * This is normally controlled byt the camera themselves as internal use.
  22355. */
  22356. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22357. /**
  22358. * Defines the list of custom render target the camera should render to.
  22359. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22360. * else in the scene.
  22361. */
  22362. _this.customRenderTargets = new Array();
  22363. /**
  22364. * Observable triggered when the camera view matrix has changed.
  22365. */
  22366. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22367. /**
  22368. * Observable triggered when the camera Projection matrix has changed.
  22369. */
  22370. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22371. /**
  22372. * Observable triggered when the inputs have been processed.
  22373. */
  22374. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22375. /**
  22376. * Observable triggered when reset has been called and applied to the camera.
  22377. */
  22378. _this.onRestoreStateObservable = new BABYLON.Observable();
  22379. /** @hidden */
  22380. _this._rigCameras = new Array();
  22381. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22382. /** @hidden */
  22383. _this._skipRendering = false;
  22384. /** @hidden */
  22385. _this._projectionMatrix = new BABYLON.Matrix();
  22386. /** @hidden */
  22387. _this._postProcesses = new Array();
  22388. /** @hidden */
  22389. _this._activeMeshes = new BABYLON.SmartArray(256);
  22390. _this._globalPosition = BABYLON.Vector3.Zero();
  22391. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22392. _this._doNotComputeProjectionMatrix = false;
  22393. _this._transformMatrix = BABYLON.Matrix.Zero();
  22394. _this._refreshFrustumPlanes = true;
  22395. _this.getScene().addCamera(_this);
  22396. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22397. _this.getScene().activeCamera = _this;
  22398. }
  22399. _this.position = position;
  22400. return _this;
  22401. }
  22402. /**
  22403. * Store current camera state (fov, position, etc..)
  22404. * @returns the camera
  22405. */
  22406. Camera.prototype.storeState = function () {
  22407. this._stateStored = true;
  22408. this._storedFov = this.fov;
  22409. return this;
  22410. };
  22411. /**
  22412. * Restores the camera state values if it has been stored. You must call storeState() first
  22413. */
  22414. Camera.prototype._restoreStateValues = function () {
  22415. if (!this._stateStored) {
  22416. return false;
  22417. }
  22418. this.fov = this._storedFov;
  22419. return true;
  22420. };
  22421. /**
  22422. * Restored camera state. You must call storeState() first.
  22423. * @returns true if restored and false otherwise
  22424. */
  22425. Camera.prototype.restoreState = function () {
  22426. if (this._restoreStateValues()) {
  22427. this.onRestoreStateObservable.notifyObservers(this);
  22428. return true;
  22429. }
  22430. return false;
  22431. };
  22432. /**
  22433. * Gets the class name of the camera.
  22434. * @returns the class name
  22435. */
  22436. Camera.prototype.getClassName = function () {
  22437. return "Camera";
  22438. };
  22439. /**
  22440. * Gets a string representation of the camera usefull for debug purpose.
  22441. * @param fullDetails Defines that a more verboe level of logging is required
  22442. * @returns the string representation
  22443. */
  22444. Camera.prototype.toString = function (fullDetails) {
  22445. var ret = "Name: " + this.name;
  22446. ret += ", type: " + this.getClassName();
  22447. if (this.animations) {
  22448. for (var i = 0; i < this.animations.length; i++) {
  22449. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22450. }
  22451. }
  22452. if (fullDetails) {
  22453. }
  22454. return ret;
  22455. };
  22456. Object.defineProperty(Camera.prototype, "globalPosition", {
  22457. /**
  22458. * Gets the current world space position of the camera.
  22459. */
  22460. get: function () {
  22461. return this._globalPosition;
  22462. },
  22463. enumerable: true,
  22464. configurable: true
  22465. });
  22466. /**
  22467. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22468. * @returns the active meshe list
  22469. */
  22470. Camera.prototype.getActiveMeshes = function () {
  22471. return this._activeMeshes;
  22472. };
  22473. /**
  22474. * Check wether a mesh is part of the current active mesh list of the camera
  22475. * @param mesh Defines the mesh to check
  22476. * @returns true if active, false otherwise
  22477. */
  22478. Camera.prototype.isActiveMesh = function (mesh) {
  22479. return (this._activeMeshes.indexOf(mesh) !== -1);
  22480. };
  22481. /**
  22482. * Is this camera ready to be used/rendered
  22483. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22484. * @return true if the camera is ready
  22485. */
  22486. Camera.prototype.isReady = function (completeCheck) {
  22487. if (completeCheck === void 0) { completeCheck = false; }
  22488. if (completeCheck) {
  22489. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22490. var pp = _a[_i];
  22491. if (pp && !pp.isReady()) {
  22492. return false;
  22493. }
  22494. }
  22495. }
  22496. return _super.prototype.isReady.call(this, completeCheck);
  22497. };
  22498. /** @hidden */
  22499. Camera.prototype._initCache = function () {
  22500. _super.prototype._initCache.call(this);
  22501. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22502. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22503. this._cache.mode = undefined;
  22504. this._cache.minZ = undefined;
  22505. this._cache.maxZ = undefined;
  22506. this._cache.fov = undefined;
  22507. this._cache.fovMode = undefined;
  22508. this._cache.aspectRatio = undefined;
  22509. this._cache.orthoLeft = undefined;
  22510. this._cache.orthoRight = undefined;
  22511. this._cache.orthoBottom = undefined;
  22512. this._cache.orthoTop = undefined;
  22513. this._cache.renderWidth = undefined;
  22514. this._cache.renderHeight = undefined;
  22515. };
  22516. /** @hidden */
  22517. Camera.prototype._updateCache = function (ignoreParentClass) {
  22518. if (!ignoreParentClass) {
  22519. _super.prototype._updateCache.call(this);
  22520. }
  22521. this._cache.position.copyFrom(this.position);
  22522. this._cache.upVector.copyFrom(this.upVector);
  22523. };
  22524. /** @hidden */
  22525. Camera.prototype._isSynchronized = function () {
  22526. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22527. };
  22528. /** @hidden */
  22529. Camera.prototype._isSynchronizedViewMatrix = function () {
  22530. if (!_super.prototype._isSynchronized.call(this))
  22531. return false;
  22532. return this._cache.position.equals(this.position)
  22533. && this._cache.upVector.equals(this.upVector)
  22534. && this.isSynchronizedWithParent();
  22535. };
  22536. /** @hidden */
  22537. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22538. var check = this._cache.mode === this.mode
  22539. && this._cache.minZ === this.minZ
  22540. && this._cache.maxZ === this.maxZ;
  22541. if (!check) {
  22542. return false;
  22543. }
  22544. var engine = this.getEngine();
  22545. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22546. check = this._cache.fov === this.fov
  22547. && this._cache.fovMode === this.fovMode
  22548. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22549. }
  22550. else {
  22551. check = this._cache.orthoLeft === this.orthoLeft
  22552. && this._cache.orthoRight === this.orthoRight
  22553. && this._cache.orthoBottom === this.orthoBottom
  22554. && this._cache.orthoTop === this.orthoTop
  22555. && this._cache.renderWidth === engine.getRenderWidth()
  22556. && this._cache.renderHeight === engine.getRenderHeight();
  22557. }
  22558. return check;
  22559. };
  22560. /**
  22561. * Attach the input controls to a specific dom element to get the input from.
  22562. * @param element Defines the element the controls should be listened from
  22563. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22564. */
  22565. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22566. };
  22567. /**
  22568. * Detach the current controls from the specified dom element.
  22569. * @param element Defines the element to stop listening the inputs from
  22570. */
  22571. Camera.prototype.detachControl = function (element) {
  22572. };
  22573. /**
  22574. * Update the camera state according to the different inputs gathered during the frame.
  22575. */
  22576. Camera.prototype.update = function () {
  22577. this._checkInputs();
  22578. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22579. this._updateRigCameras();
  22580. }
  22581. };
  22582. /** @hidden */
  22583. Camera.prototype._checkInputs = function () {
  22584. this.onAfterCheckInputsObservable.notifyObservers(this);
  22585. };
  22586. Object.defineProperty(Camera.prototype, "rigCameras", {
  22587. /** @hidden */
  22588. get: function () {
  22589. return this._rigCameras;
  22590. },
  22591. enumerable: true,
  22592. configurable: true
  22593. });
  22594. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22595. get: function () {
  22596. return this._rigPostProcess;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. /**
  22602. * Internal, gets the first post proces.
  22603. * @returns the first post process to be run on this camera.
  22604. */
  22605. Camera.prototype._getFirstPostProcess = function () {
  22606. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22607. if (this._postProcesses[ppIndex] !== null) {
  22608. return this._postProcesses[ppIndex];
  22609. }
  22610. }
  22611. return null;
  22612. };
  22613. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22614. // invalidate framebuffer
  22615. var firstPostProcess = this._getFirstPostProcess();
  22616. if (firstPostProcess) {
  22617. firstPostProcess.markTextureDirty();
  22618. }
  22619. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22620. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22621. var cam = this._rigCameras[i];
  22622. var rigPostProcess = cam._rigPostProcess;
  22623. // for VR rig, there does not have to be a post process
  22624. if (rigPostProcess) {
  22625. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22626. if (isPass) {
  22627. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22628. cam.isIntermediate = this._postProcesses.length === 0;
  22629. }
  22630. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22631. rigPostProcess.markTextureDirty();
  22632. }
  22633. else {
  22634. cam._postProcesses = this._postProcesses.slice(0);
  22635. }
  22636. }
  22637. };
  22638. /**
  22639. * Attach a post process to the camera.
  22640. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22641. * @param postProcess The post process to attach to the camera
  22642. * @param insertAt The position of the post process in case several of them are in use in the scene
  22643. * @returns the position the post process has been inserted at
  22644. */
  22645. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22646. if (insertAt === void 0) { insertAt = null; }
  22647. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22648. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22649. return 0;
  22650. }
  22651. if (insertAt == null || insertAt < 0) {
  22652. this._postProcesses.push(postProcess);
  22653. }
  22654. else if (this._postProcesses[insertAt] === null) {
  22655. this._postProcesses[insertAt] = postProcess;
  22656. }
  22657. else {
  22658. this._postProcesses.splice(insertAt, 0, postProcess);
  22659. }
  22660. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22661. return this._postProcesses.indexOf(postProcess);
  22662. };
  22663. /**
  22664. * Detach a post process to the camera.
  22665. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22666. * @param postProcess The post process to detach from the camera
  22667. */
  22668. Camera.prototype.detachPostProcess = function (postProcess) {
  22669. var idx = this._postProcesses.indexOf(postProcess);
  22670. if (idx !== -1) {
  22671. this._postProcesses[idx] = null;
  22672. }
  22673. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22674. };
  22675. /**
  22676. * Gets the current world matrix of the camera
  22677. */
  22678. Camera.prototype.getWorldMatrix = function () {
  22679. if (this._isSynchronizedViewMatrix()) {
  22680. return this._worldMatrix;
  22681. }
  22682. // Getting the the view matrix will also compute the world matrix.
  22683. this.getViewMatrix();
  22684. return this._worldMatrix;
  22685. };
  22686. /** @hidden */
  22687. Camera.prototype._getViewMatrix = function () {
  22688. return BABYLON.Matrix.Identity();
  22689. };
  22690. /**
  22691. * Gets the current view matrix of the camera.
  22692. * @param force forces the camera to recompute the matrix without looking at the cached state
  22693. * @returns the view matrix
  22694. */
  22695. Camera.prototype.getViewMatrix = function (force) {
  22696. if (!force && this._isSynchronizedViewMatrix()) {
  22697. return this._computedViewMatrix;
  22698. }
  22699. this.updateCache();
  22700. this._computedViewMatrix = this._getViewMatrix();
  22701. this._currentRenderId = this.getScene().getRenderId();
  22702. this._childRenderId = this._currentRenderId;
  22703. this._refreshFrustumPlanes = true;
  22704. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22705. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22706. }
  22707. this.onViewMatrixChangedObservable.notifyObservers(this);
  22708. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22709. return this._computedViewMatrix;
  22710. };
  22711. /**
  22712. * Freeze the projection matrix.
  22713. * It will prevent the cache check of the camera projection compute and can speed up perf
  22714. * if no parameter of the camera are meant to change
  22715. * @param projection Defines manually a projection if necessary
  22716. */
  22717. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22718. this._doNotComputeProjectionMatrix = true;
  22719. if (projection !== undefined) {
  22720. this._projectionMatrix = projection;
  22721. }
  22722. };
  22723. ;
  22724. /**
  22725. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22726. */
  22727. Camera.prototype.unfreezeProjectionMatrix = function () {
  22728. this._doNotComputeProjectionMatrix = false;
  22729. };
  22730. ;
  22731. /**
  22732. * Gets the current projection matrix of the camera.
  22733. * @param force forces the camera to recompute the matrix without looking at the cached state
  22734. * @returns the projection matrix
  22735. */
  22736. Camera.prototype.getProjectionMatrix = function (force) {
  22737. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22738. return this._projectionMatrix;
  22739. }
  22740. // Cache
  22741. this._cache.mode = this.mode;
  22742. this._cache.minZ = this.minZ;
  22743. this._cache.maxZ = this.maxZ;
  22744. // Matrix
  22745. this._refreshFrustumPlanes = true;
  22746. var engine = this.getEngine();
  22747. var scene = this.getScene();
  22748. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22749. this._cache.fov = this.fov;
  22750. this._cache.fovMode = this.fovMode;
  22751. this._cache.aspectRatio = engine.getAspectRatio(this);
  22752. if (this.minZ <= 0) {
  22753. this.minZ = 0.1;
  22754. }
  22755. if (scene.useRightHandedSystem) {
  22756. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22757. }
  22758. else {
  22759. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22760. }
  22761. }
  22762. else {
  22763. var halfWidth = engine.getRenderWidth() / 2.0;
  22764. var halfHeight = engine.getRenderHeight() / 2.0;
  22765. if (scene.useRightHandedSystem) {
  22766. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22767. }
  22768. else {
  22769. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22770. }
  22771. this._cache.orthoLeft = this.orthoLeft;
  22772. this._cache.orthoRight = this.orthoRight;
  22773. this._cache.orthoBottom = this.orthoBottom;
  22774. this._cache.orthoTop = this.orthoTop;
  22775. this._cache.renderWidth = engine.getRenderWidth();
  22776. this._cache.renderHeight = engine.getRenderHeight();
  22777. }
  22778. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22779. return this._projectionMatrix;
  22780. };
  22781. /**
  22782. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22783. * @returns a Matrix
  22784. */
  22785. Camera.prototype.getTransformationMatrix = function () {
  22786. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22787. return this._transformMatrix;
  22788. };
  22789. Camera.prototype._updateFrustumPlanes = function () {
  22790. if (!this._refreshFrustumPlanes) {
  22791. return;
  22792. }
  22793. this.getTransformationMatrix();
  22794. if (!this._frustumPlanes) {
  22795. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22796. }
  22797. else {
  22798. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22799. }
  22800. this._refreshFrustumPlanes = false;
  22801. };
  22802. /**
  22803. * Checks if a cullable object (mesh...) is in the camera frustum
  22804. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22805. * @param target The object to check
  22806. * @returns true if the object is in frustum otherwise false
  22807. */
  22808. Camera.prototype.isInFrustum = function (target) {
  22809. this._updateFrustumPlanes();
  22810. return target.isInFrustum(this._frustumPlanes);
  22811. };
  22812. /**
  22813. * Checks if a cullable object (mesh...) is in the camera frustum
  22814. * Unlike isInFrustum this cheks the full bounding box
  22815. * @param target The object to check
  22816. * @returns true if the object is in frustum otherwise false
  22817. */
  22818. Camera.prototype.isCompletelyInFrustum = function (target) {
  22819. this._updateFrustumPlanes();
  22820. return target.isCompletelyInFrustum(this._frustumPlanes);
  22821. };
  22822. /**
  22823. * Gets a ray in the forward direction from the camera.
  22824. * @param length Defines the length of the ray to create
  22825. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22826. * @param origin Defines the start point of the ray which defaults to the camera position
  22827. * @returns the forward ray
  22828. */
  22829. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22830. if (length === void 0) { length = 100; }
  22831. if (!transform) {
  22832. transform = this.getWorldMatrix();
  22833. }
  22834. if (!origin) {
  22835. origin = this.position;
  22836. }
  22837. var forward = new BABYLON.Vector3(0, 0, 1);
  22838. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22839. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22840. return new BABYLON.Ray(origin, direction, length);
  22841. };
  22842. /**
  22843. * Releases resources associated with this node.
  22844. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22845. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22846. */
  22847. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22848. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22849. // Observables
  22850. this.onViewMatrixChangedObservable.clear();
  22851. this.onProjectionMatrixChangedObservable.clear();
  22852. this.onAfterCheckInputsObservable.clear();
  22853. this.onRestoreStateObservable.clear();
  22854. // Inputs
  22855. if (this.inputs) {
  22856. this.inputs.clear();
  22857. }
  22858. // Animations
  22859. this.getScene().stopAnimation(this);
  22860. // Remove from scene
  22861. this.getScene().removeCamera(this);
  22862. while (this._rigCameras.length > 0) {
  22863. var camera = this._rigCameras.pop();
  22864. if (camera) {
  22865. camera.dispose();
  22866. }
  22867. }
  22868. // Postprocesses
  22869. if (this._rigPostProcess) {
  22870. this._rigPostProcess.dispose(this);
  22871. this._rigPostProcess = null;
  22872. this._postProcesses = [];
  22873. }
  22874. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22875. this._rigPostProcess = null;
  22876. this._postProcesses = [];
  22877. }
  22878. else {
  22879. var i = this._postProcesses.length;
  22880. while (--i >= 0) {
  22881. var postProcess = this._postProcesses[i];
  22882. if (postProcess) {
  22883. postProcess.dispose(this);
  22884. }
  22885. }
  22886. }
  22887. // Render targets
  22888. var i = this.customRenderTargets.length;
  22889. while (--i >= 0) {
  22890. this.customRenderTargets[i].dispose();
  22891. }
  22892. this.customRenderTargets = [];
  22893. // Active Meshes
  22894. this._activeMeshes.dispose();
  22895. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22896. };
  22897. Object.defineProperty(Camera.prototype, "leftCamera", {
  22898. /**
  22899. * Gets the left camera of a rig setup in case of Rigged Camera
  22900. */
  22901. get: function () {
  22902. if (this._rigCameras.length < 1) {
  22903. return null;
  22904. }
  22905. return this._rigCameras[0];
  22906. },
  22907. enumerable: true,
  22908. configurable: true
  22909. });
  22910. Object.defineProperty(Camera.prototype, "rightCamera", {
  22911. /**
  22912. * Gets the right camera of a rig setup in case of Rigged Camera
  22913. */
  22914. get: function () {
  22915. if (this._rigCameras.length < 2) {
  22916. return null;
  22917. }
  22918. return this._rigCameras[1];
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. /**
  22924. * Gets the left camera target of a rig setup in case of Rigged Camera
  22925. * @returns the target position
  22926. */
  22927. Camera.prototype.getLeftTarget = function () {
  22928. if (this._rigCameras.length < 1) {
  22929. return null;
  22930. }
  22931. return this._rigCameras[0].getTarget();
  22932. };
  22933. /**
  22934. * Gets the right camera target of a rig setup in case of Rigged Camera
  22935. * @returns the target position
  22936. */
  22937. Camera.prototype.getRightTarget = function () {
  22938. if (this._rigCameras.length < 2) {
  22939. return null;
  22940. }
  22941. return this._rigCameras[1].getTarget();
  22942. };
  22943. /**
  22944. * @hidden
  22945. */
  22946. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22947. if (this.cameraRigMode === mode) {
  22948. return;
  22949. }
  22950. while (this._rigCameras.length > 0) {
  22951. var camera = this._rigCameras.pop();
  22952. if (camera) {
  22953. camera.dispose();
  22954. }
  22955. }
  22956. this.cameraRigMode = mode;
  22957. this._cameraRigParams = {};
  22958. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22959. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22960. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22961. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22962. // create the rig cameras, unless none
  22963. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22964. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22965. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22966. if (leftCamera && rightCamera) {
  22967. this._rigCameras.push(leftCamera);
  22968. this._rigCameras.push(rightCamera);
  22969. }
  22970. }
  22971. switch (this.cameraRigMode) {
  22972. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22973. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22974. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22975. break;
  22976. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22977. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22978. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22979. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22980. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22981. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22982. break;
  22983. case Camera.RIG_MODE_VR:
  22984. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22985. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22986. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22987. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22988. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22989. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22990. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22991. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22992. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22993. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22994. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22995. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22996. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22997. if (metrics.compensateDistortion) {
  22998. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22999. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23000. }
  23001. break;
  23002. case Camera.RIG_MODE_WEBVR:
  23003. if (rigParams.vrDisplay) {
  23004. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23005. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23006. //Left eye
  23007. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23008. this._rigCameras[0].setCameraRigParameter("left", true);
  23009. //leaving this for future reference
  23010. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23011. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23012. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23013. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23014. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23015. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23016. this._rigCameras[0].parent = this;
  23017. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23018. //Right eye
  23019. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23020. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23021. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23022. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23023. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23024. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23025. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23026. this._rigCameras[1].parent = this;
  23027. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23028. if (Camera.UseAlternateWebVRRendering) {
  23029. this._rigCameras[1]._skipRendering = true;
  23030. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23031. }
  23032. }
  23033. break;
  23034. }
  23035. this._cascadePostProcessesToRigCams();
  23036. this.update();
  23037. };
  23038. Camera.prototype._getVRProjectionMatrix = function () {
  23039. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23040. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23041. return this._projectionMatrix;
  23042. };
  23043. Camera.prototype._updateCameraRotationMatrix = function () {
  23044. //Here for WebVR
  23045. };
  23046. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23047. //Here for WebVR
  23048. };
  23049. /**
  23050. * This function MUST be overwritten by the different WebVR cameras available.
  23051. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23052. */
  23053. Camera.prototype._getWebVRProjectionMatrix = function () {
  23054. return BABYLON.Matrix.Identity();
  23055. };
  23056. /**
  23057. * This function MUST be overwritten by the different WebVR cameras available.
  23058. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23059. */
  23060. Camera.prototype._getWebVRViewMatrix = function () {
  23061. return BABYLON.Matrix.Identity();
  23062. };
  23063. /** @hidden */
  23064. Camera.prototype.setCameraRigParameter = function (name, value) {
  23065. if (!this._cameraRigParams) {
  23066. this._cameraRigParams = {};
  23067. }
  23068. this._cameraRigParams[name] = value;
  23069. //provisionnally:
  23070. if (name === "interaxialDistance") {
  23071. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23072. }
  23073. };
  23074. /**
  23075. * needs to be overridden by children so sub has required properties to be copied
  23076. * @hidden
  23077. */
  23078. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23079. return null;
  23080. };
  23081. /**
  23082. * May need to be overridden by children
  23083. * @hidden
  23084. */
  23085. Camera.prototype._updateRigCameras = function () {
  23086. for (var i = 0; i < this._rigCameras.length; i++) {
  23087. this._rigCameras[i].minZ = this.minZ;
  23088. this._rigCameras[i].maxZ = this.maxZ;
  23089. this._rigCameras[i].fov = this.fov;
  23090. }
  23091. // only update viewport when ANAGLYPH
  23092. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23093. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23094. }
  23095. };
  23096. /** @hidden */
  23097. Camera.prototype._setupInputs = function () {
  23098. };
  23099. /**
  23100. * Serialiaze the camera setup to a json represention
  23101. * @returns the JSON representation
  23102. */
  23103. Camera.prototype.serialize = function () {
  23104. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23105. // Type
  23106. serializationObject.type = this.getClassName();
  23107. // Parent
  23108. if (this.parent) {
  23109. serializationObject.parentId = this.parent.id;
  23110. }
  23111. if (this.inputs) {
  23112. this.inputs.serialize(serializationObject);
  23113. }
  23114. // Animations
  23115. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23116. serializationObject.ranges = this.serializeAnimationRanges();
  23117. return serializationObject;
  23118. };
  23119. /**
  23120. * Clones the current camera.
  23121. * @param name The cloned camera name
  23122. * @returns the cloned camera
  23123. */
  23124. Camera.prototype.clone = function (name) {
  23125. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23126. };
  23127. /**
  23128. * Gets the direction of the camera relative to a given local axis.
  23129. * @param localAxis Defines the reference axis to provide a relative direction.
  23130. * @return the direction
  23131. */
  23132. Camera.prototype.getDirection = function (localAxis) {
  23133. var result = BABYLON.Vector3.Zero();
  23134. this.getDirectionToRef(localAxis, result);
  23135. return result;
  23136. };
  23137. /**
  23138. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23139. * @param localAxis Defines the reference axis to provide a relative direction.
  23140. * @param result Defines the vector to store the result in
  23141. */
  23142. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23143. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23144. };
  23145. /**
  23146. * Gets a camera constructor for a given camera type
  23147. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23148. * @param name The name of the camera the result will be able to instantiate
  23149. * @param scene The scene the result will construct the camera in
  23150. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23151. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23152. * @returns a factory method to construc the camera
  23153. */
  23154. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23155. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23156. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23157. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23158. interaxial_distance: interaxial_distance,
  23159. isStereoscopicSideBySide: isStereoscopicSideBySide
  23160. });
  23161. if (constructorFunc) {
  23162. return constructorFunc;
  23163. }
  23164. // Default to universal camera
  23165. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23166. };
  23167. /**
  23168. * Compute the world matrix of the camera.
  23169. * @returns the camera workd matrix
  23170. */
  23171. Camera.prototype.computeWorldMatrix = function () {
  23172. return this.getWorldMatrix();
  23173. };
  23174. /**
  23175. * Parse a JSON and creates the camera from the parsed information
  23176. * @param parsedCamera The JSON to parse
  23177. * @param scene The scene to instantiate the camera in
  23178. * @returns the newly constructed camera
  23179. */
  23180. Camera.Parse = function (parsedCamera, scene) {
  23181. var type = parsedCamera.type;
  23182. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23183. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23184. // Parent
  23185. if (parsedCamera.parentId) {
  23186. camera._waitingParentId = parsedCamera.parentId;
  23187. }
  23188. //If camera has an input manager, let it parse inputs settings
  23189. if (camera.inputs) {
  23190. camera.inputs.parse(parsedCamera);
  23191. camera._setupInputs();
  23192. }
  23193. if (camera.setPosition) { // need to force position
  23194. camera.position.copyFromFloats(0, 0, 0);
  23195. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23196. }
  23197. // Target
  23198. if (parsedCamera.target) {
  23199. if (camera.setTarget) {
  23200. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23201. }
  23202. }
  23203. // Apply 3d rig, when found
  23204. if (parsedCamera.cameraRigMode) {
  23205. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23206. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23207. }
  23208. // Animations
  23209. if (parsedCamera.animations) {
  23210. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23211. var parsedAnimation = parsedCamera.animations[animationIndex];
  23212. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23213. }
  23214. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23215. }
  23216. if (parsedCamera.autoAnimate) {
  23217. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23218. }
  23219. return camera;
  23220. };
  23221. /**
  23222. * This is the default projection mode used by the cameras.
  23223. * It helps recreating a feeling of perspective and better appreciate depth.
  23224. * This is the best way to simulate real life cameras.
  23225. */
  23226. Camera.PERSPECTIVE_CAMERA = 0;
  23227. /**
  23228. * This helps creating camera with an orthographic mode.
  23229. * 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.
  23230. */
  23231. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23232. /**
  23233. * This is the default FOV mode for perspective cameras.
  23234. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23235. */
  23236. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23237. /**
  23238. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23239. */
  23240. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23241. /**
  23242. * This specifies ther is no need for a camera rig.
  23243. * Basically only one eye is rendered corresponding to the camera.
  23244. */
  23245. Camera.RIG_MODE_NONE = 0;
  23246. /**
  23247. * Simulates a camera Rig with one blue eye and one red eye.
  23248. * This can be use with 3d blue and red glasses.
  23249. */
  23250. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23251. /**
  23252. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23253. */
  23254. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23255. /**
  23256. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23257. */
  23258. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23259. /**
  23260. * Defines that both eyes of the camera will be rendered over under each other.
  23261. */
  23262. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23263. /**
  23264. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23265. */
  23266. Camera.RIG_MODE_VR = 20;
  23267. /**
  23268. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23269. */
  23270. Camera.RIG_MODE_WEBVR = 21;
  23271. /**
  23272. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23273. */
  23274. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23275. /**
  23276. * @hidden
  23277. * Might be removed once multiview will be a thing
  23278. */
  23279. Camera.UseAlternateWebVRRendering = false;
  23280. __decorate([
  23281. BABYLON.serializeAsVector3()
  23282. ], Camera.prototype, "position", void 0);
  23283. __decorate([
  23284. BABYLON.serializeAsVector3()
  23285. ], Camera.prototype, "upVector", void 0);
  23286. __decorate([
  23287. BABYLON.serialize()
  23288. ], Camera.prototype, "orthoLeft", void 0);
  23289. __decorate([
  23290. BABYLON.serialize()
  23291. ], Camera.prototype, "orthoRight", void 0);
  23292. __decorate([
  23293. BABYLON.serialize()
  23294. ], Camera.prototype, "orthoBottom", void 0);
  23295. __decorate([
  23296. BABYLON.serialize()
  23297. ], Camera.prototype, "orthoTop", void 0);
  23298. __decorate([
  23299. BABYLON.serialize()
  23300. ], Camera.prototype, "fov", void 0);
  23301. __decorate([
  23302. BABYLON.serialize()
  23303. ], Camera.prototype, "minZ", void 0);
  23304. __decorate([
  23305. BABYLON.serialize()
  23306. ], Camera.prototype, "maxZ", void 0);
  23307. __decorate([
  23308. BABYLON.serialize()
  23309. ], Camera.prototype, "inertia", void 0);
  23310. __decorate([
  23311. BABYLON.serialize()
  23312. ], Camera.prototype, "mode", void 0);
  23313. __decorate([
  23314. BABYLON.serialize()
  23315. ], Camera.prototype, "layerMask", void 0);
  23316. __decorate([
  23317. BABYLON.serialize()
  23318. ], Camera.prototype, "fovMode", void 0);
  23319. __decorate([
  23320. BABYLON.serialize()
  23321. ], Camera.prototype, "cameraRigMode", void 0);
  23322. __decorate([
  23323. BABYLON.serialize()
  23324. ], Camera.prototype, "interaxialDistance", void 0);
  23325. __decorate([
  23326. BABYLON.serialize()
  23327. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23328. return Camera;
  23329. }(BABYLON.Node));
  23330. BABYLON.Camera = Camera;
  23331. })(BABYLON || (BABYLON = {}));
  23332. //# sourceMappingURL=babylon.camera.js.map
  23333. var BABYLON;
  23334. (function (BABYLON) {
  23335. var RenderingManager = /** @class */ (function () {
  23336. function RenderingManager(scene) {
  23337. /**
  23338. * @hidden
  23339. */
  23340. this._useSceneAutoClearSetup = false;
  23341. this._renderingGroups = new Array();
  23342. this._autoClearDepthStencil = {};
  23343. this._customOpaqueSortCompareFn = {};
  23344. this._customAlphaTestSortCompareFn = {};
  23345. this._customTransparentSortCompareFn = {};
  23346. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23347. this._scene = scene;
  23348. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23349. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23350. }
  23351. }
  23352. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23353. if (depth === void 0) { depth = true; }
  23354. if (stencil === void 0) { stencil = true; }
  23355. if (this._depthStencilBufferAlreadyCleaned) {
  23356. return;
  23357. }
  23358. this._scene.getEngine().clear(null, false, depth, stencil);
  23359. this._depthStencilBufferAlreadyCleaned = true;
  23360. };
  23361. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23362. // Update the observable context (not null as it only goes away on dispose)
  23363. var info = this._renderingGroupInfo;
  23364. info.scene = this._scene;
  23365. info.camera = this._scene.activeCamera;
  23366. // Dispatch sprites
  23367. if (this._scene.spriteManagers && renderSprites) {
  23368. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23369. var manager = this._scene.spriteManagers[index];
  23370. this.dispatchSprites(manager);
  23371. }
  23372. }
  23373. // Render
  23374. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23375. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23376. var renderingGroup = this._renderingGroups[index];
  23377. if (!renderingGroup)
  23378. continue;
  23379. var renderingGroupMask = Math.pow(2, index);
  23380. info.renderingGroupId = index;
  23381. // Before Observable
  23382. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23383. // Clear depth/stencil if needed
  23384. if (RenderingManager.AUTOCLEAR) {
  23385. var autoClear = this._useSceneAutoClearSetup ?
  23386. this._scene.getAutoClearDepthStencilSetup(index) :
  23387. this._autoClearDepthStencil[index];
  23388. if (autoClear && autoClear.autoClear) {
  23389. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23390. }
  23391. }
  23392. // Render
  23393. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23394. var step = _a[_i];
  23395. step.action(index);
  23396. }
  23397. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23398. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23399. var step = _c[_b];
  23400. step.action(index);
  23401. }
  23402. // After Observable
  23403. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23404. }
  23405. };
  23406. RenderingManager.prototype.reset = function () {
  23407. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23408. var renderingGroup = this._renderingGroups[index];
  23409. if (renderingGroup) {
  23410. renderingGroup.prepare();
  23411. }
  23412. }
  23413. };
  23414. RenderingManager.prototype.dispose = function () {
  23415. this.freeRenderingGroups();
  23416. this._renderingGroups.length = 0;
  23417. this._renderingGroupInfo = null;
  23418. };
  23419. /**
  23420. * Clear the info related to rendering groups preventing retention points during dispose.
  23421. */
  23422. RenderingManager.prototype.freeRenderingGroups = function () {
  23423. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23424. var renderingGroup = this._renderingGroups[index];
  23425. if (renderingGroup) {
  23426. renderingGroup.dispose();
  23427. }
  23428. }
  23429. };
  23430. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23431. if (this._renderingGroups[renderingGroupId] === undefined) {
  23432. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23433. }
  23434. };
  23435. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23436. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23437. this._prepareRenderingGroup(renderingGroupId);
  23438. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23439. };
  23440. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23441. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23442. this._prepareRenderingGroup(renderingGroupId);
  23443. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23444. };
  23445. /**
  23446. * @param subMesh The submesh to dispatch
  23447. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23448. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23449. */
  23450. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23451. if (mesh === undefined) {
  23452. mesh = subMesh.getMesh();
  23453. }
  23454. var renderingGroupId = mesh.renderingGroupId || 0;
  23455. this._prepareRenderingGroup(renderingGroupId);
  23456. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23457. };
  23458. /**
  23459. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23460. * This allowed control for front to back rendering or reversly depending of the special needs.
  23461. *
  23462. * @param renderingGroupId The rendering group id corresponding to its index
  23463. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23464. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23465. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23466. */
  23467. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23468. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23469. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23470. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23471. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23472. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23473. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23474. if (this._renderingGroups[renderingGroupId]) {
  23475. var group = this._renderingGroups[renderingGroupId];
  23476. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23477. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23478. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23479. }
  23480. };
  23481. /**
  23482. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23483. *
  23484. * @param renderingGroupId The rendering group id corresponding to its index
  23485. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23486. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23487. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23488. */
  23489. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23490. if (depth === void 0) { depth = true; }
  23491. if (stencil === void 0) { stencil = true; }
  23492. this._autoClearDepthStencil[renderingGroupId] = {
  23493. autoClear: autoClearDepthStencil,
  23494. depth: depth,
  23495. stencil: stencil
  23496. };
  23497. };
  23498. /**
  23499. * Gets the current auto clear configuration for one rendering group of the rendering
  23500. * manager.
  23501. * @param index the rendering group index to get the information for
  23502. * @returns The auto clear setup for the requested rendering group
  23503. */
  23504. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23505. return this._autoClearDepthStencil[index];
  23506. };
  23507. /**
  23508. * The max id used for rendering groups (not included)
  23509. */
  23510. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23511. /**
  23512. * The min id used for rendering groups (included)
  23513. */
  23514. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23515. /**
  23516. * Used to globally prevent autoclearing scenes.
  23517. */
  23518. RenderingManager.AUTOCLEAR = true;
  23519. return RenderingManager;
  23520. }());
  23521. BABYLON.RenderingManager = RenderingManager;
  23522. })(BABYLON || (BABYLON = {}));
  23523. //# sourceMappingURL=babylon.renderingManager.js.map
  23524. var BABYLON;
  23525. (function (BABYLON) {
  23526. var RenderingGroup = /** @class */ (function () {
  23527. /**
  23528. * Creates a new rendering group.
  23529. * @param index The rendering group index
  23530. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23531. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23532. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23533. */
  23534. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23535. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23536. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23537. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23538. this.index = index;
  23539. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23540. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23541. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23542. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23543. this._particleSystems = new BABYLON.SmartArray(256);
  23544. this._spriteManagers = new BABYLON.SmartArray(256);
  23545. this._edgesRenderers = new BABYLON.SmartArray(16);
  23546. this._scene = scene;
  23547. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23548. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23549. this.transparentSortCompareFn = transparentSortCompareFn;
  23550. }
  23551. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23552. /**
  23553. * Set the opaque sort comparison function.
  23554. * If null the sub meshes will be render in the order they were created
  23555. */
  23556. set: function (value) {
  23557. this._opaqueSortCompareFn = value;
  23558. if (value) {
  23559. this._renderOpaque = this.renderOpaqueSorted;
  23560. }
  23561. else {
  23562. this._renderOpaque = RenderingGroup.renderUnsorted;
  23563. }
  23564. },
  23565. enumerable: true,
  23566. configurable: true
  23567. });
  23568. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23569. /**
  23570. * Set the alpha test sort comparison function.
  23571. * If null the sub meshes will be render in the order they were created
  23572. */
  23573. set: function (value) {
  23574. this._alphaTestSortCompareFn = value;
  23575. if (value) {
  23576. this._renderAlphaTest = this.renderAlphaTestSorted;
  23577. }
  23578. else {
  23579. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23580. }
  23581. },
  23582. enumerable: true,
  23583. configurable: true
  23584. });
  23585. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23586. /**
  23587. * Set the transparent sort comparison function.
  23588. * If null the sub meshes will be render in the order they were created
  23589. */
  23590. set: function (value) {
  23591. if (value) {
  23592. this._transparentSortCompareFn = value;
  23593. }
  23594. else {
  23595. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23596. }
  23597. this._renderTransparent = this.renderTransparentSorted;
  23598. },
  23599. enumerable: true,
  23600. configurable: true
  23601. });
  23602. /**
  23603. * Render all the sub meshes contained in the group.
  23604. * @param customRenderFunction Used to override the default render behaviour of the group.
  23605. * @returns true if rendered some submeshes.
  23606. */
  23607. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23608. if (customRenderFunction) {
  23609. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23610. return;
  23611. }
  23612. var engine = this._scene.getEngine();
  23613. // Depth only
  23614. if (this._depthOnlySubMeshes.length !== 0) {
  23615. engine.setColorWrite(false);
  23616. this._renderAlphaTest(this._depthOnlySubMeshes);
  23617. engine.setColorWrite(true);
  23618. }
  23619. // Opaque
  23620. if (this._opaqueSubMeshes.length !== 0) {
  23621. this._renderOpaque(this._opaqueSubMeshes);
  23622. }
  23623. // Alpha test
  23624. if (this._alphaTestSubMeshes.length !== 0) {
  23625. this._renderAlphaTest(this._alphaTestSubMeshes);
  23626. }
  23627. var stencilState = engine.getStencilBuffer();
  23628. engine.setStencilBuffer(false);
  23629. // Sprites
  23630. if (renderSprites) {
  23631. this._renderSprites();
  23632. }
  23633. // Particles
  23634. if (renderParticles) {
  23635. this._renderParticles(activeMeshes);
  23636. }
  23637. if (this.onBeforeTransparentRendering) {
  23638. this.onBeforeTransparentRendering();
  23639. }
  23640. // Transparent
  23641. if (this._transparentSubMeshes.length !== 0) {
  23642. this._renderTransparent(this._transparentSubMeshes);
  23643. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23644. }
  23645. // Set back stencil to false in case it changes before the edge renderer.
  23646. engine.setStencilBuffer(false);
  23647. // Edges
  23648. if (this._edgesRenderers.length) {
  23649. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23650. this._edgesRenderers.data[edgesRendererIndex].render();
  23651. }
  23652. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23653. }
  23654. // Restore Stencil state.
  23655. engine.setStencilBuffer(stencilState);
  23656. };
  23657. /**
  23658. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23659. * @param subMeshes The submeshes to render
  23660. */
  23661. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23662. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23663. };
  23664. /**
  23665. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23666. * @param subMeshes The submeshes to render
  23667. */
  23668. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23669. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23670. };
  23671. /**
  23672. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23673. * @param subMeshes The submeshes to render
  23674. */
  23675. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23676. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23677. };
  23678. /**
  23679. * Renders the submeshes in a specified order.
  23680. * @param subMeshes The submeshes to sort before render
  23681. * @param sortCompareFn The comparison function use to sort
  23682. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23683. * @param transparent Specifies to activate blending if true
  23684. */
  23685. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23686. var subIndex = 0;
  23687. var subMesh;
  23688. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23689. for (; subIndex < subMeshes.length; subIndex++) {
  23690. subMesh = subMeshes.data[subIndex];
  23691. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23692. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23693. }
  23694. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23695. if (sortCompareFn) {
  23696. sortedArray.sort(sortCompareFn);
  23697. }
  23698. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23699. subMesh = sortedArray[subIndex];
  23700. if (transparent) {
  23701. var material = subMesh.getMaterial();
  23702. if (material && material.needDepthPrePass) {
  23703. var engine = material.getScene().getEngine();
  23704. engine.setColorWrite(false);
  23705. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23706. subMesh.render(false);
  23707. engine.setColorWrite(true);
  23708. }
  23709. }
  23710. subMesh.render(transparent);
  23711. }
  23712. };
  23713. /**
  23714. * Renders the submeshes in the order they were dispatched (no sort applied).
  23715. * @param subMeshes The submeshes to render
  23716. */
  23717. RenderingGroup.renderUnsorted = function (subMeshes) {
  23718. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23719. var submesh = subMeshes.data[subIndex];
  23720. submesh.render(false);
  23721. }
  23722. };
  23723. /**
  23724. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23725. * are rendered back to front if in the same alpha index.
  23726. *
  23727. * @param a The first submesh
  23728. * @param b The second submesh
  23729. * @returns The result of the comparison
  23730. */
  23731. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23732. // Alpha index first
  23733. if (a._alphaIndex > b._alphaIndex) {
  23734. return 1;
  23735. }
  23736. if (a._alphaIndex < b._alphaIndex) {
  23737. return -1;
  23738. }
  23739. // Then distance to camera
  23740. return RenderingGroup.backToFrontSortCompare(a, b);
  23741. };
  23742. /**
  23743. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23744. * are rendered back to front.
  23745. *
  23746. * @param a The first submesh
  23747. * @param b The second submesh
  23748. * @returns The result of the comparison
  23749. */
  23750. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23751. // Then distance to camera
  23752. if (a._distanceToCamera < b._distanceToCamera) {
  23753. return 1;
  23754. }
  23755. if (a._distanceToCamera > b._distanceToCamera) {
  23756. return -1;
  23757. }
  23758. return 0;
  23759. };
  23760. /**
  23761. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23762. * are rendered front to back (prevent overdraw).
  23763. *
  23764. * @param a The first submesh
  23765. * @param b The second submesh
  23766. * @returns The result of the comparison
  23767. */
  23768. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23769. // Then distance to camera
  23770. if (a._distanceToCamera < b._distanceToCamera) {
  23771. return -1;
  23772. }
  23773. if (a._distanceToCamera > b._distanceToCamera) {
  23774. return 1;
  23775. }
  23776. return 0;
  23777. };
  23778. /**
  23779. * Resets the different lists of submeshes to prepare a new frame.
  23780. */
  23781. RenderingGroup.prototype.prepare = function () {
  23782. this._opaqueSubMeshes.reset();
  23783. this._transparentSubMeshes.reset();
  23784. this._alphaTestSubMeshes.reset();
  23785. this._depthOnlySubMeshes.reset();
  23786. this._particleSystems.reset();
  23787. this._spriteManagers.reset();
  23788. this._edgesRenderers.reset();
  23789. };
  23790. RenderingGroup.prototype.dispose = function () {
  23791. this._opaqueSubMeshes.dispose();
  23792. this._transparentSubMeshes.dispose();
  23793. this._alphaTestSubMeshes.dispose();
  23794. this._depthOnlySubMeshes.dispose();
  23795. this._particleSystems.dispose();
  23796. this._spriteManagers.dispose();
  23797. this._edgesRenderers.dispose();
  23798. };
  23799. /**
  23800. * Inserts the submesh in its correct queue depending on its material.
  23801. * @param subMesh The submesh to dispatch
  23802. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23803. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23804. */
  23805. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23806. // Get mesh and materials if not provided
  23807. if (mesh === undefined) {
  23808. mesh = subMesh.getMesh();
  23809. }
  23810. if (material === undefined) {
  23811. material = subMesh.getMaterial();
  23812. }
  23813. if (material === null || material === undefined) {
  23814. return;
  23815. }
  23816. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23817. this._transparentSubMeshes.push(subMesh);
  23818. }
  23819. else if (material.needAlphaTesting()) { // Alpha test
  23820. if (material.needDepthPrePass) {
  23821. this._depthOnlySubMeshes.push(subMesh);
  23822. }
  23823. this._alphaTestSubMeshes.push(subMesh);
  23824. }
  23825. else {
  23826. if (material.needDepthPrePass) {
  23827. this._depthOnlySubMeshes.push(subMesh);
  23828. }
  23829. this._opaqueSubMeshes.push(subMesh); // Opaque
  23830. }
  23831. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23832. this._edgesRenderers.push(mesh._edgesRenderer);
  23833. }
  23834. };
  23835. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23836. this._spriteManagers.push(spriteManager);
  23837. };
  23838. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23839. this._particleSystems.push(particleSystem);
  23840. };
  23841. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23842. if (this._particleSystems.length === 0) {
  23843. return;
  23844. }
  23845. // Particles
  23846. var activeCamera = this._scene.activeCamera;
  23847. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23848. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23849. var particleSystem = this._particleSystems.data[particleIndex];
  23850. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23851. continue;
  23852. }
  23853. var emitter = particleSystem.emitter;
  23854. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23855. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23856. }
  23857. }
  23858. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23859. };
  23860. RenderingGroup.prototype._renderSprites = function () {
  23861. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23862. return;
  23863. }
  23864. // Sprites
  23865. var activeCamera = this._scene.activeCamera;
  23866. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23867. for (var id = 0; id < this._spriteManagers.length; id++) {
  23868. var spriteManager = this._spriteManagers.data[id];
  23869. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23870. spriteManager.render();
  23871. }
  23872. }
  23873. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23874. };
  23875. return RenderingGroup;
  23876. }());
  23877. BABYLON.RenderingGroup = RenderingGroup;
  23878. })(BABYLON || (BABYLON = {}));
  23879. //# sourceMappingURL=babylon.renderingGroup.js.map
  23880. var BABYLON;
  23881. (function (BABYLON) {
  23882. /**
  23883. * Groups all the scene component constants in one place to ease maintenance.
  23884. * @hidden
  23885. */
  23886. var SceneComponentConstants = /** @class */ (function () {
  23887. function SceneComponentConstants() {
  23888. }
  23889. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23890. SceneComponentConstants.NAME_LAYER = "Layer";
  23891. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23892. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23893. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23894. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23895. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23896. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23897. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23898. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23899. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23900. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23901. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23902. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23903. SceneComponentConstants.NAME_OCTREE = "Octree";
  23904. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23905. SceneComponentConstants.NAME_AUDIO = "Audio";
  23906. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23907. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23908. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23909. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23910. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23911. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23912. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23913. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23914. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23915. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23916. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23917. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23918. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23919. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23920. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23921. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23922. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23923. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23924. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23925. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23926. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23927. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23928. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23929. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23930. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23931. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23932. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23933. return SceneComponentConstants;
  23934. }());
  23935. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23936. /**
  23937. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23938. * @hidden
  23939. */
  23940. var Stage = /** @class */ (function (_super) {
  23941. __extends(Stage, _super);
  23942. /**
  23943. * Hide ctor from the rest of the world.
  23944. * @param items The items to add.
  23945. */
  23946. function Stage(items) {
  23947. return _super.apply(this, items) || this;
  23948. }
  23949. /**
  23950. * Creates a new Stage.
  23951. * @returns A new instance of a Stage
  23952. */
  23953. Stage.Create = function () {
  23954. return Object.create(Stage.prototype);
  23955. };
  23956. /**
  23957. * Registers a step in an ordered way in the targeted stage.
  23958. * @param index Defines the position to register the step in
  23959. * @param component Defines the component attached to the step
  23960. * @param action Defines the action to launch during the step
  23961. */
  23962. Stage.prototype.registerStep = function (index, component, action) {
  23963. var i = 0;
  23964. var maxIndex = Number.MAX_VALUE;
  23965. for (; i < this.length && i < maxIndex; i++) {
  23966. var step = this[i];
  23967. maxIndex = step.index;
  23968. }
  23969. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23970. };
  23971. /**
  23972. * Clears all the steps from the stage.
  23973. */
  23974. Stage.prototype.clear = function () {
  23975. this.length = 0;
  23976. };
  23977. return Stage;
  23978. }(Array));
  23979. BABYLON.Stage = Stage;
  23980. })(BABYLON || (BABYLON = {}));
  23981. //# sourceMappingURL=babylon.sceneComponent.js.map
  23982. var BABYLON;
  23983. (function (BABYLON) {
  23984. /**
  23985. * Base class of the scene acting as a container for the different elements composing a scene.
  23986. * This class is dynamically extended by the different components of the scene increasing
  23987. * flexibility and reducing coupling
  23988. */
  23989. var AbstractScene = /** @class */ (function () {
  23990. function AbstractScene() {
  23991. /**
  23992. * Gets the list of root nodes (ie. nodes with no parent)
  23993. */
  23994. this.rootNodes = new Array();
  23995. /** All of the cameras added to this scene
  23996. * @see http://doc.babylonjs.com/babylon101/cameras
  23997. */
  23998. this.cameras = new Array();
  23999. /**
  24000. * All of the lights added to this scene
  24001. * @see http://doc.babylonjs.com/babylon101/lights
  24002. */
  24003. this.lights = new Array();
  24004. /**
  24005. * All of the (abstract) meshes added to this scene
  24006. */
  24007. this.meshes = new Array();
  24008. /**
  24009. * The list of skeletons added to the scene
  24010. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24011. */
  24012. this.skeletons = new Array();
  24013. /**
  24014. * All of the particle systems added to this scene
  24015. * @see http://doc.babylonjs.com/babylon101/particles
  24016. */
  24017. this.particleSystems = new Array();
  24018. /**
  24019. * Gets a list of Animations associated with the scene
  24020. */
  24021. this.animations = [];
  24022. /**
  24023. * All of the animation groups added to this scene
  24024. * @see http://doc.babylonjs.com/how_to/group
  24025. */
  24026. this.animationGroups = new Array();
  24027. /**
  24028. * All of the multi-materials added to this scene
  24029. * @see http://doc.babylonjs.com/how_to/multi_materials
  24030. */
  24031. this.multiMaterials = new Array();
  24032. /**
  24033. * All of the materials added to this scene
  24034. * @see http://doc.babylonjs.com/babylon101/materials
  24035. */
  24036. this.materials = new Array();
  24037. /**
  24038. * The list of morph target managers added to the scene
  24039. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24040. */
  24041. this.morphTargetManagers = new Array();
  24042. /**
  24043. * The list of geometries used in the scene.
  24044. */
  24045. this.geometries = new Array();
  24046. /**
  24047. * All of the tranform nodes added to this scene
  24048. * @see http://doc.babylonjs.com/how_to/transformnode
  24049. */
  24050. this.transformNodes = new Array();
  24051. /**
  24052. * ActionManagers available on the scene.
  24053. */
  24054. this.actionManagers = new Array();
  24055. /**
  24056. * Textures to keep.
  24057. */
  24058. this.textures = new Array();
  24059. }
  24060. /**
  24061. * Adds a parser in the list of available ones
  24062. * @param name Defines the name of the parser
  24063. * @param parser Defines the parser to add
  24064. */
  24065. AbstractScene.AddParser = function (name, parser) {
  24066. this._BabylonFileParsers[name] = parser;
  24067. };
  24068. /**
  24069. * Gets a general parser from the list of avaialble ones
  24070. * @param name Defines the name of the parser
  24071. * @returns the requested parser or null
  24072. */
  24073. AbstractScene.GetParser = function (name) {
  24074. if (this._BabylonFileParsers[name]) {
  24075. return this._BabylonFileParsers[name];
  24076. }
  24077. return null;
  24078. };
  24079. /**
  24080. * Adds n individual parser in the list of available ones
  24081. * @param name Defines the name of the parser
  24082. * @param parser Defines the parser to add
  24083. */
  24084. AbstractScene.AddIndividualParser = function (name, parser) {
  24085. this._IndividualBabylonFileParsers[name] = parser;
  24086. };
  24087. /**
  24088. * Gets an individual parser from the list of avaialble ones
  24089. * @param name Defines the name of the parser
  24090. * @returns the requested parser or null
  24091. */
  24092. AbstractScene.GetIndividualParser = function (name) {
  24093. if (this._IndividualBabylonFileParsers[name]) {
  24094. return this._IndividualBabylonFileParsers[name];
  24095. }
  24096. return null;
  24097. };
  24098. /**
  24099. * Parser json data and populate both a scene and its associated container object
  24100. * @param jsonData Defines the data to parse
  24101. * @param scene Defines the scene to parse the data for
  24102. * @param container Defines the container attached to the parsing sequence
  24103. * @param rootUrl Defines the root url of the data
  24104. */
  24105. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24106. for (var parserName in this._BabylonFileParsers) {
  24107. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24108. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24109. }
  24110. }
  24111. };
  24112. /**
  24113. * Stores the list of available parsers in the application.
  24114. */
  24115. AbstractScene._BabylonFileParsers = {};
  24116. /**
  24117. * Stores the list of available individual parsers in the application.
  24118. */
  24119. AbstractScene._IndividualBabylonFileParsers = {};
  24120. return AbstractScene;
  24121. }());
  24122. BABYLON.AbstractScene = AbstractScene;
  24123. })(BABYLON || (BABYLON = {}));
  24124. //# sourceMappingURL=babylon.abstractScene.js.map
  24125. var BABYLON;
  24126. (function (BABYLON) {
  24127. /** @hidden */
  24128. var ClickInfo = /** @class */ (function () {
  24129. function ClickInfo() {
  24130. this._singleClick = false;
  24131. this._doubleClick = false;
  24132. this._hasSwiped = false;
  24133. this._ignore = false;
  24134. }
  24135. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24136. get: function () {
  24137. return this._singleClick;
  24138. },
  24139. set: function (b) {
  24140. this._singleClick = b;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24146. get: function () {
  24147. return this._doubleClick;
  24148. },
  24149. set: function (b) {
  24150. this._doubleClick = b;
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24156. get: function () {
  24157. return this._hasSwiped;
  24158. },
  24159. set: function (b) {
  24160. this._hasSwiped = b;
  24161. },
  24162. enumerable: true,
  24163. configurable: true
  24164. });
  24165. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24166. get: function () {
  24167. return this._ignore;
  24168. },
  24169. set: function (b) {
  24170. this._ignore = b;
  24171. },
  24172. enumerable: true,
  24173. configurable: true
  24174. });
  24175. return ClickInfo;
  24176. }());
  24177. /**
  24178. * This class is used by the onRenderingGroupObservable
  24179. */
  24180. var RenderingGroupInfo = /** @class */ (function () {
  24181. function RenderingGroupInfo() {
  24182. }
  24183. return RenderingGroupInfo;
  24184. }());
  24185. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24186. /**
  24187. * Represents a scene to be rendered by the engine.
  24188. * @see http://doc.babylonjs.com/features/scene
  24189. */
  24190. var Scene = /** @class */ (function (_super) {
  24191. __extends(Scene, _super);
  24192. /**
  24193. * Creates a new Scene
  24194. * @param engine defines the engine to use to render this scene
  24195. */
  24196. function Scene(engine) {
  24197. var _this = _super.call(this) || this;
  24198. // Members
  24199. /**
  24200. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24201. */
  24202. _this.autoClear = true;
  24203. /**
  24204. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24205. */
  24206. _this.autoClearDepthAndStencil = true;
  24207. /**
  24208. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24209. */
  24210. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24211. /**
  24212. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24213. */
  24214. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24215. _this._forceWireframe = false;
  24216. _this._forcePointsCloud = false;
  24217. /**
  24218. * Gets or sets a boolean indicating if animations are enabled
  24219. */
  24220. _this.animationsEnabled = true;
  24221. _this._animationPropertiesOverride = null;
  24222. /**
  24223. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24224. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24225. */
  24226. _this.useConstantAnimationDeltaTime = false;
  24227. /**
  24228. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24229. * Please note that it requires to run a ray cast through the scene on every frame
  24230. */
  24231. _this.constantlyUpdateMeshUnderPointer = false;
  24232. /**
  24233. * Defines the HTML cursor to use when hovering over interactive elements
  24234. */
  24235. _this.hoverCursor = "pointer";
  24236. /**
  24237. * Defines the HTML default cursor to use (empty by default)
  24238. */
  24239. _this.defaultCursor = "";
  24240. /**
  24241. * This is used to call preventDefault() on pointer down
  24242. * in order to block unwanted artifacts like system double clicks
  24243. */
  24244. _this.preventDefaultOnPointerDown = true;
  24245. // Metadata
  24246. /**
  24247. * Gets or sets user defined metadata
  24248. */
  24249. _this.metadata = null;
  24250. /**
  24251. * Use this array to add regular expressions used to disable offline support for specific urls
  24252. */
  24253. _this.disableOfflineSupportExceptionRules = new Array();
  24254. /**
  24255. * An event triggered when the scene is disposed.
  24256. */
  24257. _this.onDisposeObservable = new BABYLON.Observable();
  24258. _this._onDisposeObserver = null;
  24259. /**
  24260. * An event triggered before rendering the scene (right after animations and physics)
  24261. */
  24262. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24263. _this._onBeforeRenderObserver = null;
  24264. /**
  24265. * An event triggered after rendering the scene
  24266. */
  24267. _this.onAfterRenderObservable = new BABYLON.Observable();
  24268. _this._onAfterRenderObserver = null;
  24269. /**
  24270. * An event triggered before animating the scene
  24271. */
  24272. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24273. /**
  24274. * An event triggered after animations processing
  24275. */
  24276. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24277. /**
  24278. * An event triggered before draw calls are ready to be sent
  24279. */
  24280. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24281. /**
  24282. * An event triggered after draw calls have been sent
  24283. */
  24284. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24285. /**
  24286. * An event triggered when the scene is ready
  24287. */
  24288. _this.onReadyObservable = new BABYLON.Observable();
  24289. /**
  24290. * An event triggered before rendering a camera
  24291. */
  24292. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24293. _this._onBeforeCameraRenderObserver = null;
  24294. /**
  24295. * An event triggered after rendering a camera
  24296. */
  24297. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24298. _this._onAfterCameraRenderObserver = null;
  24299. /**
  24300. * An event triggered when active meshes evaluation is about to start
  24301. */
  24302. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24303. /**
  24304. * An event triggered when active meshes evaluation is done
  24305. */
  24306. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24307. /**
  24308. * An event triggered when particles rendering is about to start
  24309. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24310. */
  24311. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24312. /**
  24313. * An event triggered when particles rendering is done
  24314. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24315. */
  24316. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24317. /**
  24318. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24319. */
  24320. _this.onDataLoadedObservable = new BABYLON.Observable();
  24321. /**
  24322. * An event triggered when a camera is created
  24323. */
  24324. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24325. /**
  24326. * An event triggered when a camera is removed
  24327. */
  24328. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24329. /**
  24330. * An event triggered when a light is created
  24331. */
  24332. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24333. /**
  24334. * An event triggered when a light is removed
  24335. */
  24336. _this.onLightRemovedObservable = new BABYLON.Observable();
  24337. /**
  24338. * An event triggered when a geometry is created
  24339. */
  24340. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24341. /**
  24342. * An event triggered when a geometry is removed
  24343. */
  24344. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24345. /**
  24346. * An event triggered when a transform node is created
  24347. */
  24348. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24349. /**
  24350. * An event triggered when a transform node is removed
  24351. */
  24352. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24353. /**
  24354. * An event triggered when a mesh is created
  24355. */
  24356. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24357. /**
  24358. * An event triggered when a mesh is removed
  24359. */
  24360. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24361. /**
  24362. * An event triggered when render targets are about to be rendered
  24363. * Can happen multiple times per frame.
  24364. */
  24365. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24366. /**
  24367. * An event triggered when render targets were rendered.
  24368. * Can happen multiple times per frame.
  24369. */
  24370. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24371. /**
  24372. * An event triggered before calculating deterministic simulation step
  24373. */
  24374. _this.onBeforeStepObservable = new BABYLON.Observable();
  24375. /**
  24376. * An event triggered after calculating deterministic simulation step
  24377. */
  24378. _this.onAfterStepObservable = new BABYLON.Observable();
  24379. /**
  24380. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24381. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24382. * 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)
  24383. */
  24384. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24385. /**
  24386. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24387. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24388. * 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)
  24389. */
  24390. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24391. /**
  24392. * This Observable will when a mesh has been imported into the scene.
  24393. */
  24394. _this.onMeshImportedObservable = new BABYLON.Observable();
  24395. // Animations
  24396. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24397. /**
  24398. * 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).
  24399. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24400. */
  24401. _this.onPrePointerObservable = new BABYLON.Observable();
  24402. /**
  24403. * Observable event triggered each time an input event is received from the rendering canvas
  24404. */
  24405. _this.onPointerObservable = new BABYLON.Observable();
  24406. _this._meshPickProceed = false;
  24407. _this._currentPickResult = null;
  24408. _this._previousPickResult = null;
  24409. _this._totalPointersPressed = 0;
  24410. _this._doubleClickOccured = false;
  24411. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24412. _this.cameraToUseForPointers = null;
  24413. _this._pointerX = 0;
  24414. _this._pointerY = 0;
  24415. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24416. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24417. _this._startingPointerTime = 0;
  24418. _this._previousStartingPointerTime = 0;
  24419. _this._pointerCaptures = {};
  24420. // Deterministic lockstep
  24421. _this._timeAccumulator = 0;
  24422. _this._currentStepId = 0;
  24423. _this._currentInternalStep = 0;
  24424. // Keyboard
  24425. /**
  24426. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24427. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24428. */
  24429. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24430. /**
  24431. * Observable event triggered each time an keyboard event is received from the hosting window
  24432. */
  24433. _this.onKeyboardObservable = new BABYLON.Observable();
  24434. // Coordinates system
  24435. _this._useRightHandedSystem = false;
  24436. // Fog
  24437. _this._fogEnabled = true;
  24438. _this._fogMode = Scene.FOGMODE_NONE;
  24439. /**
  24440. * Gets or sets the fog color to use
  24441. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24442. */
  24443. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24444. /**
  24445. * Gets or sets the fog density to use
  24446. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24447. */
  24448. _this.fogDensity = 0.1;
  24449. /**
  24450. * Gets or sets the fog start distance to use
  24451. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24452. */
  24453. _this.fogStart = 0;
  24454. /**
  24455. * Gets or sets the fog end distance to use
  24456. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24457. */
  24458. _this.fogEnd = 1000.0;
  24459. // Lights
  24460. _this._shadowsEnabled = true;
  24461. _this._lightsEnabled = true;
  24462. /** All of the active cameras added to this scene. */
  24463. _this.activeCameras = new Array();
  24464. // Textures
  24465. _this._texturesEnabled = true;
  24466. // Particles
  24467. /**
  24468. * Gets or sets a boolean indicating if particles are enabled on this scene
  24469. */
  24470. _this.particlesEnabled = true;
  24471. // Sprites
  24472. /**
  24473. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24474. */
  24475. _this.spritesEnabled = true;
  24476. // Skeletons
  24477. _this._skeletonsEnabled = true;
  24478. // Lens flares
  24479. /**
  24480. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24481. */
  24482. _this.lensFlaresEnabled = true;
  24483. // Collisions
  24484. /**
  24485. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24486. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24487. */
  24488. _this.collisionsEnabled = true;
  24489. /**
  24490. * Defines the gravity applied to this scene (used only for collisions)
  24491. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24492. */
  24493. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24494. // Postprocesses
  24495. /**
  24496. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24497. */
  24498. _this.postProcessesEnabled = true;
  24499. /**
  24500. * The list of postprocesses added to the scene
  24501. */
  24502. _this.postProcesses = new Array();
  24503. // Customs render targets
  24504. /**
  24505. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24506. */
  24507. _this.renderTargetsEnabled = true;
  24508. /**
  24509. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24510. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24511. */
  24512. _this.dumpNextRenderTargets = false;
  24513. /**
  24514. * The list of user defined render targets added to the scene
  24515. */
  24516. _this.customRenderTargets = new Array();
  24517. /**
  24518. * Gets the list of meshes imported to the scene through SceneLoader
  24519. */
  24520. _this.importedMeshesFiles = new Array();
  24521. // Probes
  24522. /**
  24523. * Gets or sets a boolean indicating if probes are enabled on this scene
  24524. */
  24525. _this.probesEnabled = true;
  24526. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24527. // Procedural textures
  24528. /**
  24529. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24530. */
  24531. _this.proceduralTexturesEnabled = true;
  24532. // Performance counters
  24533. _this._totalVertices = new BABYLON.PerfCounter();
  24534. /** @hidden */
  24535. _this._activeIndices = new BABYLON.PerfCounter();
  24536. /** @hidden */
  24537. _this._activeParticles = new BABYLON.PerfCounter();
  24538. /** @hidden */
  24539. _this._activeBones = new BABYLON.PerfCounter();
  24540. _this._animationTime = 0;
  24541. /**
  24542. * Gets or sets a general scale for animation speed
  24543. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24544. */
  24545. _this.animationTimeScale = 1;
  24546. _this._renderId = 0;
  24547. _this._frameId = 0;
  24548. _this._executeWhenReadyTimeoutId = -1;
  24549. _this._intermediateRendering = false;
  24550. _this._viewUpdateFlag = -1;
  24551. _this._projectionUpdateFlag = -1;
  24552. _this._alternateViewUpdateFlag = -1;
  24553. _this._alternateProjectionUpdateFlag = -1;
  24554. /** @hidden */
  24555. _this._toBeDisposed = new Array(256);
  24556. _this._activeRequests = new Array();
  24557. _this._pendingData = new Array();
  24558. _this._isDisposed = false;
  24559. /**
  24560. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24561. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24562. */
  24563. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24564. _this._activeMeshes = new BABYLON.SmartArray(256);
  24565. _this._processedMaterials = new BABYLON.SmartArray(256);
  24566. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24567. /** @hidden */
  24568. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24569. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24570. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24571. /** @hidden */
  24572. _this._activeAnimatables = new Array();
  24573. _this._transformMatrix = BABYLON.Matrix.Zero();
  24574. _this._useAlternateCameraConfiguration = false;
  24575. _this._alternateRendering = false;
  24576. /**
  24577. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24578. * This is useful if there are more lights that the maximum simulteanous authorized
  24579. */
  24580. _this.requireLightSorting = false;
  24581. /**
  24582. * @hidden
  24583. * Backing store of defined scene components.
  24584. */
  24585. _this._components = [];
  24586. /**
  24587. * @hidden
  24588. * Backing store of defined scene components.
  24589. */
  24590. _this._serializableComponents = [];
  24591. /**
  24592. * List of components to register on the next registration step.
  24593. */
  24594. _this._transientComponents = [];
  24595. /**
  24596. * @hidden
  24597. * Defines the actions happening before camera updates.
  24598. */
  24599. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24600. /**
  24601. * @hidden
  24602. * Defines the actions happening before clear the canvas.
  24603. */
  24604. _this._beforeClearStage = BABYLON.Stage.Create();
  24605. /**
  24606. * @hidden
  24607. * Defines the actions when collecting render targets for the frame.
  24608. */
  24609. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24610. /**
  24611. * @hidden
  24612. * Defines the actions happening for one camera in the frame.
  24613. */
  24614. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24615. /**
  24616. * @hidden
  24617. * Defines the actions happening during the per mesh ready checks.
  24618. */
  24619. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24620. /**
  24621. * @hidden
  24622. * Defines the actions happening before evaluate active mesh checks.
  24623. */
  24624. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24625. /**
  24626. * @hidden
  24627. * Defines the actions happening during the evaluate sub mesh checks.
  24628. */
  24629. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24630. /**
  24631. * @hidden
  24632. * Defines the actions happening during the active mesh stage.
  24633. */
  24634. _this._activeMeshStage = BABYLON.Stage.Create();
  24635. /**
  24636. * @hidden
  24637. * Defines the actions happening during the per camera render target step.
  24638. */
  24639. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24640. /**
  24641. * @hidden
  24642. * Defines the actions happening just before the active camera is drawing.
  24643. */
  24644. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24645. /**
  24646. * @hidden
  24647. * Defines the actions happening just before a rendering group is drawing.
  24648. */
  24649. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24650. /**
  24651. * @hidden
  24652. * Defines the actions happening just before a mesh is drawing.
  24653. */
  24654. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24655. /**
  24656. * @hidden
  24657. * Defines the actions happening just after a mesh has been drawn.
  24658. */
  24659. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24660. /**
  24661. * @hidden
  24662. * Defines the actions happening just after a rendering group has been drawn.
  24663. */
  24664. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24665. /**
  24666. * @hidden
  24667. * Defines the actions happening just after the active camera has been drawn.
  24668. */
  24669. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24670. /**
  24671. * @hidden
  24672. * Defines the actions happening just after rendering all cameras and computing intersections.
  24673. */
  24674. _this._afterRenderStage = BABYLON.Stage.Create();
  24675. /**
  24676. * @hidden
  24677. * Defines the actions happening when a pointer move event happens.
  24678. */
  24679. _this._pointerMoveStage = BABYLON.Stage.Create();
  24680. /**
  24681. * @hidden
  24682. * Defines the actions happening when a pointer down event happens.
  24683. */
  24684. _this._pointerDownStage = BABYLON.Stage.Create();
  24685. /**
  24686. * @hidden
  24687. * Defines the actions happening when a pointer up event happens.
  24688. */
  24689. _this._pointerUpStage = BABYLON.Stage.Create();
  24690. _this._defaultMeshCandidates = {
  24691. data: [],
  24692. length: 0
  24693. };
  24694. _this._defaultSubMeshCandidates = {
  24695. data: [],
  24696. length: 0
  24697. };
  24698. _this._activeMeshesFrozen = false;
  24699. /** @hidden */
  24700. _this._allowPostProcessClearColor = true;
  24701. /**
  24702. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24703. */
  24704. _this.getDeterministicFrameTime = function () {
  24705. return 1000.0 / 60.0; // frame time in ms
  24706. };
  24707. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24708. _this._blockMaterialDirtyMechanism = false;
  24709. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24710. _this._engine.scenes.push(_this);
  24711. _this._uid = null;
  24712. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24713. if (BABYLON.PostProcessManager) {
  24714. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24715. }
  24716. if (BABYLON.Tools.IsWindowObjectExist()) {
  24717. _this.attachControl();
  24718. }
  24719. //collision coordinator initialization. For now legacy per default.
  24720. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24721. // Uniform Buffer
  24722. _this._createUbo();
  24723. // Default Image processing definition
  24724. if (BABYLON.ImageProcessingConfiguration) {
  24725. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24726. }
  24727. _this.setDefaultCandidateProviders();
  24728. return _this;
  24729. }
  24730. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24731. /**
  24732. * Texture used in all pbr material as the reflection texture.
  24733. * As in the majority of the scene they are the same (exception for multi room and so on),
  24734. * this is easier to reference from here than from all the materials.
  24735. */
  24736. get: function () {
  24737. return this._environmentTexture;
  24738. },
  24739. /**
  24740. * Texture used in all pbr material as the reflection texture.
  24741. * As in the majority of the scene they are the same (exception for multi room and so on),
  24742. * this is easier to set here than in all the materials.
  24743. */
  24744. set: function (value) {
  24745. if (this._environmentTexture === value) {
  24746. return;
  24747. }
  24748. this._environmentTexture = value;
  24749. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24755. /**
  24756. * Default image processing configuration used either in the rendering
  24757. * Forward main pass or through the imageProcessingPostProcess if present.
  24758. * As in the majority of the scene they are the same (exception for multi camera),
  24759. * this is easier to reference from here than from all the materials and post process.
  24760. *
  24761. * No setter as we it is a shared configuration, you can set the values instead.
  24762. */
  24763. get: function () {
  24764. return this._imageProcessingConfiguration;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24770. get: function () {
  24771. return this._forceWireframe;
  24772. },
  24773. /**
  24774. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24775. */
  24776. set: function (value) {
  24777. if (this._forceWireframe === value) {
  24778. return;
  24779. }
  24780. this._forceWireframe = value;
  24781. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24787. get: function () {
  24788. return this._forcePointsCloud;
  24789. },
  24790. /**
  24791. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24792. */
  24793. set: function (value) {
  24794. if (this._forcePointsCloud === value) {
  24795. return;
  24796. }
  24797. this._forcePointsCloud = value;
  24798. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24804. /**
  24805. * Gets or sets the animation properties override
  24806. */
  24807. get: function () {
  24808. return this._animationPropertiesOverride;
  24809. },
  24810. set: function (value) {
  24811. this._animationPropertiesOverride = value;
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  24815. });
  24816. Object.defineProperty(Scene.prototype, "onDispose", {
  24817. /** Sets a function to be executed when this scene is disposed. */
  24818. set: function (callback) {
  24819. if (this._onDisposeObserver) {
  24820. this.onDisposeObservable.remove(this._onDisposeObserver);
  24821. }
  24822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(Scene.prototype, "beforeRender", {
  24828. /** Sets a function to be executed before rendering this scene */
  24829. set: function (callback) {
  24830. if (this._onBeforeRenderObserver) {
  24831. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24832. }
  24833. if (callback) {
  24834. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24835. }
  24836. },
  24837. enumerable: true,
  24838. configurable: true
  24839. });
  24840. Object.defineProperty(Scene.prototype, "afterRender", {
  24841. /** Sets a function to be executed after rendering this scene */
  24842. set: function (callback) {
  24843. if (this._onAfterRenderObserver) {
  24844. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24845. }
  24846. if (callback) {
  24847. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24848. }
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24854. /** Sets a function to be executed before rendering a camera*/
  24855. set: function (callback) {
  24856. if (this._onBeforeCameraRenderObserver) {
  24857. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24858. }
  24859. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24865. /** Sets a function to be executed after rendering a camera*/
  24866. set: function (callback) {
  24867. if (this._onAfterCameraRenderObserver) {
  24868. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24869. }
  24870. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24876. /**
  24877. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24878. */
  24879. get: function () {
  24880. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24886. get: function () {
  24887. return this._useRightHandedSystem;
  24888. },
  24889. /**
  24890. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24891. */
  24892. set: function (value) {
  24893. if (this._useRightHandedSystem === value) {
  24894. return;
  24895. }
  24896. this._useRightHandedSystem = value;
  24897. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. /**
  24903. * Sets the step Id used by deterministic lock step
  24904. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24905. * @param newStepId defines the step Id
  24906. */
  24907. Scene.prototype.setStepId = function (newStepId) {
  24908. this._currentStepId = newStepId;
  24909. };
  24910. ;
  24911. /**
  24912. * Gets the step Id used by deterministic lock step
  24913. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24914. * @returns the step Id
  24915. */
  24916. Scene.prototype.getStepId = function () {
  24917. return this._currentStepId;
  24918. };
  24919. ;
  24920. /**
  24921. * Gets the internal step used by deterministic lock step
  24922. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24923. * @returns the internal step
  24924. */
  24925. Scene.prototype.getInternalStep = function () {
  24926. return this._currentInternalStep;
  24927. };
  24928. ;
  24929. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24930. get: function () {
  24931. return this._fogEnabled;
  24932. },
  24933. /**
  24934. * Gets or sets a boolean indicating if fog is enabled on this scene
  24935. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24936. */
  24937. set: function (value) {
  24938. if (this._fogEnabled === value) {
  24939. return;
  24940. }
  24941. this._fogEnabled = value;
  24942. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. Object.defineProperty(Scene.prototype, "fogMode", {
  24948. get: function () {
  24949. return this._fogMode;
  24950. },
  24951. /**
  24952. * Gets or sets the fog mode to use
  24953. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24954. */
  24955. set: function (value) {
  24956. if (this._fogMode === value) {
  24957. return;
  24958. }
  24959. this._fogMode = value;
  24960. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24966. get: function () {
  24967. return this._shadowsEnabled;
  24968. },
  24969. /**
  24970. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24971. */
  24972. set: function (value) {
  24973. if (this._shadowsEnabled === value) {
  24974. return;
  24975. }
  24976. this._shadowsEnabled = value;
  24977. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24978. },
  24979. enumerable: true,
  24980. configurable: true
  24981. });
  24982. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24983. get: function () {
  24984. return this._lightsEnabled;
  24985. },
  24986. /**
  24987. * Gets or sets a boolean indicating if lights are enabled on this scene
  24988. */
  24989. set: function (value) {
  24990. if (this._lightsEnabled === value) {
  24991. return;
  24992. }
  24993. this._lightsEnabled = value;
  24994. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25000. /** The default material used on meshes when no material is affected */
  25001. get: function () {
  25002. if (!this._defaultMaterial) {
  25003. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25004. }
  25005. return this._defaultMaterial;
  25006. },
  25007. /** The default material used on meshes when no material is affected */
  25008. set: function (value) {
  25009. this._defaultMaterial = value;
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25015. get: function () {
  25016. return this._texturesEnabled;
  25017. },
  25018. /**
  25019. * Gets or sets a boolean indicating if textures are enabled on this scene
  25020. */
  25021. set: function (value) {
  25022. if (this._texturesEnabled === value) {
  25023. return;
  25024. }
  25025. this._texturesEnabled = value;
  25026. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25027. },
  25028. enumerable: true,
  25029. configurable: true
  25030. });
  25031. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25032. get: function () {
  25033. return this._skeletonsEnabled;
  25034. },
  25035. /**
  25036. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25037. */
  25038. set: function (value) {
  25039. if (this._skeletonsEnabled === value) {
  25040. return;
  25041. }
  25042. this._skeletonsEnabled = value;
  25043. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25049. /** @hidden */
  25050. get: function () {
  25051. return this._alternateRendering;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25057. /**
  25058. * Gets the list of frustum planes (built from the active camera)
  25059. */
  25060. get: function () {
  25061. return this._frustumPlanes;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. /**
  25067. * Registers the transient components if needed.
  25068. */
  25069. Scene.prototype._registerTransientComponents = function () {
  25070. // Register components that have been associated lately to the scene.
  25071. if (this._transientComponents.length > 0) {
  25072. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25073. var component = _a[_i];
  25074. component.register();
  25075. }
  25076. this._transientComponents = [];
  25077. }
  25078. };
  25079. /**
  25080. * @hidden
  25081. * Add a component to the scene.
  25082. * Note that the ccomponent could be registered on th next frame if this is called after
  25083. * the register component stage.
  25084. * @param component Defines the component to add to the scene
  25085. */
  25086. Scene.prototype._addComponent = function (component) {
  25087. this._components.push(component);
  25088. this._transientComponents.push(component);
  25089. var serializableComponent = component;
  25090. if (serializableComponent.addFromContainer) {
  25091. this._serializableComponents.push(serializableComponent);
  25092. }
  25093. };
  25094. /**
  25095. * @hidden
  25096. * Gets a component from the scene.
  25097. * @param name defines the name of the component to retrieve
  25098. * @returns the component or null if not present
  25099. */
  25100. Scene.prototype._getComponent = function (name) {
  25101. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25102. var component = _a[_i];
  25103. if (component.name === name) {
  25104. return component;
  25105. }
  25106. }
  25107. return null;
  25108. };
  25109. /**
  25110. * @hidden
  25111. */
  25112. Scene.prototype._getDefaultMeshCandidates = function () {
  25113. this._defaultMeshCandidates.data = this.meshes;
  25114. this._defaultMeshCandidates.length = this.meshes.length;
  25115. return this._defaultMeshCandidates;
  25116. };
  25117. /**
  25118. * @hidden
  25119. */
  25120. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25121. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25122. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25123. return this._defaultSubMeshCandidates;
  25124. };
  25125. /**
  25126. * Sets the default candidate providers for the scene.
  25127. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25128. * and getCollidingSubMeshCandidates to their default function
  25129. */
  25130. Scene.prototype.setDefaultCandidateProviders = function () {
  25131. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25132. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25133. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25134. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25135. };
  25136. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25137. /**
  25138. * Gets a boolean indicating if collisions are processed on a web worker
  25139. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25140. */
  25141. get: function () {
  25142. return this._workerCollisions;
  25143. },
  25144. set: function (enabled) {
  25145. if (!BABYLON.CollisionCoordinatorLegacy) {
  25146. return;
  25147. }
  25148. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25149. this._workerCollisions = enabled;
  25150. if (this.collisionCoordinator) {
  25151. this.collisionCoordinator.destroy();
  25152. }
  25153. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25154. this.collisionCoordinator.init(this);
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25160. /**
  25161. * Gets the mesh that is currently under the pointer
  25162. */
  25163. get: function () {
  25164. return this._pointerOverMesh;
  25165. },
  25166. enumerable: true,
  25167. configurable: true
  25168. });
  25169. Object.defineProperty(Scene.prototype, "pointerX", {
  25170. /**
  25171. * Gets the current on-screen X position of the pointer
  25172. */
  25173. get: function () {
  25174. return this._pointerX;
  25175. },
  25176. enumerable: true,
  25177. configurable: true
  25178. });
  25179. Object.defineProperty(Scene.prototype, "pointerY", {
  25180. /**
  25181. * Gets the current on-screen Y position of the pointer
  25182. */
  25183. get: function () {
  25184. return this._pointerY;
  25185. },
  25186. enumerable: true,
  25187. configurable: true
  25188. });
  25189. /**
  25190. * Gets the cached material (ie. the latest rendered one)
  25191. * @returns the cached material
  25192. */
  25193. Scene.prototype.getCachedMaterial = function () {
  25194. return this._cachedMaterial;
  25195. };
  25196. /**
  25197. * Gets the cached effect (ie. the latest rendered one)
  25198. * @returns the cached effect
  25199. */
  25200. Scene.prototype.getCachedEffect = function () {
  25201. return this._cachedEffect;
  25202. };
  25203. /**
  25204. * Gets the cached visibility state (ie. the latest rendered one)
  25205. * @returns the cached visibility state
  25206. */
  25207. Scene.prototype.getCachedVisibility = function () {
  25208. return this._cachedVisibility;
  25209. };
  25210. /**
  25211. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25212. * @param material defines the current material
  25213. * @param effect defines the current effect
  25214. * @param visibility defines the current visibility state
  25215. * @returns true if one parameter is not cached
  25216. */
  25217. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25218. if (visibility === void 0) { visibility = 1; }
  25219. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25220. };
  25221. /**
  25222. * Gets the engine associated with the scene
  25223. * @returns an Engine
  25224. */
  25225. Scene.prototype.getEngine = function () {
  25226. return this._engine;
  25227. };
  25228. /**
  25229. * Gets the total number of vertices rendered per frame
  25230. * @returns the total number of vertices rendered per frame
  25231. */
  25232. Scene.prototype.getTotalVertices = function () {
  25233. return this._totalVertices.current;
  25234. };
  25235. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25236. /**
  25237. * Gets the performance counter for total vertices
  25238. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25239. */
  25240. get: function () {
  25241. return this._totalVertices;
  25242. },
  25243. enumerable: true,
  25244. configurable: true
  25245. });
  25246. /**
  25247. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25248. * @returns the total number of active indices rendered per frame
  25249. */
  25250. Scene.prototype.getActiveIndices = function () {
  25251. return this._activeIndices.current;
  25252. };
  25253. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25254. /**
  25255. * Gets the performance counter for active indices
  25256. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25257. */
  25258. get: function () {
  25259. return this._activeIndices;
  25260. },
  25261. enumerable: true,
  25262. configurable: true
  25263. });
  25264. /**
  25265. * Gets the total number of active particles rendered per frame
  25266. * @returns the total number of active particles rendered per frame
  25267. */
  25268. Scene.prototype.getActiveParticles = function () {
  25269. return this._activeParticles.current;
  25270. };
  25271. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25272. /**
  25273. * Gets the performance counter for active particles
  25274. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25275. */
  25276. get: function () {
  25277. return this._activeParticles;
  25278. },
  25279. enumerable: true,
  25280. configurable: true
  25281. });
  25282. /**
  25283. * Gets the total number of active bones rendered per frame
  25284. * @returns the total number of active bones rendered per frame
  25285. */
  25286. Scene.prototype.getActiveBones = function () {
  25287. return this._activeBones.current;
  25288. };
  25289. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25290. /**
  25291. * Gets the performance counter for active bones
  25292. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25293. */
  25294. get: function () {
  25295. return this._activeBones;
  25296. },
  25297. enumerable: true,
  25298. configurable: true
  25299. });
  25300. /** @hidden */
  25301. Scene.prototype.getInterFramePerfCounter = function () {
  25302. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25303. return 0;
  25304. };
  25305. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25306. /** @hidden */
  25307. get: function () {
  25308. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25309. return null;
  25310. },
  25311. enumerable: true,
  25312. configurable: true
  25313. });
  25314. /** @hidden */
  25315. Scene.prototype.getLastFrameDuration = function () {
  25316. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25317. return 0;
  25318. };
  25319. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25320. /** @hidden */
  25321. get: function () {
  25322. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25323. return null;
  25324. },
  25325. enumerable: true,
  25326. configurable: true
  25327. });
  25328. /** @hidden */
  25329. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25330. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25331. return 0;
  25332. };
  25333. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25334. /** @hidden */
  25335. get: function () {
  25336. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25337. return null;
  25338. },
  25339. enumerable: true,
  25340. configurable: true
  25341. });
  25342. /**
  25343. * Gets the array of active meshes
  25344. * @returns an array of AbstractMesh
  25345. */
  25346. Scene.prototype.getActiveMeshes = function () {
  25347. return this._activeMeshes;
  25348. };
  25349. /** @hidden */
  25350. Scene.prototype.getRenderTargetsDuration = function () {
  25351. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25352. return 0;
  25353. };
  25354. /** @hidden */
  25355. Scene.prototype.getRenderDuration = function () {
  25356. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25357. return 0;
  25358. };
  25359. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25360. /** @hidden */
  25361. get: function () {
  25362. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25363. return null;
  25364. },
  25365. enumerable: true,
  25366. configurable: true
  25367. });
  25368. /** @hidden */
  25369. Scene.prototype.getParticlesDuration = function () {
  25370. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25371. return 0;
  25372. };
  25373. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25374. /** @hidden */
  25375. get: function () {
  25376. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25377. return null;
  25378. },
  25379. enumerable: true,
  25380. configurable: true
  25381. });
  25382. /** @hidden */
  25383. Scene.prototype.getSpritesDuration = function () {
  25384. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25385. return 0;
  25386. };
  25387. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25388. /** @hidden */
  25389. get: function () {
  25390. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25391. return null;
  25392. },
  25393. enumerable: true,
  25394. configurable: true
  25395. });
  25396. /**
  25397. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25398. * @returns a number
  25399. */
  25400. Scene.prototype.getAnimationRatio = function () {
  25401. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25402. };
  25403. /**
  25404. * Gets an unique Id for the current render phase
  25405. * @returns a number
  25406. */
  25407. Scene.prototype.getRenderId = function () {
  25408. return this._renderId;
  25409. };
  25410. /**
  25411. * Gets an unique Id for the current frame
  25412. * @returns a number
  25413. */
  25414. Scene.prototype.getFrameId = function () {
  25415. return this._frameId;
  25416. };
  25417. /** Call this function if you want to manually increment the render Id*/
  25418. Scene.prototype.incrementRenderId = function () {
  25419. this._renderId++;
  25420. };
  25421. Scene.prototype._updatePointerPosition = function (evt) {
  25422. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25423. if (!canvasRect) {
  25424. return;
  25425. }
  25426. this._pointerX = evt.clientX - canvasRect.left;
  25427. this._pointerY = evt.clientY - canvasRect.top;
  25428. this._unTranslatedPointerX = this._pointerX;
  25429. this._unTranslatedPointerY = this._pointerY;
  25430. };
  25431. Scene.prototype._createUbo = function () {
  25432. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25433. this._sceneUbo.addUniform("viewProjection", 16);
  25434. this._sceneUbo.addUniform("view", 16);
  25435. };
  25436. Scene.prototype._createAlternateUbo = function () {
  25437. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25438. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25439. this._alternateSceneUbo.addUniform("view", 16);
  25440. };
  25441. // Pointers handling
  25442. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25443. if (pointerInfo.pickInfo) {
  25444. if (!pointerInfo.pickInfo.ray) {
  25445. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25446. }
  25447. }
  25448. };
  25449. /**
  25450. * Use this method to simulate a pointer move on a mesh
  25451. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25452. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25453. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25454. * @returns the current scene
  25455. */
  25456. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25457. var evt = new PointerEvent("pointermove", pointerEventInit);
  25458. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25459. return this;
  25460. }
  25461. return this._processPointerMove(pickResult, evt);
  25462. };
  25463. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25464. var canvas = this._engine.getRenderingCanvas();
  25465. if (!canvas) {
  25466. return this;
  25467. }
  25468. // Restore pointer
  25469. canvas.style.cursor = this.defaultCursor;
  25470. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25471. if (isMeshPicked) {
  25472. this.setPointerOverMesh(pickResult.pickedMesh);
  25473. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25474. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25475. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25476. }
  25477. else {
  25478. canvas.style.cursor = this.hoverCursor;
  25479. }
  25480. }
  25481. }
  25482. else {
  25483. this.setPointerOverMesh(null);
  25484. }
  25485. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25486. var step = _a[_i];
  25487. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25488. }
  25489. if (pickResult) {
  25490. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25491. if (this.onPointerMove) {
  25492. this.onPointerMove(evt, pickResult, type);
  25493. }
  25494. if (this.onPointerObservable.hasObservers()) {
  25495. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25496. this._setRayOnPointerInfo(pi);
  25497. this.onPointerObservable.notifyObservers(pi, type);
  25498. }
  25499. }
  25500. return this;
  25501. };
  25502. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25503. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25504. if (pickResult) {
  25505. pi.ray = pickResult.ray;
  25506. }
  25507. this.onPrePointerObservable.notifyObservers(pi, type);
  25508. if (pi.skipOnPointerObservable) {
  25509. return true;
  25510. }
  25511. else {
  25512. return false;
  25513. }
  25514. };
  25515. /**
  25516. * Use this method to simulate a pointer down on a mesh
  25517. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25518. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25519. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25520. * @returns the current scene
  25521. */
  25522. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25523. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25524. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25525. return this;
  25526. }
  25527. return this._processPointerDown(pickResult, evt);
  25528. };
  25529. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25530. var _this = this;
  25531. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25532. this._pickedDownMesh = pickResult.pickedMesh;
  25533. var actionManager = pickResult.pickedMesh.actionManager;
  25534. if (actionManager) {
  25535. if (actionManager.hasPickTriggers) {
  25536. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25537. switch (evt.button) {
  25538. case 0:
  25539. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25540. break;
  25541. case 1:
  25542. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25543. break;
  25544. case 2:
  25545. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25546. break;
  25547. }
  25548. }
  25549. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25550. window.setTimeout(function () {
  25551. 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);
  25552. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25553. if (_this._totalPointersPressed !== 0 &&
  25554. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25555. !_this._isPointerSwiping()) {
  25556. _this._startingPointerTime = 0;
  25557. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25558. }
  25559. }
  25560. }, Scene.LongPressDelay);
  25561. }
  25562. }
  25563. }
  25564. else {
  25565. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25566. var step = _a[_i];
  25567. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25568. }
  25569. }
  25570. if (pickResult) {
  25571. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25572. if (this.onPointerDown) {
  25573. this.onPointerDown(evt, pickResult, type);
  25574. }
  25575. if (this.onPointerObservable.hasObservers()) {
  25576. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25577. this._setRayOnPointerInfo(pi);
  25578. this.onPointerObservable.notifyObservers(pi, type);
  25579. }
  25580. }
  25581. return this;
  25582. };
  25583. /**
  25584. * Use this method to simulate a pointer up on a mesh
  25585. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25586. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25587. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25588. * @returns the current scene
  25589. */
  25590. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25591. var evt = new PointerEvent("pointerup", pointerEventInit);
  25592. var clickInfo = new ClickInfo();
  25593. clickInfo.singleClick = true;
  25594. clickInfo.ignore = true;
  25595. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25596. return this;
  25597. }
  25598. return this._processPointerUp(pickResult, evt, clickInfo);
  25599. };
  25600. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25601. if (pickResult && pickResult && pickResult.pickedMesh) {
  25602. this._pickedUpMesh = pickResult.pickedMesh;
  25603. if (this._pickedDownMesh === this._pickedUpMesh) {
  25604. if (this.onPointerPick) {
  25605. this.onPointerPick(evt, pickResult);
  25606. }
  25607. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25608. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25609. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25610. this._setRayOnPointerInfo(pi);
  25611. this.onPointerObservable.notifyObservers(pi, type_1);
  25612. }
  25613. }
  25614. if (pickResult.pickedMesh.actionManager) {
  25615. if (clickInfo.ignore) {
  25616. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25617. }
  25618. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25619. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25620. }
  25621. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25622. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25623. }
  25624. }
  25625. }
  25626. else {
  25627. if (!clickInfo.ignore) {
  25628. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25629. var step = _a[_i];
  25630. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25631. }
  25632. }
  25633. }
  25634. if (this._pickedDownMesh &&
  25635. this._pickedDownMesh.actionManager &&
  25636. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25637. this._pickedDownMesh !== this._pickedUpMesh) {
  25638. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25639. }
  25640. var type = BABYLON.PointerEventTypes.POINTERUP;
  25641. if (this.onPointerObservable.hasObservers()) {
  25642. if (!clickInfo.ignore) {
  25643. if (!clickInfo.hasSwiped) {
  25644. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25645. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25646. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25647. this._setRayOnPointerInfo(pi);
  25648. this.onPointerObservable.notifyObservers(pi, type_2);
  25649. }
  25650. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25651. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25652. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25653. this._setRayOnPointerInfo(pi);
  25654. this.onPointerObservable.notifyObservers(pi, type_3);
  25655. }
  25656. }
  25657. }
  25658. else {
  25659. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25660. this._setRayOnPointerInfo(pi);
  25661. this.onPointerObservable.notifyObservers(pi, type);
  25662. }
  25663. }
  25664. if (this.onPointerUp) {
  25665. this.onPointerUp(evt, pickResult, type);
  25666. }
  25667. return this;
  25668. };
  25669. /**
  25670. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25671. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25672. * @returns true if the pointer was captured
  25673. */
  25674. Scene.prototype.isPointerCaptured = function (pointerId) {
  25675. if (pointerId === void 0) { pointerId = 0; }
  25676. return this._pointerCaptures[pointerId];
  25677. };
  25678. /** @hidden */
  25679. Scene.prototype._isPointerSwiping = function () {
  25680. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25681. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25682. };
  25683. /**
  25684. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25685. * @param attachUp defines if you want to attach events to pointerup
  25686. * @param attachDown defines if you want to attach events to pointerdown
  25687. * @param attachMove defines if you want to attach events to pointermove
  25688. */
  25689. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25690. var _this = this;
  25691. if (attachUp === void 0) { attachUp = true; }
  25692. if (attachDown === void 0) { attachDown = true; }
  25693. if (attachMove === void 0) { attachMove = true; }
  25694. this._initActionManager = function (act, clickInfo) {
  25695. if (!_this._meshPickProceed) {
  25696. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25697. _this._currentPickResult = pickResult;
  25698. if (pickResult) {
  25699. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25700. }
  25701. _this._meshPickProceed = true;
  25702. }
  25703. return act;
  25704. };
  25705. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25706. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25707. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25708. btn !== _this._previousButtonPressed) {
  25709. _this._doubleClickOccured = false;
  25710. clickInfo.singleClick = true;
  25711. clickInfo.ignore = false;
  25712. cb(clickInfo, _this._currentPickResult);
  25713. }
  25714. };
  25715. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25716. var clickInfo = new ClickInfo();
  25717. _this._currentPickResult = null;
  25718. var act = null;
  25719. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25720. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25721. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25722. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25723. act = _this._initActionManager(act, clickInfo);
  25724. if (act)
  25725. checkPicking = act.hasPickTriggers;
  25726. }
  25727. if (checkPicking) {
  25728. var btn = evt.button;
  25729. clickInfo.hasSwiped = _this._isPointerSwiping();
  25730. if (!clickInfo.hasSwiped) {
  25731. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25732. if (!checkSingleClickImmediately) {
  25733. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25734. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25735. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25736. act = _this._initActionManager(act, clickInfo);
  25737. if (act)
  25738. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25739. }
  25740. }
  25741. if (checkSingleClickImmediately) {
  25742. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25743. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25744. btn !== _this._previousButtonPressed) {
  25745. clickInfo.singleClick = true;
  25746. cb(clickInfo, _this._currentPickResult);
  25747. }
  25748. }
  25749. // at least one double click is required to be check and exclusive double click is enabled
  25750. else {
  25751. // wait that no double click has been raised during the double click delay
  25752. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25753. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25754. }
  25755. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25756. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25757. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25758. act = _this._initActionManager(act, clickInfo);
  25759. if (act)
  25760. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25761. }
  25762. if (checkDoubleClick) {
  25763. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25764. if (btn === _this._previousButtonPressed &&
  25765. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25766. !_this._doubleClickOccured) {
  25767. // pointer has not moved for 2 clicks, it's a double click
  25768. if (!clickInfo.hasSwiped &&
  25769. !_this._isPointerSwiping()) {
  25770. _this._previousStartingPointerTime = 0;
  25771. _this._doubleClickOccured = true;
  25772. clickInfo.doubleClick = true;
  25773. clickInfo.ignore = false;
  25774. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25775. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25776. }
  25777. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25778. cb(clickInfo, _this._currentPickResult);
  25779. }
  25780. // if the two successive clicks are too far, it's just two simple clicks
  25781. else {
  25782. _this._doubleClickOccured = false;
  25783. _this._previousStartingPointerTime = _this._startingPointerTime;
  25784. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25785. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25786. _this._previousButtonPressed = btn;
  25787. if (Scene.ExclusiveDoubleClickMode) {
  25788. if (_this._previousDelayedSimpleClickTimeout) {
  25789. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25790. }
  25791. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25792. cb(clickInfo, _this._previousPickResult);
  25793. }
  25794. else {
  25795. cb(clickInfo, _this._currentPickResult);
  25796. }
  25797. }
  25798. }
  25799. // just the first click of the double has been raised
  25800. else {
  25801. _this._doubleClickOccured = false;
  25802. _this._previousStartingPointerTime = _this._startingPointerTime;
  25803. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25804. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25805. _this._previousButtonPressed = btn;
  25806. }
  25807. }
  25808. }
  25809. }
  25810. clickInfo.ignore = true;
  25811. cb(clickInfo, _this._currentPickResult);
  25812. };
  25813. this._onPointerMove = function (evt) {
  25814. _this._updatePointerPosition(evt);
  25815. // PreObservable support
  25816. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25817. return;
  25818. }
  25819. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25820. return;
  25821. }
  25822. if (!_this.pointerMovePredicate) {
  25823. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25824. }
  25825. // Meshes
  25826. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25827. _this._processPointerMove(pickResult, evt);
  25828. };
  25829. this._onPointerDown = function (evt) {
  25830. _this._totalPointersPressed++;
  25831. _this._pickedDownMesh = null;
  25832. _this._meshPickProceed = false;
  25833. _this._updatePointerPosition(evt);
  25834. if (_this.preventDefaultOnPointerDown && canvas) {
  25835. evt.preventDefault();
  25836. canvas.focus();
  25837. }
  25838. // PreObservable support
  25839. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25840. return;
  25841. }
  25842. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25843. return;
  25844. }
  25845. _this._pointerCaptures[evt.pointerId] = true;
  25846. _this._startingPointerPosition.x = _this._pointerX;
  25847. _this._startingPointerPosition.y = _this._pointerY;
  25848. _this._startingPointerTime = Date.now();
  25849. if (!_this.pointerDownPredicate) {
  25850. _this.pointerDownPredicate = function (mesh) {
  25851. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25852. };
  25853. }
  25854. // Meshes
  25855. _this._pickedDownMesh = null;
  25856. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25857. _this._processPointerDown(pickResult, evt);
  25858. };
  25859. this._onPointerUp = function (evt) {
  25860. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25861. return; // So we need to test it the pointer down was pressed before.
  25862. }
  25863. _this._totalPointersPressed--;
  25864. _this._pickedUpMesh = null;
  25865. _this._meshPickProceed = false;
  25866. _this._updatePointerPosition(evt);
  25867. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25868. // PreObservable support
  25869. if (_this.onPrePointerObservable.hasObservers()) {
  25870. if (!clickInfo.ignore) {
  25871. if (!clickInfo.hasSwiped) {
  25872. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25873. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25874. return;
  25875. }
  25876. }
  25877. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25878. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25879. return;
  25880. }
  25881. }
  25882. }
  25883. }
  25884. else {
  25885. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25886. return;
  25887. }
  25888. }
  25889. }
  25890. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25891. return;
  25892. }
  25893. _this._pointerCaptures[evt.pointerId] = false;
  25894. if (!_this.pointerUpPredicate) {
  25895. _this.pointerUpPredicate = function (mesh) {
  25896. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25897. };
  25898. }
  25899. // Meshes
  25900. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25901. _this._initActionManager(null, clickInfo);
  25902. }
  25903. if (!pickResult) {
  25904. pickResult = _this._currentPickResult;
  25905. }
  25906. _this._processPointerUp(pickResult, evt, clickInfo);
  25907. _this._previousPickResult = _this._currentPickResult;
  25908. });
  25909. };
  25910. this._onKeyDown = function (evt) {
  25911. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25912. if (_this.onPreKeyboardObservable.hasObservers()) {
  25913. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25914. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25915. if (pi.skipOnPointerObservable) {
  25916. return;
  25917. }
  25918. }
  25919. if (_this.onKeyboardObservable.hasObservers()) {
  25920. var pi = new BABYLON.KeyboardInfo(type, evt);
  25921. _this.onKeyboardObservable.notifyObservers(pi, type);
  25922. }
  25923. if (_this.actionManager) {
  25924. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25925. }
  25926. };
  25927. this._onKeyUp = function (evt) {
  25928. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25929. if (_this.onPreKeyboardObservable.hasObservers()) {
  25930. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25931. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25932. if (pi.skipOnPointerObservable) {
  25933. return;
  25934. }
  25935. }
  25936. if (_this.onKeyboardObservable.hasObservers()) {
  25937. var pi = new BABYLON.KeyboardInfo(type, evt);
  25938. _this.onKeyboardObservable.notifyObservers(pi, type);
  25939. }
  25940. if (_this.actionManager) {
  25941. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25942. }
  25943. };
  25944. var engine = this.getEngine();
  25945. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25946. if (!canvas) {
  25947. return;
  25948. }
  25949. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25950. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25951. });
  25952. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25953. if (!canvas) {
  25954. return;
  25955. }
  25956. canvas.removeEventListener("keydown", _this._onKeyDown);
  25957. canvas.removeEventListener("keyup", _this._onKeyUp);
  25958. });
  25959. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25960. var canvas = this._engine.getRenderingCanvas();
  25961. if (!canvas) {
  25962. return;
  25963. }
  25964. if (attachMove) {
  25965. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25966. // Wheel
  25967. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25968. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25969. }
  25970. if (attachDown) {
  25971. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25972. }
  25973. if (attachUp) {
  25974. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25975. }
  25976. canvas.tabIndex = 1;
  25977. };
  25978. /** Detaches all event handlers*/
  25979. Scene.prototype.detachControl = function () {
  25980. var engine = this.getEngine();
  25981. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25982. var canvas = engine.getRenderingCanvas();
  25983. if (!canvas) {
  25984. return;
  25985. }
  25986. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25987. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25988. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25989. if (this._onCanvasBlurObserver) {
  25990. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25991. }
  25992. if (this._onCanvasFocusObserver) {
  25993. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25994. }
  25995. // Wheel
  25996. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25997. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25998. // Keyboard
  25999. canvas.removeEventListener("keydown", this._onKeyDown);
  26000. canvas.removeEventListener("keyup", this._onKeyUp);
  26001. // Observables
  26002. this.onKeyboardObservable.clear();
  26003. this.onPreKeyboardObservable.clear();
  26004. this.onPointerObservable.clear();
  26005. this.onPrePointerObservable.clear();
  26006. };
  26007. /**
  26008. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26009. * Delay loaded resources are not taking in account
  26010. * @return true if all required resources are ready
  26011. */
  26012. Scene.prototype.isReady = function () {
  26013. if (this._isDisposed) {
  26014. return false;
  26015. }
  26016. if (this._pendingData.length > 0) {
  26017. return false;
  26018. }
  26019. var index;
  26020. var engine = this.getEngine();
  26021. // Geometries
  26022. for (index = 0; index < this.geometries.length; index++) {
  26023. var geometry = this.geometries[index];
  26024. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26025. return false;
  26026. }
  26027. }
  26028. // Meshes
  26029. for (index = 0; index < this.meshes.length; index++) {
  26030. var mesh = this.meshes[index];
  26031. if (!mesh.isEnabled()) {
  26032. continue;
  26033. }
  26034. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26035. continue;
  26036. }
  26037. if (!mesh.isReady(true)) {
  26038. return false;
  26039. }
  26040. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26041. // Is Ready For Mesh
  26042. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26043. var step = _a[_i];
  26044. if (!step.action(mesh, hardwareInstancedRendering)) {
  26045. return false;
  26046. }
  26047. }
  26048. }
  26049. // Post-processes
  26050. if (this.activeCameras && this.activeCameras.length > 0) {
  26051. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26052. var camera = _c[_b];
  26053. if (!camera.isReady(true)) {
  26054. return false;
  26055. }
  26056. }
  26057. }
  26058. else if (this.activeCamera) {
  26059. if (!this.activeCamera.isReady(true)) {
  26060. return false;
  26061. }
  26062. }
  26063. // Particles
  26064. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26065. var particleSystem = _e[_d];
  26066. if (!particleSystem.isReady()) {
  26067. return false;
  26068. }
  26069. }
  26070. return true;
  26071. };
  26072. /** Resets all cached information relative to material (including effect and visibility) */
  26073. Scene.prototype.resetCachedMaterial = function () {
  26074. this._cachedMaterial = null;
  26075. this._cachedEffect = null;
  26076. this._cachedVisibility = null;
  26077. };
  26078. /**
  26079. * Registers a function to be called before every frame render
  26080. * @param func defines the function to register
  26081. */
  26082. Scene.prototype.registerBeforeRender = function (func) {
  26083. this.onBeforeRenderObservable.add(func);
  26084. };
  26085. /**
  26086. * Unregisters a function called before every frame render
  26087. * @param func defines the function to unregister
  26088. */
  26089. Scene.prototype.unregisterBeforeRender = function (func) {
  26090. this.onBeforeRenderObservable.removeCallback(func);
  26091. };
  26092. /**
  26093. * Registers a function to be called after every frame render
  26094. * @param func defines the function to register
  26095. */
  26096. Scene.prototype.registerAfterRender = function (func) {
  26097. this.onAfterRenderObservable.add(func);
  26098. };
  26099. /**
  26100. * Unregisters a function called after every frame render
  26101. * @param func defines the function to unregister
  26102. */
  26103. Scene.prototype.unregisterAfterRender = function (func) {
  26104. this.onAfterRenderObservable.removeCallback(func);
  26105. };
  26106. Scene.prototype._executeOnceBeforeRender = function (func) {
  26107. var _this = this;
  26108. var execFunc = function () {
  26109. func();
  26110. setTimeout(function () {
  26111. _this.unregisterBeforeRender(execFunc);
  26112. });
  26113. };
  26114. this.registerBeforeRender(execFunc);
  26115. };
  26116. /**
  26117. * The provided function will run before render once and will be disposed afterwards.
  26118. * A timeout delay can be provided so that the function will be executed in N ms.
  26119. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26120. * @param func The function to be executed.
  26121. * @param timeout optional delay in ms
  26122. */
  26123. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26124. var _this = this;
  26125. if (timeout !== undefined) {
  26126. setTimeout(function () {
  26127. _this._executeOnceBeforeRender(func);
  26128. }, timeout);
  26129. }
  26130. else {
  26131. this._executeOnceBeforeRender(func);
  26132. }
  26133. };
  26134. /** @hidden */
  26135. Scene.prototype._addPendingData = function (data) {
  26136. this._pendingData.push(data);
  26137. };
  26138. /** @hidden */
  26139. Scene.prototype._removePendingData = function (data) {
  26140. var wasLoading = this.isLoading;
  26141. var index = this._pendingData.indexOf(data);
  26142. if (index !== -1) {
  26143. this._pendingData.splice(index, 1);
  26144. }
  26145. if (wasLoading && !this.isLoading) {
  26146. this.onDataLoadedObservable.notifyObservers(this);
  26147. }
  26148. };
  26149. /**
  26150. * Returns the number of items waiting to be loaded
  26151. * @returns the number of items waiting to be loaded
  26152. */
  26153. Scene.prototype.getWaitingItemsCount = function () {
  26154. return this._pendingData.length;
  26155. };
  26156. Object.defineProperty(Scene.prototype, "isLoading", {
  26157. /**
  26158. * Returns a boolean indicating if the scene is still loading data
  26159. */
  26160. get: function () {
  26161. return this._pendingData.length > 0;
  26162. },
  26163. enumerable: true,
  26164. configurable: true
  26165. });
  26166. /**
  26167. * Registers a function to be executed when the scene is ready
  26168. * @param {Function} func - the function to be executed
  26169. */
  26170. Scene.prototype.executeWhenReady = function (func) {
  26171. var _this = this;
  26172. this.onReadyObservable.add(func);
  26173. if (this._executeWhenReadyTimeoutId !== -1) {
  26174. return;
  26175. }
  26176. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26177. _this._checkIsReady();
  26178. }, 150);
  26179. };
  26180. /**
  26181. * Returns a promise that resolves when the scene is ready
  26182. * @returns A promise that resolves when the scene is ready
  26183. */
  26184. Scene.prototype.whenReadyAsync = function () {
  26185. var _this = this;
  26186. return new Promise(function (resolve) {
  26187. _this.executeWhenReady(function () {
  26188. resolve();
  26189. });
  26190. });
  26191. };
  26192. /** @hidden */
  26193. Scene.prototype._checkIsReady = function () {
  26194. var _this = this;
  26195. this._registerTransientComponents();
  26196. if (this.isReady()) {
  26197. this.onReadyObservable.notifyObservers(this);
  26198. this.onReadyObservable.clear();
  26199. this._executeWhenReadyTimeoutId = -1;
  26200. return;
  26201. }
  26202. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26203. _this._checkIsReady();
  26204. }, 150);
  26205. };
  26206. // Animations
  26207. /**
  26208. * Will start the animation sequence of a given target
  26209. * @param target defines the target
  26210. * @param from defines from which frame should animation start
  26211. * @param to defines until which frame should animation run.
  26212. * @param weight defines the weight to apply to the animation (1.0 by default)
  26213. * @param loop defines if the animation loops
  26214. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26215. * @param onAnimationEnd defines the function to be executed when the animation ends
  26216. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26217. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26218. * @returns the animatable object created for this animation
  26219. */
  26220. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26221. if (weight === void 0) { weight = 1.0; }
  26222. if (speedRatio === void 0) { speedRatio = 1.0; }
  26223. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26224. returnedAnimatable.weight = weight;
  26225. return returnedAnimatable;
  26226. };
  26227. /**
  26228. * Will start the animation sequence of a given target
  26229. * @param target defines the target
  26230. * @param from defines from which frame should animation start
  26231. * @param to defines until which frame should animation run.
  26232. * @param loop defines if the animation loops
  26233. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26234. * @param onAnimationEnd defines the function to be executed when the animation ends
  26235. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26236. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26237. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26238. * @returns the animatable object created for this animation
  26239. */
  26240. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26241. if (speedRatio === void 0) { speedRatio = 1.0; }
  26242. if (stopCurrent === void 0) { stopCurrent = true; }
  26243. if (from > to && speedRatio > 0) {
  26244. speedRatio *= -1;
  26245. }
  26246. if (stopCurrent) {
  26247. this.stopAnimation(target, undefined, targetMask);
  26248. }
  26249. if (!animatable) {
  26250. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26251. }
  26252. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26253. // Local animations
  26254. if (target.animations && shouldRunTargetAnimations) {
  26255. animatable.appendAnimations(target, target.animations);
  26256. }
  26257. // Children animations
  26258. if (target.getAnimatables) {
  26259. var animatables = target.getAnimatables();
  26260. for (var index = 0; index < animatables.length; index++) {
  26261. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26262. }
  26263. }
  26264. animatable.reset();
  26265. return animatable;
  26266. };
  26267. /**
  26268. * Begin a new animation on a given node
  26269. * @param target defines the target where the animation will take place
  26270. * @param animations defines the list of animations to start
  26271. * @param from defines the initial value
  26272. * @param to defines the final value
  26273. * @param loop defines if you want animation to loop (off by default)
  26274. * @param speedRatio defines the speed ratio to apply to all animations
  26275. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26276. * @returns the list of created animatables
  26277. */
  26278. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26279. if (speedRatio === undefined) {
  26280. speedRatio = 1.0;
  26281. }
  26282. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26283. return animatable;
  26284. };
  26285. /**
  26286. * Begin a new animation on a given node and its hierarchy
  26287. * @param target defines the root node where the animation will take place
  26288. * @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.
  26289. * @param animations defines the list of animations to start
  26290. * @param from defines the initial value
  26291. * @param to defines the final value
  26292. * @param loop defines if you want animation to loop (off by default)
  26293. * @param speedRatio defines the speed ratio to apply to all animations
  26294. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26295. * @returns the list of animatables created for all nodes
  26296. */
  26297. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26298. var children = target.getDescendants(directDescendantsOnly);
  26299. var result = [];
  26300. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26301. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26302. var child = children_1[_i];
  26303. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26304. }
  26305. return result;
  26306. };
  26307. /**
  26308. * Gets the animatable associated with a specific target
  26309. * @param target defines the target of the animatable
  26310. * @returns the required animatable if found
  26311. */
  26312. Scene.prototype.getAnimatableByTarget = function (target) {
  26313. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26314. if (this._activeAnimatables[index].target === target) {
  26315. return this._activeAnimatables[index];
  26316. }
  26317. }
  26318. return null;
  26319. };
  26320. /**
  26321. * Gets all animatables associated with a given target
  26322. * @param target defines the target to look animatables for
  26323. * @returns an array of Animatables
  26324. */
  26325. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26326. var result = [];
  26327. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26328. if (this._activeAnimatables[index].target === target) {
  26329. result.push(this._activeAnimatables[index]);
  26330. }
  26331. }
  26332. return result;
  26333. };
  26334. Object.defineProperty(Scene.prototype, "animatables", {
  26335. /**
  26336. * Gets all animatable attached to the scene
  26337. */
  26338. get: function () {
  26339. return this._activeAnimatables;
  26340. },
  26341. enumerable: true,
  26342. configurable: true
  26343. });
  26344. /**
  26345. * Will stop the animation of the given target
  26346. * @param target - the target
  26347. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26348. * @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)
  26349. */
  26350. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26351. var animatables = this.getAllAnimatablesByTarget(target);
  26352. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26353. var animatable = animatables_1[_i];
  26354. animatable.stop(animationName, targetMask);
  26355. }
  26356. };
  26357. /**
  26358. * Stops and removes all animations that have been applied to the scene
  26359. */
  26360. Scene.prototype.stopAllAnimations = function () {
  26361. if (this._activeAnimatables) {
  26362. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26363. this._activeAnimatables[i].stop();
  26364. }
  26365. this._activeAnimatables = [];
  26366. }
  26367. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26368. var group = _a[_i];
  26369. group.stop();
  26370. }
  26371. };
  26372. Scene.prototype._animate = function () {
  26373. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26374. return;
  26375. }
  26376. // Getting time
  26377. var now = BABYLON.Tools.Now;
  26378. if (!this._animationTimeLast) {
  26379. if (this._pendingData.length > 0) {
  26380. return;
  26381. }
  26382. this._animationTimeLast = now;
  26383. }
  26384. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26385. this._animationTime += deltaTime;
  26386. this._animationTimeLast = now;
  26387. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26388. this._activeAnimatables[index]._animate(this._animationTime);
  26389. }
  26390. // Late animation bindings
  26391. this._processLateAnimationBindings();
  26392. };
  26393. /** @hidden */
  26394. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26395. var target = runtimeAnimation.target;
  26396. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26397. if (!target._lateAnimationHolders) {
  26398. target._lateAnimationHolders = {};
  26399. }
  26400. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26401. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26402. totalWeight: 0,
  26403. animations: [],
  26404. originalValue: originalValue
  26405. };
  26406. }
  26407. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26408. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26409. };
  26410. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26411. var normalizer = 1.0;
  26412. var finalPosition = BABYLON.Tmp.Vector3[0];
  26413. var finalScaling = BABYLON.Tmp.Vector3[1];
  26414. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26415. var startIndex = 0;
  26416. var originalAnimation = holder.animations[0];
  26417. var originalValue = holder.originalValue;
  26418. var scale = 1;
  26419. if (holder.totalWeight < 1.0) {
  26420. // We need to mix the original value in
  26421. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26422. scale = 1.0 - holder.totalWeight;
  26423. }
  26424. else {
  26425. startIndex = 1;
  26426. // We need to normalize the weights
  26427. normalizer = holder.totalWeight;
  26428. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26429. scale = originalAnimation.weight / normalizer;
  26430. if (scale == 1) {
  26431. return originalAnimation.currentValue;
  26432. }
  26433. }
  26434. finalScaling.scaleInPlace(scale);
  26435. finalPosition.scaleInPlace(scale);
  26436. finalQuaternion.scaleInPlace(scale);
  26437. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26438. var runtimeAnimation = holder.animations[animIndex];
  26439. var scale = runtimeAnimation.weight / normalizer;
  26440. var currentPosition = BABYLON.Tmp.Vector3[2];
  26441. var currentScaling = BABYLON.Tmp.Vector3[3];
  26442. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26443. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26444. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26445. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26446. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26447. }
  26448. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26449. return originalAnimation._workValue;
  26450. };
  26451. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26452. var originalAnimation = holder.animations[0];
  26453. var originalValue = holder.originalValue;
  26454. if (holder.animations.length === 1) {
  26455. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26456. return refQuaternion;
  26457. }
  26458. var normalizer = 1.0;
  26459. var quaternions;
  26460. var weights;
  26461. if (holder.totalWeight < 1.0) {
  26462. var scale = 1.0 - holder.totalWeight;
  26463. quaternions = [];
  26464. weights = [];
  26465. quaternions.push(originalValue);
  26466. weights.push(scale);
  26467. }
  26468. else {
  26469. if (holder.animations.length === 2) { // Slerp as soon as we can
  26470. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26471. return refQuaternion;
  26472. }
  26473. quaternions = [];
  26474. weights = [];
  26475. normalizer = holder.totalWeight;
  26476. }
  26477. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26478. var runtimeAnimation = holder.animations[animIndex];
  26479. quaternions.push(runtimeAnimation.currentValue);
  26480. weights.push(runtimeAnimation.weight / normalizer);
  26481. }
  26482. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26483. var cumulativeAmount = 0;
  26484. var cumulativeQuaternion = null;
  26485. for (var index = 0; index < quaternions.length;) {
  26486. if (!cumulativeQuaternion) {
  26487. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26488. cumulativeQuaternion = refQuaternion;
  26489. cumulativeAmount = weights[index] + weights[index + 1];
  26490. index += 2;
  26491. continue;
  26492. }
  26493. cumulativeAmount += weights[index];
  26494. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26495. index++;
  26496. }
  26497. return cumulativeQuaternion;
  26498. };
  26499. Scene.prototype._processLateAnimationBindings = function () {
  26500. if (!this._registeredForLateAnimationBindings.length) {
  26501. return;
  26502. }
  26503. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26504. var target = this._registeredForLateAnimationBindings.data[index];
  26505. for (var path in target._lateAnimationHolders) {
  26506. var holder = target._lateAnimationHolders[path];
  26507. var originalAnimation = holder.animations[0];
  26508. var originalValue = holder.originalValue;
  26509. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26510. var finalValue = target[path];
  26511. if (matrixDecomposeMode) {
  26512. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26513. }
  26514. else {
  26515. var quaternionMode = originalValue.w !== undefined;
  26516. if (quaternionMode) {
  26517. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26518. }
  26519. else {
  26520. var startIndex = 0;
  26521. var normalizer = 1.0;
  26522. if (holder.totalWeight < 1.0) {
  26523. // We need to mix the original value in
  26524. if (originalValue.scale) {
  26525. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26526. }
  26527. else {
  26528. finalValue = originalValue * (1.0 - holder.totalWeight);
  26529. }
  26530. }
  26531. else {
  26532. // We need to normalize the weights
  26533. normalizer = holder.totalWeight;
  26534. var scale_1 = originalAnimation.weight / normalizer;
  26535. if (scale_1 !== 1) {
  26536. if (originalAnimation.currentValue.scale) {
  26537. finalValue = originalAnimation.currentValue.scale(scale_1);
  26538. }
  26539. else {
  26540. finalValue = originalAnimation.currentValue * scale_1;
  26541. }
  26542. }
  26543. else {
  26544. finalValue = originalAnimation.currentValue;
  26545. }
  26546. startIndex = 1;
  26547. }
  26548. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26549. var runtimeAnimation = holder.animations[animIndex];
  26550. var scale = runtimeAnimation.weight / normalizer;
  26551. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26552. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26553. }
  26554. else {
  26555. finalValue += runtimeAnimation.currentValue * scale;
  26556. }
  26557. }
  26558. }
  26559. }
  26560. target[path] = finalValue;
  26561. }
  26562. target._lateAnimationHolders = {};
  26563. }
  26564. this._registeredForLateAnimationBindings.reset();
  26565. };
  26566. // Matrix
  26567. /** @hidden */
  26568. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26569. this._useAlternateCameraConfiguration = active;
  26570. };
  26571. /**
  26572. * Gets the current view matrix
  26573. * @returns a Matrix
  26574. */
  26575. Scene.prototype.getViewMatrix = function () {
  26576. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26577. };
  26578. /**
  26579. * Gets the current projection matrix
  26580. * @returns a Matrix
  26581. */
  26582. Scene.prototype.getProjectionMatrix = function () {
  26583. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26584. };
  26585. /**
  26586. * Gets the current transform matrix
  26587. * @returns a Matrix made of View * Projection
  26588. */
  26589. Scene.prototype.getTransformMatrix = function () {
  26590. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26591. };
  26592. /**
  26593. * Sets the current transform matrix
  26594. * @param view defines the View matrix to use
  26595. * @param projection defines the Projection matrix to use
  26596. */
  26597. Scene.prototype.setTransformMatrix = function (view, projection) {
  26598. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26599. return;
  26600. }
  26601. this._viewUpdateFlag = view.updateFlag;
  26602. this._projectionUpdateFlag = projection.updateFlag;
  26603. this._viewMatrix = view;
  26604. this._projectionMatrix = projection;
  26605. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26606. // Update frustum
  26607. if (!this._frustumPlanes) {
  26608. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26609. }
  26610. else {
  26611. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26612. }
  26613. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26614. var otherCamera = this.activeCamera._alternateCamera;
  26615. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26616. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26617. }
  26618. if (this._sceneUbo.useUbo) {
  26619. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26620. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26621. this._sceneUbo.update();
  26622. }
  26623. };
  26624. /** @hidden */
  26625. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26626. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26627. return;
  26628. }
  26629. this._alternateViewUpdateFlag = view.updateFlag;
  26630. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26631. this._alternateViewMatrix = view;
  26632. this._alternateProjectionMatrix = projection;
  26633. if (!this._alternateTransformMatrix) {
  26634. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26635. }
  26636. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26637. if (!this._alternateSceneUbo) {
  26638. this._createAlternateUbo();
  26639. }
  26640. if (this._alternateSceneUbo.useUbo) {
  26641. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26642. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26643. this._alternateSceneUbo.update();
  26644. }
  26645. };
  26646. /**
  26647. * Gets the uniform buffer used to store scene data
  26648. * @returns a UniformBuffer
  26649. */
  26650. Scene.prototype.getSceneUniformBuffer = function () {
  26651. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26652. };
  26653. /**
  26654. * Gets an unique (relatively to the current scene) Id
  26655. * @returns an unique number for the scene
  26656. */
  26657. Scene.prototype.getUniqueId = function () {
  26658. var result = Scene._uniqueIdCounter;
  26659. Scene._uniqueIdCounter++;
  26660. return result;
  26661. };
  26662. /**
  26663. * Add a mesh to the list of scene's meshes
  26664. * @param newMesh defines the mesh to add
  26665. * @param recursive if all child meshes should also be added to the scene
  26666. */
  26667. Scene.prototype.addMesh = function (newMesh, recursive) {
  26668. var _this = this;
  26669. if (recursive === void 0) { recursive = false; }
  26670. this.meshes.push(newMesh);
  26671. //notify the collision coordinator
  26672. if (this.collisionCoordinator) {
  26673. this.collisionCoordinator.onMeshAdded(newMesh);
  26674. }
  26675. newMesh._resyncLightSources();
  26676. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26677. if (recursive) {
  26678. newMesh.getChildMeshes().forEach(function (m) {
  26679. _this.addMesh(m);
  26680. });
  26681. }
  26682. };
  26683. /**
  26684. * Remove a mesh for the list of scene's meshes
  26685. * @param toRemove defines the mesh to remove
  26686. * @param recursive if all child meshes should also be removed from the scene
  26687. * @returns the index where the mesh was in the mesh list
  26688. */
  26689. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26690. var _this = this;
  26691. if (recursive === void 0) { recursive = false; }
  26692. var index = this.meshes.indexOf(toRemove);
  26693. if (index !== -1) {
  26694. // Remove from the scene if mesh found
  26695. this.meshes.splice(index, 1);
  26696. }
  26697. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26698. if (recursive) {
  26699. toRemove.getChildMeshes().forEach(function (m) {
  26700. _this.removeMesh(m);
  26701. });
  26702. }
  26703. return index;
  26704. };
  26705. /**
  26706. * Add a transform node to the list of scene's transform nodes
  26707. * @param newTransformNode defines the transform node to add
  26708. */
  26709. Scene.prototype.addTransformNode = function (newTransformNode) {
  26710. this.transformNodes.push(newTransformNode);
  26711. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26712. };
  26713. /**
  26714. * Remove a transform node for the list of scene's transform nodes
  26715. * @param toRemove defines the transform node to remove
  26716. * @returns the index where the transform node was in the transform node list
  26717. */
  26718. Scene.prototype.removeTransformNode = function (toRemove) {
  26719. var index = this.transformNodes.indexOf(toRemove);
  26720. if (index !== -1) {
  26721. // Remove from the scene if found
  26722. this.transformNodes.splice(index, 1);
  26723. }
  26724. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26725. return index;
  26726. };
  26727. /**
  26728. * Remove a skeleton for the list of scene's skeletons
  26729. * @param toRemove defines the skeleton to remove
  26730. * @returns the index where the skeleton was in the skeleton list
  26731. */
  26732. Scene.prototype.removeSkeleton = function (toRemove) {
  26733. var index = this.skeletons.indexOf(toRemove);
  26734. if (index !== -1) {
  26735. // Remove from the scene if found
  26736. this.skeletons.splice(index, 1);
  26737. }
  26738. return index;
  26739. };
  26740. /**
  26741. * Remove a morph target for the list of scene's morph targets
  26742. * @param toRemove defines the morph target to remove
  26743. * @returns the index where the morph target was in the morph target list
  26744. */
  26745. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26746. var index = this.morphTargetManagers.indexOf(toRemove);
  26747. if (index !== -1) {
  26748. // Remove from the scene if found
  26749. this.morphTargetManagers.splice(index, 1);
  26750. }
  26751. return index;
  26752. };
  26753. /**
  26754. * Remove a light for the list of scene's lights
  26755. * @param toRemove defines the light to remove
  26756. * @returns the index where the light was in the light list
  26757. */
  26758. Scene.prototype.removeLight = function (toRemove) {
  26759. var index = this.lights.indexOf(toRemove);
  26760. if (index !== -1) {
  26761. // Remove from meshes
  26762. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26763. var mesh = _a[_i];
  26764. mesh._removeLightSource(toRemove);
  26765. }
  26766. // Remove from the scene if mesh found
  26767. this.lights.splice(index, 1);
  26768. this.sortLightsByPriority();
  26769. }
  26770. this.onLightRemovedObservable.notifyObservers(toRemove);
  26771. return index;
  26772. };
  26773. /**
  26774. * Remove a camera for the list of scene's cameras
  26775. * @param toRemove defines the camera to remove
  26776. * @returns the index where the camera was in the camera list
  26777. */
  26778. Scene.prototype.removeCamera = function (toRemove) {
  26779. var index = this.cameras.indexOf(toRemove);
  26780. if (index !== -1) {
  26781. // Remove from the scene if mesh found
  26782. this.cameras.splice(index, 1);
  26783. }
  26784. // Remove from activeCameras
  26785. var index2 = this.activeCameras.indexOf(toRemove);
  26786. if (index2 !== -1) {
  26787. // Remove from the scene if mesh found
  26788. this.activeCameras.splice(index2, 1);
  26789. }
  26790. // Reset the activeCamera
  26791. if (this.activeCamera === toRemove) {
  26792. if (this.cameras.length > 0) {
  26793. this.activeCamera = this.cameras[0];
  26794. }
  26795. else {
  26796. this.activeCamera = null;
  26797. }
  26798. }
  26799. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26800. return index;
  26801. };
  26802. /**
  26803. * Remove a particle system for the list of scene's particle systems
  26804. * @param toRemove defines the particle system to remove
  26805. * @returns the index where the particle system was in the particle system list
  26806. */
  26807. Scene.prototype.removeParticleSystem = function (toRemove) {
  26808. var index = this.particleSystems.indexOf(toRemove);
  26809. if (index !== -1) {
  26810. this.particleSystems.splice(index, 1);
  26811. }
  26812. return index;
  26813. };
  26814. /**
  26815. * Remove a animation for the list of scene's animations
  26816. * @param toRemove defines the animation to remove
  26817. * @returns the index where the animation was in the animation list
  26818. */
  26819. Scene.prototype.removeAnimation = function (toRemove) {
  26820. var index = this.animations.indexOf(toRemove);
  26821. if (index !== -1) {
  26822. this.animations.splice(index, 1);
  26823. }
  26824. return index;
  26825. };
  26826. /**
  26827. * Removes the given animation group from this scene.
  26828. * @param toRemove The animation group to remove
  26829. * @returns The index of the removed animation group
  26830. */
  26831. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26832. var index = this.animationGroups.indexOf(toRemove);
  26833. if (index !== -1) {
  26834. this.animationGroups.splice(index, 1);
  26835. }
  26836. return index;
  26837. };
  26838. /**
  26839. * Removes the given multi-material from this scene.
  26840. * @param toRemove The multi-material to remove
  26841. * @returns The index of the removed multi-material
  26842. */
  26843. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26844. var index = this.multiMaterials.indexOf(toRemove);
  26845. if (index !== -1) {
  26846. this.multiMaterials.splice(index, 1);
  26847. }
  26848. return index;
  26849. };
  26850. /**
  26851. * Removes the given material from this scene.
  26852. * @param toRemove The material to remove
  26853. * @returns The index of the removed material
  26854. */
  26855. Scene.prototype.removeMaterial = function (toRemove) {
  26856. var index = this.materials.indexOf(toRemove);
  26857. if (index !== -1) {
  26858. this.materials.splice(index, 1);
  26859. }
  26860. return index;
  26861. };
  26862. /**
  26863. * Removes the given action manager from this scene.
  26864. * @param toRemove The action manager to remove
  26865. * @returns The index of the removed action manager
  26866. */
  26867. Scene.prototype.removeActionManager = function (toRemove) {
  26868. var index = this.actionManagers.indexOf(toRemove);
  26869. if (index !== -1) {
  26870. this.actionManagers.splice(index, 1);
  26871. }
  26872. return index;
  26873. };
  26874. /**
  26875. * Removes the given texture from this scene.
  26876. * @param toRemove The texture to remove
  26877. * @returns The index of the removed texture
  26878. */
  26879. Scene.prototype.removeTexture = function (toRemove) {
  26880. var index = this.textures.indexOf(toRemove);
  26881. if (index !== -1) {
  26882. this.textures.splice(index, 1);
  26883. }
  26884. return index;
  26885. };
  26886. /**
  26887. * Adds the given light to this scene
  26888. * @param newLight The light to add
  26889. */
  26890. Scene.prototype.addLight = function (newLight) {
  26891. this.lights.push(newLight);
  26892. this.sortLightsByPriority();
  26893. // Add light to all meshes (To support if the light is removed and then readded)
  26894. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26895. var mesh = _a[_i];
  26896. if (mesh._lightSources.indexOf(newLight) === -1) {
  26897. mesh._lightSources.push(newLight);
  26898. mesh._resyncLightSources();
  26899. }
  26900. }
  26901. this.onNewLightAddedObservable.notifyObservers(newLight);
  26902. };
  26903. /**
  26904. * Sorts the list list based on light priorities
  26905. */
  26906. Scene.prototype.sortLightsByPriority = function () {
  26907. if (this.requireLightSorting) {
  26908. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26909. }
  26910. };
  26911. /**
  26912. * Adds the given camera to this scene
  26913. * @param newCamera The camera to add
  26914. */
  26915. Scene.prototype.addCamera = function (newCamera) {
  26916. this.cameras.push(newCamera);
  26917. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26918. };
  26919. /**
  26920. * Adds the given skeleton to this scene
  26921. * @param newSkeleton The skeleton to add
  26922. */
  26923. Scene.prototype.addSkeleton = function (newSkeleton) {
  26924. this.skeletons.push(newSkeleton);
  26925. };
  26926. /**
  26927. * Adds the given particle system to this scene
  26928. * @param newParticleSystem The particle system to add
  26929. */
  26930. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26931. this.particleSystems.push(newParticleSystem);
  26932. };
  26933. /**
  26934. * Adds the given animation to this scene
  26935. * @param newAnimation The animation to add
  26936. */
  26937. Scene.prototype.addAnimation = function (newAnimation) {
  26938. this.animations.push(newAnimation);
  26939. };
  26940. /**
  26941. * Adds the given animation group to this scene.
  26942. * @param newAnimationGroup The animation group to add
  26943. */
  26944. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26945. this.animationGroups.push(newAnimationGroup);
  26946. };
  26947. /**
  26948. * Adds the given multi-material to this scene
  26949. * @param newMultiMaterial The multi-material to add
  26950. */
  26951. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26952. this.multiMaterials.push(newMultiMaterial);
  26953. };
  26954. /**
  26955. * Adds the given material to this scene
  26956. * @param newMaterial The material to add
  26957. */
  26958. Scene.prototype.addMaterial = function (newMaterial) {
  26959. this.materials.push(newMaterial);
  26960. };
  26961. /**
  26962. * Adds the given morph target to this scene
  26963. * @param newMorphTargetManager The morph target to add
  26964. */
  26965. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26966. this.morphTargetManagers.push(newMorphTargetManager);
  26967. };
  26968. /**
  26969. * Adds the given geometry to this scene
  26970. * @param newGeometry The geometry to add
  26971. */
  26972. Scene.prototype.addGeometry = function (newGeometry) {
  26973. this.geometries.push(newGeometry);
  26974. };
  26975. /**
  26976. * Adds the given action manager to this scene
  26977. * @param newActionManager The action manager to add
  26978. */
  26979. Scene.prototype.addActionManager = function (newActionManager) {
  26980. this.actionManagers.push(newActionManager);
  26981. };
  26982. /**
  26983. * Adds the given texture to this scene.
  26984. * @param newTexture The texture to add
  26985. */
  26986. Scene.prototype.addTexture = function (newTexture) {
  26987. this.textures.push(newTexture);
  26988. };
  26989. /**
  26990. * Switch active camera
  26991. * @param newCamera defines the new active camera
  26992. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26993. */
  26994. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26995. if (attachControl === void 0) { attachControl = true; }
  26996. var canvas = this._engine.getRenderingCanvas();
  26997. if (!canvas) {
  26998. return;
  26999. }
  27000. if (this.activeCamera) {
  27001. this.activeCamera.detachControl(canvas);
  27002. }
  27003. this.activeCamera = newCamera;
  27004. if (attachControl) {
  27005. newCamera.attachControl(canvas);
  27006. }
  27007. };
  27008. /**
  27009. * sets the active camera of the scene using its ID
  27010. * @param id defines the camera's ID
  27011. * @return the new active camera or null if none found.
  27012. */
  27013. Scene.prototype.setActiveCameraByID = function (id) {
  27014. var camera = this.getCameraByID(id);
  27015. if (camera) {
  27016. this.activeCamera = camera;
  27017. return camera;
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * sets the active camera of the scene using its name
  27023. * @param name defines the camera's name
  27024. * @returns the new active camera or null if none found.
  27025. */
  27026. Scene.prototype.setActiveCameraByName = function (name) {
  27027. var camera = this.getCameraByName(name);
  27028. if (camera) {
  27029. this.activeCamera = camera;
  27030. return camera;
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * get an animation group using its name
  27036. * @param name defines the material's name
  27037. * @return the animation group or null if none found.
  27038. */
  27039. Scene.prototype.getAnimationGroupByName = function (name) {
  27040. for (var index = 0; index < this.animationGroups.length; index++) {
  27041. if (this.animationGroups[index].name === name) {
  27042. return this.animationGroups[index];
  27043. }
  27044. }
  27045. return null;
  27046. };
  27047. /**
  27048. * get a material using its id
  27049. * @param id defines the material's ID
  27050. * @return the material or null if none found.
  27051. */
  27052. Scene.prototype.getMaterialByID = function (id) {
  27053. for (var index = 0; index < this.materials.length; index++) {
  27054. if (this.materials[index].id === id) {
  27055. return this.materials[index];
  27056. }
  27057. }
  27058. return null;
  27059. };
  27060. /**
  27061. * Gets a material using its name
  27062. * @param name defines the material's name
  27063. * @return the material or null if none found.
  27064. */
  27065. Scene.prototype.getMaterialByName = function (name) {
  27066. for (var index = 0; index < this.materials.length; index++) {
  27067. if (this.materials[index].name === name) {
  27068. return this.materials[index];
  27069. }
  27070. }
  27071. return null;
  27072. };
  27073. /**
  27074. * Gets a camera using its id
  27075. * @param id defines the id to look for
  27076. * @returns the camera or null if not found
  27077. */
  27078. Scene.prototype.getCameraByID = function (id) {
  27079. for (var index = 0; index < this.cameras.length; index++) {
  27080. if (this.cameras[index].id === id) {
  27081. return this.cameras[index];
  27082. }
  27083. }
  27084. return null;
  27085. };
  27086. /**
  27087. * Gets a camera using its unique id
  27088. * @param uniqueId defines the unique id to look for
  27089. * @returns the camera or null if not found
  27090. */
  27091. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27092. for (var index = 0; index < this.cameras.length; index++) {
  27093. if (this.cameras[index].uniqueId === uniqueId) {
  27094. return this.cameras[index];
  27095. }
  27096. }
  27097. return null;
  27098. };
  27099. /**
  27100. * Gets a camera using its name
  27101. * @param name defines the camera's name
  27102. * @return the camera or null if none found.
  27103. */
  27104. Scene.prototype.getCameraByName = function (name) {
  27105. for (var index = 0; index < this.cameras.length; index++) {
  27106. if (this.cameras[index].name === name) {
  27107. return this.cameras[index];
  27108. }
  27109. }
  27110. return null;
  27111. };
  27112. /**
  27113. * Gets a bone using its id
  27114. * @param id defines the bone's id
  27115. * @return the bone or null if not found
  27116. */
  27117. Scene.prototype.getBoneByID = function (id) {
  27118. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27119. var skeleton = this.skeletons[skeletonIndex];
  27120. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27121. if (skeleton.bones[boneIndex].id === id) {
  27122. return skeleton.bones[boneIndex];
  27123. }
  27124. }
  27125. }
  27126. return null;
  27127. };
  27128. /**
  27129. * Gets a bone using its id
  27130. * @param name defines the bone's name
  27131. * @return the bone or null if not found
  27132. */
  27133. Scene.prototype.getBoneByName = function (name) {
  27134. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27135. var skeleton = this.skeletons[skeletonIndex];
  27136. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27137. if (skeleton.bones[boneIndex].name === name) {
  27138. return skeleton.bones[boneIndex];
  27139. }
  27140. }
  27141. }
  27142. return null;
  27143. };
  27144. /**
  27145. * Gets a light node using its name
  27146. * @param name defines the the light's name
  27147. * @return the light or null if none found.
  27148. */
  27149. Scene.prototype.getLightByName = function (name) {
  27150. for (var index = 0; index < this.lights.length; index++) {
  27151. if (this.lights[index].name === name) {
  27152. return this.lights[index];
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. /**
  27158. * Gets a light node using its id
  27159. * @param id defines the light's id
  27160. * @return the light or null if none found.
  27161. */
  27162. Scene.prototype.getLightByID = function (id) {
  27163. for (var index = 0; index < this.lights.length; index++) {
  27164. if (this.lights[index].id === id) {
  27165. return this.lights[index];
  27166. }
  27167. }
  27168. return null;
  27169. };
  27170. /**
  27171. * Gets a light node using its scene-generated unique ID
  27172. * @param uniqueId defines the light's unique id
  27173. * @return the light or null if none found.
  27174. */
  27175. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27176. for (var index = 0; index < this.lights.length; index++) {
  27177. if (this.lights[index].uniqueId === uniqueId) {
  27178. return this.lights[index];
  27179. }
  27180. }
  27181. return null;
  27182. };
  27183. /**
  27184. * Gets a particle system by id
  27185. * @param id defines the particle system id
  27186. * @return the corresponding system or null if none found
  27187. */
  27188. Scene.prototype.getParticleSystemByID = function (id) {
  27189. for (var index = 0; index < this.particleSystems.length; index++) {
  27190. if (this.particleSystems[index].id === id) {
  27191. return this.particleSystems[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a geometry using its ID
  27198. * @param id defines the geometry's id
  27199. * @return the geometry or null if none found.
  27200. */
  27201. Scene.prototype.getGeometryByID = function (id) {
  27202. for (var index = 0; index < this.geometries.length; index++) {
  27203. if (this.geometries[index].id === id) {
  27204. return this.geometries[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Add a new geometry to this scene
  27211. * @param geometry defines the geometry to be added to the scene.
  27212. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27213. * @return a boolean defining if the geometry was added or not
  27214. */
  27215. Scene.prototype.pushGeometry = function (geometry, force) {
  27216. if (!force && this.getGeometryByID(geometry.id)) {
  27217. return false;
  27218. }
  27219. this.geometries.push(geometry);
  27220. //notify the collision coordinator
  27221. if (this.collisionCoordinator) {
  27222. this.collisionCoordinator.onGeometryAdded(geometry);
  27223. }
  27224. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27225. return true;
  27226. };
  27227. /**
  27228. * Removes an existing geometry
  27229. * @param geometry defines the geometry to be removed from the scene
  27230. * @return a boolean defining if the geometry was removed or not
  27231. */
  27232. Scene.prototype.removeGeometry = function (geometry) {
  27233. var index = this.geometries.indexOf(geometry);
  27234. if (index > -1) {
  27235. this.geometries.splice(index, 1);
  27236. //notify the collision coordinator
  27237. if (this.collisionCoordinator) {
  27238. this.collisionCoordinator.onGeometryDeleted(geometry);
  27239. }
  27240. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27241. return true;
  27242. }
  27243. return false;
  27244. };
  27245. /**
  27246. * Gets the list of geometries attached to the scene
  27247. * @returns an array of Geometry
  27248. */
  27249. Scene.prototype.getGeometries = function () {
  27250. return this.geometries;
  27251. };
  27252. /**
  27253. * Gets the first added mesh found of a given ID
  27254. * @param id defines the id to search for
  27255. * @return the mesh found or null if not found at all
  27256. */
  27257. Scene.prototype.getMeshByID = function (id) {
  27258. for (var index = 0; index < this.meshes.length; index++) {
  27259. if (this.meshes[index].id === id) {
  27260. return this.meshes[index];
  27261. }
  27262. }
  27263. return null;
  27264. };
  27265. /**
  27266. * Gets a list of meshes using their id
  27267. * @param id defines the id to search for
  27268. * @returns a list of meshes
  27269. */
  27270. Scene.prototype.getMeshesByID = function (id) {
  27271. return this.meshes.filter(function (m) {
  27272. return m.id === id;
  27273. });
  27274. };
  27275. /**
  27276. * Gets the first added transform node found of a given ID
  27277. * @param id defines the id to search for
  27278. * @return the found transform node or null if not found at all.
  27279. */
  27280. Scene.prototype.getTransformNodeByID = function (id) {
  27281. for (var index = 0; index < this.transformNodes.length; index++) {
  27282. if (this.transformNodes[index].id === id) {
  27283. return this.transformNodes[index];
  27284. }
  27285. }
  27286. return null;
  27287. };
  27288. /**
  27289. * Gets a list of transform nodes using their id
  27290. * @param id defines the id to search for
  27291. * @returns a list of transform nodes
  27292. */
  27293. Scene.prototype.getTransformNodesByID = function (id) {
  27294. return this.transformNodes.filter(function (m) {
  27295. return m.id === id;
  27296. });
  27297. };
  27298. /**
  27299. * Gets a mesh with its auto-generated unique id
  27300. * @param uniqueId defines the unique id to search for
  27301. * @return the found mesh or null if not found at all.
  27302. */
  27303. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27304. for (var index = 0; index < this.meshes.length; index++) {
  27305. if (this.meshes[index].uniqueId === uniqueId) {
  27306. return this.meshes[index];
  27307. }
  27308. }
  27309. return null;
  27310. };
  27311. /**
  27312. * Gets a the last added mesh using a given id
  27313. * @param id defines the id to search for
  27314. * @return the found mesh or null if not found at all.
  27315. */
  27316. Scene.prototype.getLastMeshByID = function (id) {
  27317. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27318. if (this.meshes[index].id === id) {
  27319. return this.meshes[index];
  27320. }
  27321. }
  27322. return null;
  27323. };
  27324. /**
  27325. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27326. * @param id defines the id to search for
  27327. * @return the found node or null if not found at all
  27328. */
  27329. Scene.prototype.getLastEntryByID = function (id) {
  27330. var index;
  27331. for (index = this.meshes.length - 1; index >= 0; index--) {
  27332. if (this.meshes[index].id === id) {
  27333. return this.meshes[index];
  27334. }
  27335. }
  27336. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27337. if (this.transformNodes[index].id === id) {
  27338. return this.transformNodes[index];
  27339. }
  27340. }
  27341. for (index = this.cameras.length - 1; index >= 0; index--) {
  27342. if (this.cameras[index].id === id) {
  27343. return this.cameras[index];
  27344. }
  27345. }
  27346. for (index = this.lights.length - 1; index >= 0; index--) {
  27347. if (this.lights[index].id === id) {
  27348. return this.lights[index];
  27349. }
  27350. }
  27351. return null;
  27352. };
  27353. /**
  27354. * Gets a node (Mesh, Camera, Light) using a given id
  27355. * @param id defines the id to search for
  27356. * @return the found node or null if not found at all
  27357. */
  27358. Scene.prototype.getNodeByID = function (id) {
  27359. var mesh = this.getMeshByID(id);
  27360. if (mesh) {
  27361. return mesh;
  27362. }
  27363. var light = this.getLightByID(id);
  27364. if (light) {
  27365. return light;
  27366. }
  27367. var camera = this.getCameraByID(id);
  27368. if (camera) {
  27369. return camera;
  27370. }
  27371. var bone = this.getBoneByID(id);
  27372. return bone;
  27373. };
  27374. /**
  27375. * Gets a node (Mesh, Camera, Light) using a given name
  27376. * @param name defines the name to search for
  27377. * @return the found node or null if not found at all.
  27378. */
  27379. Scene.prototype.getNodeByName = function (name) {
  27380. var mesh = this.getMeshByName(name);
  27381. if (mesh) {
  27382. return mesh;
  27383. }
  27384. var light = this.getLightByName(name);
  27385. if (light) {
  27386. return light;
  27387. }
  27388. var camera = this.getCameraByName(name);
  27389. if (camera) {
  27390. return camera;
  27391. }
  27392. var bone = this.getBoneByName(name);
  27393. return bone;
  27394. };
  27395. /**
  27396. * Gets a mesh using a given name
  27397. * @param name defines the name to search for
  27398. * @return the found mesh or null if not found at all.
  27399. */
  27400. Scene.prototype.getMeshByName = function (name) {
  27401. for (var index = 0; index < this.meshes.length; index++) {
  27402. if (this.meshes[index].name === name) {
  27403. return this.meshes[index];
  27404. }
  27405. }
  27406. return null;
  27407. };
  27408. /**
  27409. * Gets a transform node using a given name
  27410. * @param name defines the name to search for
  27411. * @return the found transform node or null if not found at all.
  27412. */
  27413. Scene.prototype.getTransformNodeByName = function (name) {
  27414. for (var index = 0; index < this.transformNodes.length; index++) {
  27415. if (this.transformNodes[index].name === name) {
  27416. return this.transformNodes[index];
  27417. }
  27418. }
  27419. return null;
  27420. };
  27421. /**
  27422. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27423. * @param id defines the id to search for
  27424. * @return the found skeleton or null if not found at all.
  27425. */
  27426. Scene.prototype.getLastSkeletonByID = function (id) {
  27427. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27428. if (this.skeletons[index].id === id) {
  27429. return this.skeletons[index];
  27430. }
  27431. }
  27432. return null;
  27433. };
  27434. /**
  27435. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27436. * @param id defines the id to search for
  27437. * @return the found skeleton or null if not found at all.
  27438. */
  27439. Scene.prototype.getSkeletonById = function (id) {
  27440. for (var index = 0; index < this.skeletons.length; index++) {
  27441. if (this.skeletons[index].id === id) {
  27442. return this.skeletons[index];
  27443. }
  27444. }
  27445. return null;
  27446. };
  27447. /**
  27448. * Gets a skeleton using a given name
  27449. * @param name defines the name to search for
  27450. * @return the found skeleton or null if not found at all.
  27451. */
  27452. Scene.prototype.getSkeletonByName = function (name) {
  27453. for (var index = 0; index < this.skeletons.length; index++) {
  27454. if (this.skeletons[index].name === name) {
  27455. return this.skeletons[index];
  27456. }
  27457. }
  27458. return null;
  27459. };
  27460. /**
  27461. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27462. * @param id defines the id to search for
  27463. * @return the found morph target manager or null if not found at all.
  27464. */
  27465. Scene.prototype.getMorphTargetManagerById = function (id) {
  27466. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27467. if (this.morphTargetManagers[index].uniqueId === id) {
  27468. return this.morphTargetManagers[index];
  27469. }
  27470. }
  27471. return null;
  27472. };
  27473. /**
  27474. * Gets a boolean indicating if the given mesh is active
  27475. * @param mesh defines the mesh to look for
  27476. * @returns true if the mesh is in the active list
  27477. */
  27478. Scene.prototype.isActiveMesh = function (mesh) {
  27479. return (this._activeMeshes.indexOf(mesh) !== -1);
  27480. };
  27481. Object.defineProperty(Scene.prototype, "uid", {
  27482. /**
  27483. * Return a unique id as a string which can serve as an identifier for the scene
  27484. */
  27485. get: function () {
  27486. if (!this._uid) {
  27487. this._uid = BABYLON.Tools.RandomId();
  27488. }
  27489. return this._uid;
  27490. },
  27491. enumerable: true,
  27492. configurable: true
  27493. });
  27494. /**
  27495. * Add an externaly attached data from its key.
  27496. * This method call will fail and return false, if such key already exists.
  27497. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27498. * @param key the unique key that identifies the data
  27499. * @param data the data object to associate to the key for this Engine instance
  27500. * @return true if no such key were already present and the data was added successfully, false otherwise
  27501. */
  27502. Scene.prototype.addExternalData = function (key, data) {
  27503. if (!this._externalData) {
  27504. this._externalData = new BABYLON.StringDictionary();
  27505. }
  27506. return this._externalData.add(key, data);
  27507. };
  27508. /**
  27509. * Get an externaly attached data from its key
  27510. * @param key the unique key that identifies the data
  27511. * @return the associated data, if present (can be null), or undefined if not present
  27512. */
  27513. Scene.prototype.getExternalData = function (key) {
  27514. if (!this._externalData) {
  27515. return null;
  27516. }
  27517. return this._externalData.get(key);
  27518. };
  27519. /**
  27520. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27521. * @param key the unique key that identifies the data
  27522. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27523. * @return the associated data, can be null if the factory returned null.
  27524. */
  27525. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27526. if (!this._externalData) {
  27527. this._externalData = new BABYLON.StringDictionary();
  27528. }
  27529. return this._externalData.getOrAddWithFactory(key, factory);
  27530. };
  27531. /**
  27532. * Remove an externaly attached data from the Engine instance
  27533. * @param key the unique key that identifies the data
  27534. * @return true if the data was successfully removed, false if it doesn't exist
  27535. */
  27536. Scene.prototype.removeExternalData = function (key) {
  27537. return this._externalData.remove(key);
  27538. };
  27539. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27540. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27541. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27542. var step = _a[_i];
  27543. step.action(mesh, subMesh);
  27544. }
  27545. var material = subMesh.getMaterial();
  27546. if (material !== null && material !== undefined) {
  27547. // Render targets
  27548. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27549. if (this._processedMaterials.indexOf(material) === -1) {
  27550. this._processedMaterials.push(material);
  27551. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27552. }
  27553. }
  27554. // Dispatch
  27555. this._activeIndices.addCount(subMesh.indexCount, false);
  27556. this._renderingManager.dispatch(subMesh, mesh, material);
  27557. }
  27558. }
  27559. };
  27560. /**
  27561. * Clear the processed materials smart array preventing retention point in material dispose.
  27562. */
  27563. Scene.prototype.freeProcessedMaterials = function () {
  27564. this._processedMaterials.dispose();
  27565. };
  27566. /**
  27567. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27568. */
  27569. Scene.prototype.freeActiveMeshes = function () {
  27570. this._activeMeshes.dispose();
  27571. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27572. this.activeCamera._activeMeshes.dispose();
  27573. }
  27574. if (this.activeCameras) {
  27575. for (var i = 0; i < this.activeCameras.length; i++) {
  27576. var activeCamera = this.activeCameras[i];
  27577. if (activeCamera && activeCamera._activeMeshes) {
  27578. activeCamera._activeMeshes.dispose();
  27579. }
  27580. }
  27581. }
  27582. };
  27583. /**
  27584. * Clear the info related to rendering groups preventing retention points during dispose.
  27585. */
  27586. Scene.prototype.freeRenderingGroups = function () {
  27587. if (this._renderingManager) {
  27588. this._renderingManager.freeRenderingGroups();
  27589. }
  27590. if (this.textures) {
  27591. for (var i = 0; i < this.textures.length; i++) {
  27592. var texture = this.textures[i];
  27593. if (texture && texture.renderList) {
  27594. texture.freeRenderingGroups();
  27595. }
  27596. }
  27597. }
  27598. };
  27599. /** @hidden */
  27600. Scene.prototype._isInIntermediateRendering = function () {
  27601. return this._intermediateRendering;
  27602. };
  27603. /**
  27604. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27605. * @returns the current scene
  27606. */
  27607. Scene.prototype.freezeActiveMeshes = function () {
  27608. if (!this.activeCamera) {
  27609. return this;
  27610. }
  27611. if (!this._frustumPlanes) {
  27612. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27613. }
  27614. this._evaluateActiveMeshes();
  27615. this._activeMeshesFrozen = true;
  27616. return this;
  27617. };
  27618. /**
  27619. * Use this function to restart evaluating active meshes on every frame
  27620. * @returns the current scene
  27621. */
  27622. Scene.prototype.unfreezeActiveMeshes = function () {
  27623. this._activeMeshesFrozen = false;
  27624. return this;
  27625. };
  27626. Scene.prototype._evaluateActiveMeshes = function () {
  27627. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27628. return;
  27629. }
  27630. if (!this.activeCamera) {
  27631. return;
  27632. }
  27633. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27634. this.activeCamera._activeMeshes.reset();
  27635. this._activeMeshes.reset();
  27636. this._renderingManager.reset();
  27637. this._processedMaterials.reset();
  27638. this._activeParticleSystems.reset();
  27639. this._activeSkeletons.reset();
  27640. this._softwareSkinnedMeshes.reset();
  27641. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27642. var step = _a[_i];
  27643. step.action();
  27644. }
  27645. // Determine mesh candidates
  27646. var meshes = this.getActiveMeshCandidates();
  27647. // Check each mesh
  27648. var len = meshes.length;
  27649. for (var i = 0; i < len; i++) {
  27650. var mesh = meshes.data[i];
  27651. if (mesh.isBlocked) {
  27652. continue;
  27653. }
  27654. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27655. if (!mesh.isReady() || !mesh.isEnabled()) {
  27656. continue;
  27657. }
  27658. mesh.computeWorldMatrix();
  27659. // Intersections
  27660. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27661. this._meshesForIntersections.pushNoDuplicate(mesh);
  27662. }
  27663. // Switch to current LOD
  27664. var meshLOD = mesh.getLOD(this.activeCamera);
  27665. if (meshLOD === undefined || meshLOD === null) {
  27666. continue;
  27667. }
  27668. mesh._preActivate();
  27669. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27670. this._activeMeshes.push(mesh);
  27671. this.activeCamera._activeMeshes.push(mesh);
  27672. mesh._activate(this._renderId);
  27673. if (meshLOD !== mesh) {
  27674. meshLOD._activate(this._renderId);
  27675. }
  27676. this._activeMesh(mesh, meshLOD);
  27677. }
  27678. }
  27679. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27680. // Particle systems
  27681. if (this.particlesEnabled) {
  27682. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27683. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27684. var particleSystem = this.particleSystems[particleIndex];
  27685. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27686. continue;
  27687. }
  27688. var emitter = particleSystem.emitter;
  27689. if (!emitter.position || emitter.isEnabled()) {
  27690. this._activeParticleSystems.push(particleSystem);
  27691. particleSystem.animate();
  27692. this._renderingManager.dispatchParticles(particleSystem);
  27693. }
  27694. }
  27695. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27696. }
  27697. };
  27698. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27699. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27700. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27701. mesh.skeleton.prepare();
  27702. }
  27703. if (!mesh.computeBonesUsingShaders) {
  27704. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27705. }
  27706. }
  27707. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27708. var step = _a[_i];
  27709. step.action(sourceMesh, mesh);
  27710. }
  27711. if (mesh !== undefined && mesh !== null
  27712. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27713. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27714. var len = subMeshes.length;
  27715. for (var i = 0; i < len; i++) {
  27716. var subMesh = subMeshes.data[i];
  27717. this._evaluateSubMesh(subMesh, mesh);
  27718. }
  27719. }
  27720. };
  27721. /**
  27722. * Update the transform matrix to update from the current active camera
  27723. * @param force defines a boolean used to force the update even if cache is up to date
  27724. */
  27725. Scene.prototype.updateTransformMatrix = function (force) {
  27726. if (!this.activeCamera) {
  27727. return;
  27728. }
  27729. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27730. };
  27731. /**
  27732. * 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)
  27733. * @param alternateCamera defines the camera to use
  27734. */
  27735. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27736. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27737. };
  27738. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27739. if (camera && camera._skipRendering) {
  27740. return;
  27741. }
  27742. var engine = this._engine;
  27743. this.activeCamera = camera;
  27744. if (!this.activeCamera)
  27745. throw new Error("Active camera not set");
  27746. // Viewport
  27747. engine.setViewport(this.activeCamera.viewport);
  27748. // Camera
  27749. this.resetCachedMaterial();
  27750. this._renderId++;
  27751. this.updateTransformMatrix();
  27752. if (camera._alternateCamera) {
  27753. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27754. this._alternateRendering = true;
  27755. }
  27756. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27757. // Meshes
  27758. this._evaluateActiveMeshes();
  27759. // Software skinning
  27760. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27761. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27762. mesh.applySkeleton(mesh.skeleton);
  27763. }
  27764. // Render targets
  27765. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27766. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27767. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27768. }
  27769. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27770. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27771. }
  27772. // Collects render targets from external components.
  27773. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27774. var step = _a[_i];
  27775. step.action(this._renderTargets);
  27776. }
  27777. if (this.renderTargetsEnabled) {
  27778. this._intermediateRendering = true;
  27779. if (this._renderTargets.length > 0) {
  27780. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27781. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27782. var renderTarget = this._renderTargets.data[renderIndex];
  27783. if (renderTarget._shouldRender()) {
  27784. this._renderId++;
  27785. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27786. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27787. }
  27788. }
  27789. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27790. this._renderId++;
  27791. }
  27792. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27793. var step = _c[_b];
  27794. step.action(this.activeCamera);
  27795. }
  27796. this._intermediateRendering = false;
  27797. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27798. }
  27799. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27800. // Prepare Frame
  27801. if (this.postProcessManager) {
  27802. this.postProcessManager._prepareFrame();
  27803. }
  27804. // Before Camera Draw
  27805. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27806. var step = _e[_d];
  27807. step.action(this.activeCamera);
  27808. }
  27809. // Render
  27810. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27811. this._renderingManager.render(null, null, true, true);
  27812. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27813. // After Camera Draw
  27814. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27815. var step = _g[_f];
  27816. step.action(this.activeCamera);
  27817. }
  27818. // Finalize frame
  27819. if (this.postProcessManager) {
  27820. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27821. }
  27822. // Reset some special arrays
  27823. this._renderTargets.reset();
  27824. this._alternateRendering = false;
  27825. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27826. };
  27827. Scene.prototype._processSubCameras = function (camera) {
  27828. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27829. this._renderForCamera(camera);
  27830. return;
  27831. }
  27832. // rig cameras
  27833. for (var index = 0; index < camera._rigCameras.length; index++) {
  27834. this._renderForCamera(camera._rigCameras[index], camera);
  27835. }
  27836. this.activeCamera = camera;
  27837. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27838. };
  27839. Scene.prototype._checkIntersections = function () {
  27840. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27841. var sourceMesh = this._meshesForIntersections.data[index];
  27842. if (!sourceMesh.actionManager) {
  27843. continue;
  27844. }
  27845. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27846. var action = sourceMesh.actionManager.actions[actionIndex];
  27847. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27848. var parameters = action.getTriggerParameter();
  27849. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27850. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27851. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27852. if (areIntersecting && currentIntersectionInProgress === -1) {
  27853. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27854. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27855. sourceMesh._intersectionsInProgress.push(otherMesh);
  27856. }
  27857. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27858. sourceMesh._intersectionsInProgress.push(otherMesh);
  27859. }
  27860. }
  27861. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27862. //They intersected, and now they don't.
  27863. //is this trigger an exit trigger? execute an event.
  27864. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27865. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27866. }
  27867. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27868. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27869. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27870. return otherMesh === parameterMesh;
  27871. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27872. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27873. }
  27874. }
  27875. }
  27876. }
  27877. }
  27878. };
  27879. /** @hidden */
  27880. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27881. // Do nothing. Code will be replaced if physics engine component is referenced
  27882. };
  27883. /**
  27884. * Render the scene
  27885. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27886. */
  27887. Scene.prototype.render = function (updateCameras) {
  27888. if (updateCameras === void 0) { updateCameras = true; }
  27889. if (this.isDisposed) {
  27890. return;
  27891. }
  27892. this._frameId++;
  27893. // Register components that have been associated lately to the scene.
  27894. this._registerTransientComponents();
  27895. this._activeParticles.fetchNewFrame();
  27896. this._totalVertices.fetchNewFrame();
  27897. this._activeIndices.fetchNewFrame();
  27898. this._activeBones.fetchNewFrame();
  27899. this._meshesForIntersections.reset();
  27900. this.resetCachedMaterial();
  27901. this.onBeforeAnimationsObservable.notifyObservers(this);
  27902. // Actions
  27903. if (this.actionManager) {
  27904. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27905. }
  27906. if (this._engine.isDeterministicLockStep()) {
  27907. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27908. var defaultFPS = (60.0 / 1000.0);
  27909. var defaultFrameTime = this.getDeterministicFrameTime();
  27910. var stepsTaken = 0;
  27911. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27912. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27913. internalSteps = Math.min(internalSteps, maxSubSteps);
  27914. do {
  27915. this.onBeforeStepObservable.notifyObservers(this);
  27916. // Animations
  27917. this._animationRatio = defaultFrameTime * defaultFPS;
  27918. this._animate();
  27919. this.onAfterAnimationsObservable.notifyObservers(this);
  27920. // Physics
  27921. this._advancePhysicsEngineStep(defaultFrameTime);
  27922. this.onAfterStepObservable.notifyObservers(this);
  27923. this._currentStepId++;
  27924. stepsTaken++;
  27925. deltaTime -= defaultFrameTime;
  27926. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27927. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27928. }
  27929. else {
  27930. // Animations
  27931. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27932. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27933. this._animate();
  27934. this.onAfterAnimationsObservable.notifyObservers(this);
  27935. // Physics
  27936. this._advancePhysicsEngineStep(deltaTime);
  27937. }
  27938. // Before camera update steps
  27939. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27940. var step = _a[_i];
  27941. step.action();
  27942. }
  27943. // Update Cameras
  27944. if (updateCameras) {
  27945. if (this.activeCameras.length > 0) {
  27946. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27947. var camera = this.activeCameras[cameraIndex];
  27948. camera.update();
  27949. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27950. // rig cameras
  27951. for (var index = 0; index < camera._rigCameras.length; index++) {
  27952. camera._rigCameras[index].update();
  27953. }
  27954. }
  27955. }
  27956. }
  27957. else if (this.activeCamera) {
  27958. this.activeCamera.update();
  27959. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27960. // rig cameras
  27961. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27962. this.activeCamera._rigCameras[index].update();
  27963. }
  27964. }
  27965. }
  27966. }
  27967. // Before render
  27968. this.onBeforeRenderObservable.notifyObservers(this);
  27969. // Customs render targets
  27970. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27971. var engine = this.getEngine();
  27972. var currentActiveCamera = this.activeCamera;
  27973. if (this.renderTargetsEnabled) {
  27974. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27975. this._intermediateRendering = true;
  27976. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27977. var renderTarget = this.customRenderTargets[customIndex];
  27978. if (renderTarget._shouldRender()) {
  27979. this._renderId++;
  27980. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27981. if (!this.activeCamera)
  27982. throw new Error("Active camera not set");
  27983. // Viewport
  27984. engine.setViewport(this.activeCamera.viewport);
  27985. // Camera
  27986. this.updateTransformMatrix();
  27987. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27988. }
  27989. }
  27990. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27991. this._intermediateRendering = false;
  27992. this._renderId++;
  27993. }
  27994. // Restore back buffer
  27995. if (this.customRenderTargets.length > 0) {
  27996. engine.restoreDefaultFramebuffer();
  27997. }
  27998. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27999. this.activeCamera = currentActiveCamera;
  28000. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28001. var step = _c[_b];
  28002. step.action();
  28003. }
  28004. // Clear
  28005. if (this.autoClearDepthAndStencil || this.autoClear) {
  28006. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28007. }
  28008. // Collects render targets from external components.
  28009. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28010. var step = _e[_d];
  28011. step.action(this._renderTargets);
  28012. }
  28013. // Multi-cameras?
  28014. if (this.activeCameras.length > 0) {
  28015. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28016. if (cameraIndex > 0) {
  28017. this._engine.clear(null, false, true, true);
  28018. }
  28019. this._processSubCameras(this.activeCameras[cameraIndex]);
  28020. }
  28021. }
  28022. else {
  28023. if (!this.activeCamera) {
  28024. throw new Error("No camera defined");
  28025. }
  28026. this._processSubCameras(this.activeCamera);
  28027. }
  28028. // Intersection checks
  28029. this._checkIntersections();
  28030. // Executes the after render stage actions.
  28031. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28032. var step = _g[_f];
  28033. step.action();
  28034. }
  28035. // After render
  28036. if (this.afterRender) {
  28037. this.afterRender();
  28038. }
  28039. this.onAfterRenderObservable.notifyObservers(this);
  28040. // Cleaning
  28041. if (this._toBeDisposed.length) {
  28042. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28043. var data = this._toBeDisposed[index];
  28044. if (data) {
  28045. data.dispose();
  28046. }
  28047. }
  28048. this._toBeDisposed = [];
  28049. }
  28050. if (this.dumpNextRenderTargets) {
  28051. this.dumpNextRenderTargets = false;
  28052. }
  28053. this._activeBones.addCount(0, true);
  28054. this._activeIndices.addCount(0, true);
  28055. this._activeParticles.addCount(0, true);
  28056. };
  28057. /**
  28058. * Freeze all materials
  28059. * A frozen material will not be updatable but should be faster to render
  28060. */
  28061. Scene.prototype.freezeMaterials = function () {
  28062. for (var i = 0; i < this.materials.length; i++) {
  28063. this.materials[i].freeze();
  28064. }
  28065. };
  28066. /**
  28067. * Unfreeze all materials
  28068. * A frozen material will not be updatable but should be faster to render
  28069. */
  28070. Scene.prototype.unfreezeMaterials = function () {
  28071. for (var i = 0; i < this.materials.length; i++) {
  28072. this.materials[i].unfreeze();
  28073. }
  28074. };
  28075. /**
  28076. * Releases all held ressources
  28077. */
  28078. Scene.prototype.dispose = function () {
  28079. this.beforeRender = null;
  28080. this.afterRender = null;
  28081. this.skeletons = [];
  28082. this.morphTargetManagers = [];
  28083. this._transientComponents = [];
  28084. this._isReadyForMeshStage.clear();
  28085. this._beforeEvaluateActiveMeshStage.clear();
  28086. this._evaluateSubMeshStage.clear();
  28087. this._activeMeshStage.clear();
  28088. this._cameraDrawRenderTargetStage.clear();
  28089. this._beforeCameraDrawStage.clear();
  28090. this._beforeRenderingGroupDrawStage.clear();
  28091. this._beforeRenderingMeshStage.clear();
  28092. this._afterRenderingMeshStage.clear();
  28093. this._afterRenderingGroupDrawStage.clear();
  28094. this._afterCameraDrawStage.clear();
  28095. this._afterRenderStage.clear();
  28096. this._beforeCameraUpdateStage.clear();
  28097. this._beforeClearStage.clear();
  28098. this._gatherRenderTargetsStage.clear();
  28099. this._gatherActiveCameraRenderTargetsStage.clear();
  28100. this._pointerMoveStage.clear();
  28101. this._pointerDownStage.clear();
  28102. this._pointerUpStage.clear();
  28103. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28104. var component = _a[_i];
  28105. component.dispose();
  28106. }
  28107. this.importedMeshesFiles = new Array();
  28108. this.stopAllAnimations();
  28109. this.resetCachedMaterial();
  28110. // Smart arrays
  28111. if (this.activeCamera) {
  28112. this.activeCamera._activeMeshes.dispose();
  28113. this.activeCamera = null;
  28114. }
  28115. this._activeMeshes.dispose();
  28116. this._renderingManager.dispose();
  28117. this._processedMaterials.dispose();
  28118. this._activeParticleSystems.dispose();
  28119. this._activeSkeletons.dispose();
  28120. this._softwareSkinnedMeshes.dispose();
  28121. this._renderTargets.dispose();
  28122. this._registeredForLateAnimationBindings.dispose();
  28123. this._meshesForIntersections.dispose();
  28124. this._toBeDisposed = [];
  28125. // Abort active requests
  28126. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28127. var request = _c[_b];
  28128. request.abort();
  28129. }
  28130. // Events
  28131. this.onDisposeObservable.notifyObservers(this);
  28132. this.onDisposeObservable.clear();
  28133. this.onBeforeRenderObservable.clear();
  28134. this.onAfterRenderObservable.clear();
  28135. this.onBeforeRenderTargetsRenderObservable.clear();
  28136. this.onAfterRenderTargetsRenderObservable.clear();
  28137. this.onAfterStepObservable.clear();
  28138. this.onBeforeStepObservable.clear();
  28139. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28140. this.onAfterActiveMeshesEvaluationObservable.clear();
  28141. this.onBeforeParticlesRenderingObservable.clear();
  28142. this.onAfterParticlesRenderingObservable.clear();
  28143. this.onBeforeDrawPhaseObservable.clear();
  28144. this.onAfterDrawPhaseObservable.clear();
  28145. this.onBeforeAnimationsObservable.clear();
  28146. this.onAfterAnimationsObservable.clear();
  28147. this.onDataLoadedObservable.clear();
  28148. this.onBeforeRenderingGroupObservable.clear();
  28149. this.onAfterRenderingGroupObservable.clear();
  28150. this.onMeshImportedObservable.clear();
  28151. this.detachControl();
  28152. // Detach cameras
  28153. var canvas = this._engine.getRenderingCanvas();
  28154. if (canvas) {
  28155. var index;
  28156. for (index = 0; index < this.cameras.length; index++) {
  28157. this.cameras[index].detachControl(canvas);
  28158. }
  28159. }
  28160. // Release animation groups
  28161. while (this.animationGroups.length) {
  28162. this.animationGroups[0].dispose();
  28163. }
  28164. // Release lights
  28165. while (this.lights.length) {
  28166. this.lights[0].dispose();
  28167. }
  28168. // Release meshes
  28169. while (this.meshes.length) {
  28170. this.meshes[0].dispose(true);
  28171. }
  28172. while (this.transformNodes.length) {
  28173. this.removeTransformNode(this.transformNodes[0]);
  28174. }
  28175. // Release cameras
  28176. while (this.cameras.length) {
  28177. this.cameras[0].dispose();
  28178. }
  28179. // Release materials
  28180. if (this.defaultMaterial) {
  28181. this.defaultMaterial.dispose();
  28182. }
  28183. while (this.multiMaterials.length) {
  28184. this.multiMaterials[0].dispose();
  28185. }
  28186. while (this.materials.length) {
  28187. this.materials[0].dispose();
  28188. }
  28189. // Release particles
  28190. while (this.particleSystems.length) {
  28191. this.particleSystems[0].dispose();
  28192. }
  28193. // Release postProcesses
  28194. while (this.postProcesses.length) {
  28195. this.postProcesses[0].dispose();
  28196. }
  28197. // Release textures
  28198. while (this.textures.length) {
  28199. this.textures[0].dispose();
  28200. }
  28201. // Release UBO
  28202. this._sceneUbo.dispose();
  28203. if (this._alternateSceneUbo) {
  28204. this._alternateSceneUbo.dispose();
  28205. }
  28206. // Post-processes
  28207. this.postProcessManager.dispose();
  28208. // Remove from engine
  28209. index = this._engine.scenes.indexOf(this);
  28210. if (index > -1) {
  28211. this._engine.scenes.splice(index, 1);
  28212. }
  28213. this._engine.wipeCaches(true);
  28214. this._isDisposed = true;
  28215. };
  28216. Object.defineProperty(Scene.prototype, "isDisposed", {
  28217. /**
  28218. * Gets if the scene is already disposed
  28219. */
  28220. get: function () {
  28221. return this._isDisposed;
  28222. },
  28223. enumerable: true,
  28224. configurable: true
  28225. });
  28226. /**
  28227. * Call this function to reduce memory footprint of the scene.
  28228. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28229. */
  28230. Scene.prototype.clearCachedVertexData = function () {
  28231. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28232. var mesh = this.meshes[meshIndex];
  28233. var geometry = mesh.geometry;
  28234. if (geometry) {
  28235. geometry._indices = [];
  28236. for (var vbName in geometry._vertexBuffers) {
  28237. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28238. continue;
  28239. }
  28240. geometry._vertexBuffers[vbName]._buffer._data = null;
  28241. }
  28242. }
  28243. }
  28244. };
  28245. /**
  28246. * This function will remove the local cached buffer data from texture.
  28247. * It will save memory but will prevent the texture from being rebuilt
  28248. */
  28249. Scene.prototype.cleanCachedTextureBuffer = function () {
  28250. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28251. var baseTexture = _a[_i];
  28252. var buffer = baseTexture._buffer;
  28253. if (buffer) {
  28254. baseTexture._buffer = null;
  28255. }
  28256. }
  28257. };
  28258. /**
  28259. * Get the world extend vectors with an optional filter
  28260. *
  28261. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28262. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28263. */
  28264. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28265. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28266. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28267. filterPredicate = filterPredicate || (function () { return true; });
  28268. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28269. mesh.computeWorldMatrix(true);
  28270. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28271. return;
  28272. }
  28273. var boundingInfo = mesh.getBoundingInfo();
  28274. var minBox = boundingInfo.boundingBox.minimumWorld;
  28275. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28276. BABYLON.Tools.CheckExtends(minBox, min, max);
  28277. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28278. });
  28279. return {
  28280. min: min,
  28281. max: max
  28282. };
  28283. };
  28284. // Picking
  28285. /**
  28286. * Creates a ray that can be used to pick in the scene
  28287. * @param x defines the x coordinate of the origin (on-screen)
  28288. * @param y defines the y coordinate of the origin (on-screen)
  28289. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28290. * @param camera defines the camera to use for the picking
  28291. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28292. * @returns a Ray
  28293. */
  28294. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28295. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28296. var result = BABYLON.Ray.Zero();
  28297. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28298. return result;
  28299. };
  28300. /**
  28301. * Creates a ray that can be used to pick in the scene
  28302. * @param x defines the x coordinate of the origin (on-screen)
  28303. * @param y defines the y coordinate of the origin (on-screen)
  28304. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28305. * @param result defines the ray where to store the picking ray
  28306. * @param camera defines the camera to use for the picking
  28307. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28308. * @returns the current scene
  28309. */
  28310. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28311. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28312. var engine = this._engine;
  28313. if (!camera) {
  28314. if (!this.activeCamera)
  28315. throw new Error("Active camera not set");
  28316. camera = this.activeCamera;
  28317. }
  28318. var cameraViewport = camera.viewport;
  28319. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28320. // Moving coordinates to local viewport world
  28321. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28322. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28323. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28324. return this;
  28325. };
  28326. /**
  28327. * Creates a ray that can be used to pick in the scene
  28328. * @param x defines the x coordinate of the origin (on-screen)
  28329. * @param y defines the y coordinate of the origin (on-screen)
  28330. * @param camera defines the camera to use for the picking
  28331. * @returns a Ray
  28332. */
  28333. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28334. var result = BABYLON.Ray.Zero();
  28335. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28336. return result;
  28337. };
  28338. /**
  28339. * Creates a ray that can be used to pick in the scene
  28340. * @param x defines the x coordinate of the origin (on-screen)
  28341. * @param y defines the y coordinate of the origin (on-screen)
  28342. * @param result defines the ray where to store the picking ray
  28343. * @param camera defines the camera to use for the picking
  28344. * @returns the current scene
  28345. */
  28346. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28347. if (!BABYLON.PickingInfo) {
  28348. return this;
  28349. }
  28350. var engine = this._engine;
  28351. if (!camera) {
  28352. if (!this.activeCamera)
  28353. throw new Error("Active camera not set");
  28354. camera = this.activeCamera;
  28355. }
  28356. var cameraViewport = camera.viewport;
  28357. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28358. var identity = BABYLON.Matrix.Identity();
  28359. // Moving coordinates to local viewport world
  28360. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28361. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28362. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28363. return this;
  28364. };
  28365. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28366. if (!BABYLON.PickingInfo) {
  28367. return null;
  28368. }
  28369. var pickingInfo = null;
  28370. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28371. var mesh = this.meshes[meshIndex];
  28372. if (predicate) {
  28373. if (!predicate(mesh)) {
  28374. continue;
  28375. }
  28376. }
  28377. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28378. continue;
  28379. }
  28380. var world = mesh.getWorldMatrix();
  28381. var ray = rayFunction(world);
  28382. var result = mesh.intersects(ray, fastCheck);
  28383. if (!result || !result.hit)
  28384. continue;
  28385. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28386. continue;
  28387. pickingInfo = result;
  28388. if (fastCheck) {
  28389. break;
  28390. }
  28391. }
  28392. return pickingInfo || new BABYLON.PickingInfo();
  28393. };
  28394. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28395. if (!BABYLON.PickingInfo) {
  28396. return null;
  28397. }
  28398. var pickingInfos = new Array();
  28399. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28400. var mesh = this.meshes[meshIndex];
  28401. if (predicate) {
  28402. if (!predicate(mesh)) {
  28403. continue;
  28404. }
  28405. }
  28406. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28407. continue;
  28408. }
  28409. var world = mesh.getWorldMatrix();
  28410. var ray = rayFunction(world);
  28411. var result = mesh.intersects(ray, false);
  28412. if (!result || !result.hit)
  28413. continue;
  28414. pickingInfos.push(result);
  28415. }
  28416. return pickingInfos;
  28417. };
  28418. /** Launch a ray to try to pick a mesh in the scene
  28419. * @param x position on screen
  28420. * @param y position on screen
  28421. * @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
  28422. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28423. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28424. * @returns a PickingInfo
  28425. */
  28426. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28427. var _this = this;
  28428. if (!BABYLON.PickingInfo) {
  28429. return null;
  28430. }
  28431. var result = this._internalPick(function (world) {
  28432. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28433. return _this._tempPickingRay;
  28434. }, predicate, fastCheck);
  28435. if (result) {
  28436. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28437. }
  28438. return result;
  28439. };
  28440. /** Use the given ray to pick a mesh in the scene
  28441. * @param ray The ray to use to pick meshes
  28442. * @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
  28443. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28444. * @returns a PickingInfo
  28445. */
  28446. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28447. var _this = this;
  28448. var result = this._internalPick(function (world) {
  28449. if (!_this._pickWithRayInverseMatrix) {
  28450. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28451. }
  28452. world.invertToRef(_this._pickWithRayInverseMatrix);
  28453. if (!_this._cachedRayForTransform) {
  28454. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28455. }
  28456. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28457. return _this._cachedRayForTransform;
  28458. }, predicate, fastCheck);
  28459. if (result) {
  28460. result.ray = ray;
  28461. }
  28462. return result;
  28463. };
  28464. /**
  28465. * Launch a ray to try to pick a mesh in the scene
  28466. * @param x X position on screen
  28467. * @param y Y position on screen
  28468. * @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
  28469. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28470. * @returns an array of PickingInfo
  28471. */
  28472. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28473. var _this = this;
  28474. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28475. };
  28476. /**
  28477. * Launch a ray to try to pick a mesh in the scene
  28478. * @param ray Ray to use
  28479. * @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
  28480. * @returns an array of PickingInfo
  28481. */
  28482. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28483. var _this = this;
  28484. return this._internalMultiPick(function (world) {
  28485. if (!_this._pickWithRayInverseMatrix) {
  28486. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28487. }
  28488. world.invertToRef(_this._pickWithRayInverseMatrix);
  28489. if (!_this._cachedRayForTransform) {
  28490. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28491. }
  28492. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28493. return _this._cachedRayForTransform;
  28494. }, predicate);
  28495. };
  28496. /**
  28497. * Force the value of meshUnderPointer
  28498. * @param mesh defines the mesh to use
  28499. */
  28500. Scene.prototype.setPointerOverMesh = function (mesh) {
  28501. if (this._pointerOverMesh === mesh) {
  28502. return;
  28503. }
  28504. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28505. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28506. }
  28507. this._pointerOverMesh = mesh;
  28508. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28509. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28510. }
  28511. };
  28512. /**
  28513. * Gets the mesh under the pointer
  28514. * @returns a Mesh or null if no mesh is under the pointer
  28515. */
  28516. Scene.prototype.getPointerOverMesh = function () {
  28517. return this._pointerOverMesh;
  28518. };
  28519. // Misc.
  28520. /** @hidden */
  28521. Scene.prototype._rebuildGeometries = function () {
  28522. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28523. var geometry = _a[_i];
  28524. geometry._rebuild();
  28525. }
  28526. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28527. var mesh = _c[_b];
  28528. mesh._rebuild();
  28529. }
  28530. if (this.postProcessManager) {
  28531. this.postProcessManager._rebuild();
  28532. }
  28533. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28534. var component = _e[_d];
  28535. component.rebuild();
  28536. }
  28537. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28538. var system = _g[_f];
  28539. system.rebuild();
  28540. }
  28541. };
  28542. /** @hidden */
  28543. Scene.prototype._rebuildTextures = function () {
  28544. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28545. var texture = _a[_i];
  28546. texture._rebuild();
  28547. }
  28548. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28549. };
  28550. // Tags
  28551. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28552. if (tagsQuery === undefined) {
  28553. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28554. return list;
  28555. }
  28556. var listByTags = [];
  28557. forEach = forEach || (function (item) { return; });
  28558. for (var i in list) {
  28559. var item = list[i];
  28560. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28561. listByTags.push(item);
  28562. forEach(item);
  28563. }
  28564. }
  28565. return listByTags;
  28566. };
  28567. /**
  28568. * Get a list of meshes by tags
  28569. * @param tagsQuery defines the tags query to use
  28570. * @param forEach defines a predicate used to filter results
  28571. * @returns an array of Mesh
  28572. */
  28573. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28574. return this._getByTags(this.meshes, tagsQuery, forEach);
  28575. };
  28576. /**
  28577. * Get a list of cameras by tags
  28578. * @param tagsQuery defines the tags query to use
  28579. * @param forEach defines a predicate used to filter results
  28580. * @returns an array of Camera
  28581. */
  28582. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28583. return this._getByTags(this.cameras, tagsQuery, forEach);
  28584. };
  28585. /**
  28586. * Get a list of lights by tags
  28587. * @param tagsQuery defines the tags query to use
  28588. * @param forEach defines a predicate used to filter results
  28589. * @returns an array of Light
  28590. */
  28591. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28592. return this._getByTags(this.lights, tagsQuery, forEach);
  28593. };
  28594. /**
  28595. * Get a list of materials by tags
  28596. * @param tagsQuery defines the tags query to use
  28597. * @param forEach defines a predicate used to filter results
  28598. * @returns an array of Material
  28599. */
  28600. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28601. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28602. };
  28603. /**
  28604. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28605. * This allowed control for front to back rendering or reversly depending of the special needs.
  28606. *
  28607. * @param renderingGroupId The rendering group id corresponding to its index
  28608. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28609. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28610. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28611. */
  28612. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28613. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28614. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28615. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28616. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28617. };
  28618. /**
  28619. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28620. *
  28621. * @param renderingGroupId The rendering group id corresponding to its index
  28622. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28623. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28624. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28625. */
  28626. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28627. if (depth === void 0) { depth = true; }
  28628. if (stencil === void 0) { stencil = true; }
  28629. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28630. };
  28631. /**
  28632. * Gets the current auto clear configuration for one rendering group of the rendering
  28633. * manager.
  28634. * @param index the rendering group index to get the information for
  28635. * @returns The auto clear setup for the requested rendering group
  28636. */
  28637. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28638. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28639. };
  28640. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28641. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28642. get: function () {
  28643. return this._blockMaterialDirtyMechanism;
  28644. },
  28645. set: function (value) {
  28646. if (this._blockMaterialDirtyMechanism === value) {
  28647. return;
  28648. }
  28649. this._blockMaterialDirtyMechanism = value;
  28650. if (!value) { // Do a complete update
  28651. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28652. }
  28653. },
  28654. enumerable: true,
  28655. configurable: true
  28656. });
  28657. /**
  28658. * Will flag all materials as dirty to trigger new shader compilation
  28659. * @param flag defines the flag used to specify which material part must be marked as dirty
  28660. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28661. */
  28662. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28663. if (this._blockMaterialDirtyMechanism) {
  28664. return;
  28665. }
  28666. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28667. var material = _a[_i];
  28668. if (predicate && !predicate(material)) {
  28669. continue;
  28670. }
  28671. material.markAsDirty(flag);
  28672. }
  28673. };
  28674. /** @hidden */
  28675. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28676. var _this = this;
  28677. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28678. this._activeRequests.push(request);
  28679. request.onCompleteObservable.add(function (request) {
  28680. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28681. });
  28682. return request;
  28683. };
  28684. /** @hidden */
  28685. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28686. var _this = this;
  28687. return new Promise(function (resolve, reject) {
  28688. _this._loadFile(url, function (data) {
  28689. resolve(data);
  28690. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28691. reject(exception);
  28692. });
  28693. });
  28694. };
  28695. // Statics
  28696. Scene._uniqueIdCounter = 0;
  28697. /** The fog is deactivated */
  28698. Scene.FOGMODE_NONE = 0;
  28699. /** The fog density is following an exponential function */
  28700. Scene.FOGMODE_EXP = 1;
  28701. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28702. Scene.FOGMODE_EXP2 = 2;
  28703. /** The fog density is following a linear function. */
  28704. Scene.FOGMODE_LINEAR = 3;
  28705. /**
  28706. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28707. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28708. */
  28709. Scene.MinDeltaTime = 1.0;
  28710. /**
  28711. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28712. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28713. */
  28714. Scene.MaxDeltaTime = 1000.0;
  28715. /** The distance in pixel that you have to move to prevent some events */
  28716. Scene.DragMovementThreshold = 10; // in pixels
  28717. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28718. Scene.LongPressDelay = 500; // in milliseconds
  28719. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28720. Scene.DoubleClickDelay = 300; // in milliseconds
  28721. /** If you need to check double click without raising a single click at first click, enable this flag */
  28722. Scene.ExclusiveDoubleClickMode = false;
  28723. return Scene;
  28724. }(BABYLON.AbstractScene));
  28725. BABYLON.Scene = Scene;
  28726. })(BABYLON || (BABYLON = {}));
  28727. //# sourceMappingURL=babylon.scene.js.map
  28728. var BABYLON;
  28729. (function (BABYLON) {
  28730. /**
  28731. * Set of assets to keep when moving a scene into an asset container.
  28732. */
  28733. var KeepAssets = /** @class */ (function (_super) {
  28734. __extends(KeepAssets, _super);
  28735. function KeepAssets() {
  28736. return _super !== null && _super.apply(this, arguments) || this;
  28737. }
  28738. return KeepAssets;
  28739. }(BABYLON.AbstractScene));
  28740. BABYLON.KeepAssets = KeepAssets;
  28741. /**
  28742. * Container with a set of assets that can be added or removed from a scene.
  28743. */
  28744. var AssetContainer = /** @class */ (function (_super) {
  28745. __extends(AssetContainer, _super);
  28746. /**
  28747. * Instantiates an AssetContainer.
  28748. * @param scene The scene the AssetContainer belongs to.
  28749. */
  28750. function AssetContainer(scene) {
  28751. var _this = _super.call(this) || this;
  28752. _this.scene = scene;
  28753. return _this;
  28754. }
  28755. /**
  28756. * Adds all the assets from the container to the scene.
  28757. */
  28758. AssetContainer.prototype.addAllToScene = function () {
  28759. var _this = this;
  28760. this.cameras.forEach(function (o) {
  28761. _this.scene.addCamera(o);
  28762. });
  28763. this.lights.forEach(function (o) {
  28764. _this.scene.addLight(o);
  28765. });
  28766. this.meshes.forEach(function (o) {
  28767. _this.scene.addMesh(o);
  28768. });
  28769. this.skeletons.forEach(function (o) {
  28770. _this.scene.addSkeleton(o);
  28771. });
  28772. this.animations.forEach(function (o) {
  28773. _this.scene.addAnimation(o);
  28774. });
  28775. this.animationGroups.forEach(function (o) {
  28776. _this.scene.addAnimationGroup(o);
  28777. });
  28778. this.multiMaterials.forEach(function (o) {
  28779. _this.scene.addMultiMaterial(o);
  28780. });
  28781. this.materials.forEach(function (o) {
  28782. _this.scene.addMaterial(o);
  28783. });
  28784. this.morphTargetManagers.forEach(function (o) {
  28785. _this.scene.addMorphTargetManager(o);
  28786. });
  28787. this.geometries.forEach(function (o) {
  28788. _this.scene.addGeometry(o);
  28789. });
  28790. this.transformNodes.forEach(function (o) {
  28791. _this.scene.addTransformNode(o);
  28792. });
  28793. this.actionManagers.forEach(function (o) {
  28794. _this.scene.addActionManager(o);
  28795. });
  28796. this.textures.forEach(function (o) {
  28797. _this.scene.addTexture(o);
  28798. });
  28799. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28800. var component = _a[_i];
  28801. component.addFromContainer(this.scene);
  28802. }
  28803. };
  28804. /**
  28805. * Removes all the assets in the container from the scene
  28806. */
  28807. AssetContainer.prototype.removeAllFromScene = function () {
  28808. var _this = this;
  28809. this.cameras.forEach(function (o) {
  28810. _this.scene.removeCamera(o);
  28811. });
  28812. this.lights.forEach(function (o) {
  28813. _this.scene.removeLight(o);
  28814. });
  28815. this.meshes.forEach(function (o) {
  28816. _this.scene.removeMesh(o);
  28817. });
  28818. this.skeletons.forEach(function (o) {
  28819. _this.scene.removeSkeleton(o);
  28820. });
  28821. this.animations.forEach(function (o) {
  28822. _this.scene.removeAnimation(o);
  28823. });
  28824. this.animationGroups.forEach(function (o) {
  28825. _this.scene.removeAnimationGroup(o);
  28826. });
  28827. this.multiMaterials.forEach(function (o) {
  28828. _this.scene.removeMultiMaterial(o);
  28829. });
  28830. this.materials.forEach(function (o) {
  28831. _this.scene.removeMaterial(o);
  28832. });
  28833. this.morphTargetManagers.forEach(function (o) {
  28834. _this.scene.removeMorphTargetManager(o);
  28835. });
  28836. this.geometries.forEach(function (o) {
  28837. _this.scene.removeGeometry(o);
  28838. });
  28839. this.transformNodes.forEach(function (o) {
  28840. _this.scene.removeTransformNode(o);
  28841. });
  28842. this.actionManagers.forEach(function (o) {
  28843. _this.scene.removeActionManager(o);
  28844. });
  28845. this.textures.forEach(function (o) {
  28846. _this.scene.removeTexture(o);
  28847. });
  28848. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28849. var component = _a[_i];
  28850. component.removeFromContainer(this.scene);
  28851. }
  28852. };
  28853. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28854. if (!sourceAssets) {
  28855. return;
  28856. }
  28857. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28858. var asset = sourceAssets_1[_i];
  28859. var move = true;
  28860. if (keepAssets) {
  28861. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28862. var keepAsset = keepAssets_1[_a];
  28863. if (asset === keepAsset) {
  28864. move = false;
  28865. break;
  28866. }
  28867. }
  28868. }
  28869. if (move) {
  28870. targetAssets.push(asset);
  28871. }
  28872. }
  28873. };
  28874. /**
  28875. * Removes all the assets contained in the scene and adds them to the container.
  28876. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28877. */
  28878. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28879. if (keepAssets === undefined) {
  28880. keepAssets = new KeepAssets();
  28881. }
  28882. for (var key in this) {
  28883. if (this.hasOwnProperty(key)) {
  28884. this[key] = this[key] || [];
  28885. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28886. }
  28887. }
  28888. this.removeAllFromScene();
  28889. };
  28890. /**
  28891. * 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.
  28892. * @returns the root mesh
  28893. */
  28894. AssetContainer.prototype.createRootMesh = function () {
  28895. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28896. this.meshes.forEach(function (m) {
  28897. if (!m.parent) {
  28898. rootMesh.addChild(m);
  28899. }
  28900. });
  28901. this.meshes.unshift(rootMesh);
  28902. return rootMesh;
  28903. };
  28904. return AssetContainer;
  28905. }(BABYLON.AbstractScene));
  28906. BABYLON.AssetContainer = AssetContainer;
  28907. })(BABYLON || (BABYLON = {}));
  28908. //# sourceMappingURL=babylon.assetContainer.js.map
  28909. var BABYLON;
  28910. (function (BABYLON) {
  28911. var Buffer = /** @class */ (function () {
  28912. /**
  28913. * Constructor
  28914. * @param engine the engine
  28915. * @param data the data to use for this buffer
  28916. * @param updatable whether the data is updatable
  28917. * @param stride the stride (optional)
  28918. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28919. * @param instanced whether the buffer is instanced (optional)
  28920. * @param useBytes set to true if the stride in in bytes (optional)
  28921. */
  28922. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28923. if (stride === void 0) { stride = 0; }
  28924. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28925. if (instanced === void 0) { instanced = false; }
  28926. if (useBytes === void 0) { useBytes = false; }
  28927. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28928. this._engine = engine.getScene().getEngine();
  28929. }
  28930. else {
  28931. this._engine = engine;
  28932. }
  28933. this._updatable = updatable;
  28934. this._instanced = instanced;
  28935. this._data = data;
  28936. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28937. if (!postponeInternalCreation) { // by default
  28938. this.create();
  28939. }
  28940. }
  28941. /**
  28942. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28943. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28944. * @param offset defines offset in the buffer (0 by default)
  28945. * @param size defines the size in floats of attributes (position is 3 for instance)
  28946. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28947. * @param instanced defines if the vertex buffer contains indexed data
  28948. * @param useBytes defines if the offset and stride are in bytes
  28949. * @returns the new vertex buffer
  28950. */
  28951. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28952. if (useBytes === void 0) { useBytes = false; }
  28953. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28954. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28955. // a lot of these parameters are ignored as they are overriden by the buffer
  28956. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28957. };
  28958. // Properties
  28959. Buffer.prototype.isUpdatable = function () {
  28960. return this._updatable;
  28961. };
  28962. Buffer.prototype.getData = function () {
  28963. return this._data;
  28964. };
  28965. Buffer.prototype.getBuffer = function () {
  28966. return this._buffer;
  28967. };
  28968. /**
  28969. * Gets the stride in float32 units (i.e. byte stride / 4).
  28970. * May not be an integer if the byte stride is not divisible by 4.
  28971. * DEPRECATED. Use byteStride instead.
  28972. * @returns the stride in float32 units
  28973. */
  28974. Buffer.prototype.getStrideSize = function () {
  28975. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28976. };
  28977. // Methods
  28978. Buffer.prototype.create = function (data) {
  28979. if (data === void 0) { data = null; }
  28980. if (!data && this._buffer) {
  28981. return; // nothing to do
  28982. }
  28983. data = data || this._data;
  28984. if (!data) {
  28985. return;
  28986. }
  28987. if (!this._buffer) { // create buffer
  28988. if (this._updatable) {
  28989. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28990. this._data = data;
  28991. }
  28992. else {
  28993. this._buffer = this._engine.createVertexBuffer(data);
  28994. }
  28995. }
  28996. else if (this._updatable) { // update buffer
  28997. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28998. this._data = data;
  28999. }
  29000. };
  29001. /** @hidden */
  29002. Buffer.prototype._rebuild = function () {
  29003. this._buffer = null;
  29004. this.create(this._data);
  29005. };
  29006. Buffer.prototype.update = function (data) {
  29007. this.create(data);
  29008. };
  29009. /**
  29010. * Updates the data directly.
  29011. * @param data the new data
  29012. * @param offset the new offset
  29013. * @param vertexCount the vertex count (optional)
  29014. * @param useBytes set to true if the offset is in bytes
  29015. */
  29016. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29017. if (useBytes === void 0) { useBytes = false; }
  29018. if (!this._buffer) {
  29019. return;
  29020. }
  29021. if (this._updatable) { // update buffer
  29022. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29023. this._data = null;
  29024. }
  29025. };
  29026. Buffer.prototype.dispose = function () {
  29027. if (!this._buffer) {
  29028. return;
  29029. }
  29030. if (this._engine._releaseBuffer(this._buffer)) {
  29031. this._buffer = null;
  29032. }
  29033. };
  29034. return Buffer;
  29035. }());
  29036. BABYLON.Buffer = Buffer;
  29037. })(BABYLON || (BABYLON = {}));
  29038. //# sourceMappingURL=babylon.buffer.js.map
  29039. var BABYLON;
  29040. (function (BABYLON) {
  29041. var VertexBuffer = /** @class */ (function () {
  29042. /**
  29043. * Constructor
  29044. * @param engine the engine
  29045. * @param data the data to use for this vertex buffer
  29046. * @param kind the vertex buffer kind
  29047. * @param updatable whether the data is updatable
  29048. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29049. * @param stride the stride (optional)
  29050. * @param instanced whether the buffer is instanced (optional)
  29051. * @param offset the offset of the data (optional)
  29052. * @param size the number of components (optional)
  29053. * @param type the type of the component (optional)
  29054. * @param normalized whether the data contains normalized data (optional)
  29055. * @param useBytes set to true if stride and offset are in bytes (optional)
  29056. */
  29057. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29058. if (normalized === void 0) { normalized = false; }
  29059. if (useBytes === void 0) { useBytes = false; }
  29060. if (data instanceof BABYLON.Buffer) {
  29061. this._buffer = data;
  29062. this._ownsBuffer = false;
  29063. }
  29064. else {
  29065. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29066. this._ownsBuffer = true;
  29067. }
  29068. this._kind = kind;
  29069. if (type == undefined) {
  29070. var data_1 = this.getData();
  29071. this.type = VertexBuffer.FLOAT;
  29072. if (data_1 instanceof Int8Array)
  29073. this.type = VertexBuffer.BYTE;
  29074. else if (data_1 instanceof Uint8Array)
  29075. this.type = VertexBuffer.UNSIGNED_BYTE;
  29076. else if (data_1 instanceof Int16Array)
  29077. this.type = VertexBuffer.SHORT;
  29078. else if (data_1 instanceof Uint16Array)
  29079. this.type = VertexBuffer.UNSIGNED_SHORT;
  29080. else if (data_1 instanceof Int32Array)
  29081. this.type = VertexBuffer.INT;
  29082. else if (data_1 instanceof Uint32Array)
  29083. this.type = VertexBuffer.UNSIGNED_INT;
  29084. }
  29085. else {
  29086. this.type = type;
  29087. }
  29088. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29089. if (useBytes) {
  29090. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29091. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29092. this.byteOffset = offset || 0;
  29093. }
  29094. else {
  29095. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29096. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29097. this.byteOffset = (offset || 0) * typeByteLength;
  29098. }
  29099. this.normalized = normalized;
  29100. this._instanced = instanced !== undefined ? instanced : false;
  29101. this._instanceDivisor = instanced ? 1 : 0;
  29102. }
  29103. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29104. /**
  29105. * Gets or sets the instance divisor when in instanced mode
  29106. */
  29107. get: function () {
  29108. return this._instanceDivisor;
  29109. },
  29110. set: function (value) {
  29111. this._instanceDivisor = value;
  29112. if (value == 0) {
  29113. this._instanced = false;
  29114. }
  29115. else {
  29116. this._instanced = true;
  29117. }
  29118. },
  29119. enumerable: true,
  29120. configurable: true
  29121. });
  29122. /** @hidden */
  29123. VertexBuffer.prototype._rebuild = function () {
  29124. if (!this._buffer) {
  29125. return;
  29126. }
  29127. this._buffer._rebuild();
  29128. };
  29129. /**
  29130. * Returns the kind of the VertexBuffer (string).
  29131. */
  29132. VertexBuffer.prototype.getKind = function () {
  29133. return this._kind;
  29134. };
  29135. // Properties
  29136. /**
  29137. * Boolean : is the VertexBuffer updatable ?
  29138. */
  29139. VertexBuffer.prototype.isUpdatable = function () {
  29140. return this._buffer.isUpdatable();
  29141. };
  29142. /**
  29143. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29144. */
  29145. VertexBuffer.prototype.getData = function () {
  29146. return this._buffer.getData();
  29147. };
  29148. /**
  29149. * Returns the WebGLBuffer associated to the VertexBuffer.
  29150. */
  29151. VertexBuffer.prototype.getBuffer = function () {
  29152. return this._buffer.getBuffer();
  29153. };
  29154. /**
  29155. * Returns the stride as a multiple of the type byte length.
  29156. * DEPRECATED. Use byteStride instead.
  29157. */
  29158. VertexBuffer.prototype.getStrideSize = function () {
  29159. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29160. };
  29161. /**
  29162. * Returns the offset as a multiple of the type byte length.
  29163. * DEPRECATED. Use byteOffset instead.
  29164. */
  29165. VertexBuffer.prototype.getOffset = function () {
  29166. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29167. };
  29168. /**
  29169. * Returns the number of components per vertex attribute (integer).
  29170. */
  29171. VertexBuffer.prototype.getSize = function () {
  29172. return this._size;
  29173. };
  29174. /**
  29175. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29176. */
  29177. VertexBuffer.prototype.getIsInstanced = function () {
  29178. return this._instanced;
  29179. };
  29180. /**
  29181. * Returns the instancing divisor, zero for non-instanced (integer).
  29182. */
  29183. VertexBuffer.prototype.getInstanceDivisor = function () {
  29184. return this._instanceDivisor;
  29185. };
  29186. // Methods
  29187. /**
  29188. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29189. * Returns the created WebGLBuffer.
  29190. */
  29191. VertexBuffer.prototype.create = function (data) {
  29192. return this._buffer.create(data);
  29193. };
  29194. /**
  29195. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29196. * This function will create a new buffer if the current one is not updatable
  29197. * Returns the updated WebGLBuffer.
  29198. */
  29199. VertexBuffer.prototype.update = function (data) {
  29200. return this._buffer.update(data);
  29201. };
  29202. /**
  29203. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29204. * Returns the directly updated WebGLBuffer.
  29205. * @param data the new data
  29206. * @param offset the new offset
  29207. * @param useBytes set to true if the offset is in bytes
  29208. */
  29209. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29210. if (useBytes === void 0) { useBytes = false; }
  29211. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29212. };
  29213. /**
  29214. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29215. */
  29216. VertexBuffer.prototype.dispose = function () {
  29217. if (this._ownsBuffer) {
  29218. this._buffer.dispose();
  29219. }
  29220. };
  29221. /**
  29222. * Enumerates each value of this vertex buffer as numbers.
  29223. * @param count the number of values to enumerate
  29224. * @param callback the callback function called for each value
  29225. */
  29226. VertexBuffer.prototype.forEach = function (count, callback) {
  29227. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29228. };
  29229. Object.defineProperty(VertexBuffer, "PositionKind", {
  29230. get: function () {
  29231. return VertexBuffer._PositionKind;
  29232. },
  29233. enumerable: true,
  29234. configurable: true
  29235. });
  29236. Object.defineProperty(VertexBuffer, "NormalKind", {
  29237. get: function () {
  29238. return VertexBuffer._NormalKind;
  29239. },
  29240. enumerable: true,
  29241. configurable: true
  29242. });
  29243. Object.defineProperty(VertexBuffer, "TangentKind", {
  29244. get: function () {
  29245. return VertexBuffer._TangentKind;
  29246. },
  29247. enumerable: true,
  29248. configurable: true
  29249. });
  29250. Object.defineProperty(VertexBuffer, "UVKind", {
  29251. get: function () {
  29252. return VertexBuffer._UVKind;
  29253. },
  29254. enumerable: true,
  29255. configurable: true
  29256. });
  29257. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29258. get: function () {
  29259. return VertexBuffer._UV2Kind;
  29260. },
  29261. enumerable: true,
  29262. configurable: true
  29263. });
  29264. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29265. get: function () {
  29266. return VertexBuffer._UV3Kind;
  29267. },
  29268. enumerable: true,
  29269. configurable: true
  29270. });
  29271. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29272. get: function () {
  29273. return VertexBuffer._UV4Kind;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29279. get: function () {
  29280. return VertexBuffer._UV5Kind;
  29281. },
  29282. enumerable: true,
  29283. configurable: true
  29284. });
  29285. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29286. get: function () {
  29287. return VertexBuffer._UV6Kind;
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. Object.defineProperty(VertexBuffer, "ColorKind", {
  29293. get: function () {
  29294. return VertexBuffer._ColorKind;
  29295. },
  29296. enumerable: true,
  29297. configurable: true
  29298. });
  29299. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29300. get: function () {
  29301. return VertexBuffer._MatricesIndicesKind;
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29307. get: function () {
  29308. return VertexBuffer._MatricesWeightsKind;
  29309. },
  29310. enumerable: true,
  29311. configurable: true
  29312. });
  29313. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29314. get: function () {
  29315. return VertexBuffer._MatricesIndicesExtraKind;
  29316. },
  29317. enumerable: true,
  29318. configurable: true
  29319. });
  29320. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29321. get: function () {
  29322. return VertexBuffer._MatricesWeightsExtraKind;
  29323. },
  29324. enumerable: true,
  29325. configurable: true
  29326. });
  29327. /**
  29328. * Deduces the stride given a kind.
  29329. * @param kind The kind string to deduce
  29330. * @returns The deduced stride
  29331. */
  29332. VertexBuffer.DeduceStride = function (kind) {
  29333. switch (kind) {
  29334. case VertexBuffer.UVKind:
  29335. case VertexBuffer.UV2Kind:
  29336. case VertexBuffer.UV3Kind:
  29337. case VertexBuffer.UV4Kind:
  29338. case VertexBuffer.UV5Kind:
  29339. case VertexBuffer.UV6Kind:
  29340. return 2;
  29341. case VertexBuffer.NormalKind:
  29342. case VertexBuffer.PositionKind:
  29343. return 3;
  29344. case VertexBuffer.ColorKind:
  29345. case VertexBuffer.MatricesIndicesKind:
  29346. case VertexBuffer.MatricesIndicesExtraKind:
  29347. case VertexBuffer.MatricesWeightsKind:
  29348. case VertexBuffer.MatricesWeightsExtraKind:
  29349. case VertexBuffer.TangentKind:
  29350. return 4;
  29351. default:
  29352. throw new Error("Invalid kind '" + kind + "'");
  29353. }
  29354. };
  29355. /**
  29356. * Gets the byte length of the given type.
  29357. * @param type the type
  29358. * @returns the number of bytes
  29359. */
  29360. VertexBuffer.GetTypeByteLength = function (type) {
  29361. switch (type) {
  29362. case VertexBuffer.BYTE:
  29363. case VertexBuffer.UNSIGNED_BYTE:
  29364. return 1;
  29365. case VertexBuffer.SHORT:
  29366. case VertexBuffer.UNSIGNED_SHORT:
  29367. return 2;
  29368. case VertexBuffer.INT:
  29369. case VertexBuffer.FLOAT:
  29370. return 4;
  29371. default:
  29372. throw new Error("Invalid type '" + type + "'");
  29373. }
  29374. };
  29375. /**
  29376. * Enumerates each value of the given parameters as numbers.
  29377. * @param data the data to enumerate
  29378. * @param byteOffset the byte offset of the data
  29379. * @param byteStride the byte stride of the data
  29380. * @param componentCount the number of components per element
  29381. * @param componentType the type of the component
  29382. * @param count the total number of components
  29383. * @param normalized whether the data is normalized
  29384. * @param callback the callback function called for each value
  29385. */
  29386. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29387. if (data instanceof Array) {
  29388. var offset = byteOffset / 4;
  29389. var stride = byteStride / 4;
  29390. for (var index = 0; index < count; index += componentCount) {
  29391. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29392. callback(data[offset + componentIndex], index + componentIndex);
  29393. }
  29394. offset += stride;
  29395. }
  29396. }
  29397. else {
  29398. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29399. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29400. for (var index = 0; index < count; index += componentCount) {
  29401. var componentByteOffset = byteOffset;
  29402. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29403. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29404. callback(value, index + componentIndex);
  29405. componentByteOffset += componentByteLength;
  29406. }
  29407. byteOffset += byteStride;
  29408. }
  29409. }
  29410. };
  29411. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29412. switch (type) {
  29413. case VertexBuffer.BYTE: {
  29414. var value = dataView.getInt8(byteOffset);
  29415. if (normalized) {
  29416. value = Math.max(value / 127, -1);
  29417. }
  29418. return value;
  29419. }
  29420. case VertexBuffer.UNSIGNED_BYTE: {
  29421. var value = dataView.getUint8(byteOffset);
  29422. if (normalized) {
  29423. value = value / 255;
  29424. }
  29425. return value;
  29426. }
  29427. case VertexBuffer.SHORT: {
  29428. var value = dataView.getInt16(byteOffset, true);
  29429. if (normalized) {
  29430. value = Math.max(value / 16383, -1);
  29431. }
  29432. return value;
  29433. }
  29434. case VertexBuffer.UNSIGNED_SHORT: {
  29435. var value = dataView.getUint16(byteOffset, true);
  29436. if (normalized) {
  29437. value = value / 65535;
  29438. }
  29439. return value;
  29440. }
  29441. case VertexBuffer.FLOAT: {
  29442. return dataView.getFloat32(byteOffset, true);
  29443. }
  29444. default: {
  29445. throw new Error("Invalid component type " + type);
  29446. }
  29447. }
  29448. };
  29449. /**
  29450. * The byte type.
  29451. */
  29452. VertexBuffer.BYTE = 5120;
  29453. /**
  29454. * The unsigned byte type.
  29455. */
  29456. VertexBuffer.UNSIGNED_BYTE = 5121;
  29457. /**
  29458. * The short type.
  29459. */
  29460. VertexBuffer.SHORT = 5122;
  29461. /**
  29462. * The unsigned short type.
  29463. */
  29464. VertexBuffer.UNSIGNED_SHORT = 5123;
  29465. /**
  29466. * The integer type.
  29467. */
  29468. VertexBuffer.INT = 5124;
  29469. /**
  29470. * The unsigned integer type.
  29471. */
  29472. VertexBuffer.UNSIGNED_INT = 5125;
  29473. /**
  29474. * The float type.
  29475. */
  29476. VertexBuffer.FLOAT = 5126;
  29477. // Enums
  29478. VertexBuffer._PositionKind = "position";
  29479. VertexBuffer._NormalKind = "normal";
  29480. VertexBuffer._TangentKind = "tangent";
  29481. VertexBuffer._UVKind = "uv";
  29482. VertexBuffer._UV2Kind = "uv2";
  29483. VertexBuffer._UV3Kind = "uv3";
  29484. VertexBuffer._UV4Kind = "uv4";
  29485. VertexBuffer._UV5Kind = "uv5";
  29486. VertexBuffer._UV6Kind = "uv6";
  29487. VertexBuffer._ColorKind = "color";
  29488. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29489. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29490. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29491. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29492. return VertexBuffer;
  29493. }());
  29494. BABYLON.VertexBuffer = VertexBuffer;
  29495. })(BABYLON || (BABYLON = {}));
  29496. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29497. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29498. var BABYLON;
  29499. (function (BABYLON) {
  29500. /**
  29501. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29502. */
  29503. var DummyInternalTextureTracker = /** @class */ (function () {
  29504. function DummyInternalTextureTracker() {
  29505. /**
  29506. * Gets or set the previous tracker in the list
  29507. */
  29508. this.previous = null;
  29509. /**
  29510. * Gets or set the next tracker in the list
  29511. */
  29512. this.next = null;
  29513. }
  29514. return DummyInternalTextureTracker;
  29515. }());
  29516. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29517. })(BABYLON || (BABYLON = {}));
  29518. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29519. var BABYLON;
  29520. (function (BABYLON) {
  29521. /**
  29522. * Class used to store data associated with WebGL texture data for the engine
  29523. * This class should not be used directly
  29524. */
  29525. var InternalTexture = /** @class */ (function () {
  29526. /**
  29527. * Creates a new InternalTexture
  29528. * @param engine defines the engine to use
  29529. * @param dataSource defines the type of data that will be used
  29530. */
  29531. function InternalTexture(engine, dataSource) {
  29532. /**
  29533. * Observable called when the texture is loaded
  29534. */
  29535. this.onLoadedObservable = new BABYLON.Observable();
  29536. /**
  29537. * Gets or set the previous tracker in the list
  29538. */
  29539. this.previous = null;
  29540. /**
  29541. * Gets or set the next tracker in the list
  29542. */
  29543. this.next = null;
  29544. // Private
  29545. /** @hidden */
  29546. this._initialSlot = -1;
  29547. /** @hidden */
  29548. this._designatedSlot = -1;
  29549. /** @hidden */
  29550. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29551. /** @hidden */
  29552. this._comparisonFunction = 0;
  29553. /** @hidden */
  29554. this._sphericalPolynomial = null;
  29555. /** @hidden */
  29556. this._lodGenerationScale = 0;
  29557. /** @hidden */
  29558. this._lodGenerationOffset = 0;
  29559. /** @hidden */
  29560. this._isRGBD = false;
  29561. /** @hidden */
  29562. this._references = 1;
  29563. this._engine = engine;
  29564. this._dataSource = dataSource;
  29565. this._webGLTexture = engine._createTexture();
  29566. }
  29567. /**
  29568. * Gets the Engine the texture belongs to.
  29569. * @returns The babylon engine
  29570. */
  29571. InternalTexture.prototype.getEngine = function () {
  29572. return this._engine;
  29573. };
  29574. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29575. /**
  29576. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29577. */
  29578. get: function () {
  29579. return this._dataSource;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. /**
  29585. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29586. */
  29587. InternalTexture.prototype.incrementReferences = function () {
  29588. this._references++;
  29589. };
  29590. /**
  29591. * Change the size of the texture (not the size of the content)
  29592. * @param width defines the new width
  29593. * @param height defines the new height
  29594. * @param depth defines the new depth (1 by default)
  29595. */
  29596. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29597. if (depth === void 0) { depth = 1; }
  29598. this.width = width;
  29599. this.height = height;
  29600. this.depth = depth;
  29601. this.baseWidth = width;
  29602. this.baseHeight = height;
  29603. this.baseDepth = depth;
  29604. this._size = width * height * depth;
  29605. };
  29606. /** @hidden */
  29607. InternalTexture.prototype._rebuild = function () {
  29608. var _this = this;
  29609. var proxy;
  29610. this.isReady = false;
  29611. this._cachedCoordinatesMode = null;
  29612. this._cachedWrapU = null;
  29613. this._cachedWrapV = null;
  29614. this._cachedAnisotropicFilteringLevel = null;
  29615. switch (this._dataSource) {
  29616. case InternalTexture.DATASOURCE_TEMP:
  29617. return;
  29618. case InternalTexture.DATASOURCE_URL:
  29619. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29620. _this.isReady = true;
  29621. }, null, this._buffer, undefined, this.format);
  29622. proxy._swapAndDie(this);
  29623. return;
  29624. case InternalTexture.DATASOURCE_RAW:
  29625. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29626. proxy._swapAndDie(this);
  29627. this.isReady = true;
  29628. return;
  29629. case InternalTexture.DATASOURCE_RAW3D:
  29630. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29631. proxy._swapAndDie(this);
  29632. this.isReady = true;
  29633. return;
  29634. case InternalTexture.DATASOURCE_DYNAMIC:
  29635. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29636. proxy._swapAndDie(this);
  29637. // The engine will make sure to update content so no need to flag it as isReady = true
  29638. return;
  29639. case InternalTexture.DATASOURCE_RENDERTARGET:
  29640. var options = new BABYLON.RenderTargetCreationOptions();
  29641. options.generateDepthBuffer = this._generateDepthBuffer;
  29642. options.generateMipMaps = this.generateMipMaps;
  29643. options.generateStencilBuffer = this._generateStencilBuffer;
  29644. options.samplingMode = this.samplingMode;
  29645. options.type = this.type;
  29646. if (this.isCube) {
  29647. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29648. }
  29649. else {
  29650. var size = {
  29651. width: this.width,
  29652. height: this.height
  29653. };
  29654. proxy = this._engine.createRenderTargetTexture(size, options);
  29655. }
  29656. proxy._swapAndDie(this);
  29657. this.isReady = true;
  29658. return;
  29659. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29660. var depthTextureOptions = {
  29661. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29662. comparisonFunction: this._comparisonFunction,
  29663. generateStencil: this._generateStencilBuffer,
  29664. isCube: this.isCube
  29665. };
  29666. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29667. proxy._swapAndDie(this);
  29668. this.isReady = true;
  29669. return;
  29670. case InternalTexture.DATASOURCE_CUBE:
  29671. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29672. _this.isReady = true;
  29673. }, null, this.format, this._extension);
  29674. proxy._swapAndDie(this);
  29675. return;
  29676. case InternalTexture.DATASOURCE_CUBERAW:
  29677. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29678. proxy._swapAndDie(this);
  29679. this.isReady = true;
  29680. return;
  29681. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29682. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29683. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29684. _this.isReady = true;
  29685. });
  29686. proxy._swapAndDie(this);
  29687. return;
  29688. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29689. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29690. if (proxy) {
  29691. proxy._swapAndDie(_this);
  29692. }
  29693. _this.isReady = true;
  29694. }, null, this.format, this._extension);
  29695. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29696. return;
  29697. }
  29698. };
  29699. /** @hidden */
  29700. InternalTexture.prototype._swapAndDie = function (target) {
  29701. target._webGLTexture = this._webGLTexture;
  29702. if (this._framebuffer) {
  29703. target._framebuffer = this._framebuffer;
  29704. }
  29705. if (this._depthStencilBuffer) {
  29706. target._depthStencilBuffer = this._depthStencilBuffer;
  29707. }
  29708. if (this._lodTextureHigh) {
  29709. if (target._lodTextureHigh) {
  29710. target._lodTextureHigh.dispose();
  29711. }
  29712. target._lodTextureHigh = this._lodTextureHigh;
  29713. }
  29714. if (this._lodTextureMid) {
  29715. if (target._lodTextureMid) {
  29716. target._lodTextureMid.dispose();
  29717. }
  29718. target._lodTextureMid = this._lodTextureMid;
  29719. }
  29720. if (this._lodTextureLow) {
  29721. if (target._lodTextureLow) {
  29722. target._lodTextureLow.dispose();
  29723. }
  29724. target._lodTextureLow = this._lodTextureLow;
  29725. }
  29726. var cache = this._engine.getLoadedTexturesCache();
  29727. var index = cache.indexOf(this);
  29728. if (index !== -1) {
  29729. cache.splice(index, 1);
  29730. }
  29731. };
  29732. /**
  29733. * Dispose the current allocated resources
  29734. */
  29735. InternalTexture.prototype.dispose = function () {
  29736. if (!this._webGLTexture) {
  29737. return;
  29738. }
  29739. this._references--;
  29740. if (this._references === 0) {
  29741. this._engine._releaseTexture(this);
  29742. this._webGLTexture = null;
  29743. this.previous = null;
  29744. this.next = null;
  29745. }
  29746. };
  29747. /**
  29748. * The source of the texture data is unknown
  29749. */
  29750. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29751. /**
  29752. * Texture data comes from an URL
  29753. */
  29754. InternalTexture.DATASOURCE_URL = 1;
  29755. /**
  29756. * Texture data is only used for temporary storage
  29757. */
  29758. InternalTexture.DATASOURCE_TEMP = 2;
  29759. /**
  29760. * Texture data comes from raw data (ArrayBuffer)
  29761. */
  29762. InternalTexture.DATASOURCE_RAW = 3;
  29763. /**
  29764. * Texture content is dynamic (video or dynamic texture)
  29765. */
  29766. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29767. /**
  29768. * Texture content is generated by rendering to it
  29769. */
  29770. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29771. /**
  29772. * Texture content is part of a multi render target process
  29773. */
  29774. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29775. /**
  29776. * Texture data comes from a cube data file
  29777. */
  29778. InternalTexture.DATASOURCE_CUBE = 7;
  29779. /**
  29780. * Texture data comes from a raw cube data
  29781. */
  29782. InternalTexture.DATASOURCE_CUBERAW = 8;
  29783. /**
  29784. * Texture data come from a prefiltered cube data file
  29785. */
  29786. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29787. /**
  29788. * Texture content is raw 3D data
  29789. */
  29790. InternalTexture.DATASOURCE_RAW3D = 10;
  29791. /**
  29792. * Texture content is a depth texture
  29793. */
  29794. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29795. /**
  29796. * Texture data comes from a raw cube data encoded with RGBD
  29797. */
  29798. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29799. return InternalTexture;
  29800. }());
  29801. BABYLON.InternalTexture = InternalTexture;
  29802. })(BABYLON || (BABYLON = {}));
  29803. //# sourceMappingURL=babylon.internalTexture.js.map
  29804. var BABYLON;
  29805. (function (BABYLON) {
  29806. var BaseTexture = /** @class */ (function () {
  29807. function BaseTexture(scene) {
  29808. this._hasAlpha = false;
  29809. this.getAlphaFromRGB = false;
  29810. this.level = 1;
  29811. this.coordinatesIndex = 0;
  29812. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29813. /**
  29814. * | Value | Type | Description |
  29815. * | ----- | ------------------ | ----------- |
  29816. * | 0 | CLAMP_ADDRESSMODE | |
  29817. * | 1 | WRAP_ADDRESSMODE | |
  29818. * | 2 | MIRROR_ADDRESSMODE | |
  29819. */
  29820. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29821. /**
  29822. * | Value | Type | Description |
  29823. * | ----- | ------------------ | ----------- |
  29824. * | 0 | CLAMP_ADDRESSMODE | |
  29825. * | 1 | WRAP_ADDRESSMODE | |
  29826. * | 2 | MIRROR_ADDRESSMODE | |
  29827. */
  29828. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29829. /**
  29830. * | Value | Type | Description |
  29831. * | ----- | ------------------ | ----------- |
  29832. * | 0 | CLAMP_ADDRESSMODE | |
  29833. * | 1 | WRAP_ADDRESSMODE | |
  29834. * | 2 | MIRROR_ADDRESSMODE | |
  29835. */
  29836. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29837. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29838. this.isCube = false;
  29839. this.is3D = false;
  29840. this.gammaSpace = true;
  29841. this.invertZ = false;
  29842. this.lodLevelInAlpha = false;
  29843. this.isRenderTarget = false;
  29844. this.animations = new Array();
  29845. /**
  29846. * An event triggered when the texture is disposed.
  29847. */
  29848. this.onDisposeObservable = new BABYLON.Observable();
  29849. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29850. this._cachedSize = BABYLON.Size.Zero();
  29851. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29852. if (this._scene) {
  29853. this._scene.textures.push(this);
  29854. }
  29855. this._uid = null;
  29856. }
  29857. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29858. get: function () {
  29859. return this._hasAlpha;
  29860. },
  29861. set: function (value) {
  29862. if (this._hasAlpha === value) {
  29863. return;
  29864. }
  29865. this._hasAlpha = value;
  29866. if (this._scene) {
  29867. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29868. }
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29874. get: function () {
  29875. return this._coordinatesMode;
  29876. },
  29877. /**
  29878. * How a texture is mapped.
  29879. *
  29880. * | Value | Type | Description |
  29881. * | ----- | ----------------------------------- | ----------- |
  29882. * | 0 | EXPLICIT_MODE | |
  29883. * | 1 | SPHERICAL_MODE | |
  29884. * | 2 | PLANAR_MODE | |
  29885. * | 3 | CUBIC_MODE | |
  29886. * | 4 | PROJECTION_MODE | |
  29887. * | 5 | SKYBOX_MODE | |
  29888. * | 6 | INVCUBIC_MODE | |
  29889. * | 7 | EQUIRECTANGULAR_MODE | |
  29890. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29891. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29892. */
  29893. set: function (value) {
  29894. if (this._coordinatesMode === value) {
  29895. return;
  29896. }
  29897. this._coordinatesMode = value;
  29898. if (this._scene) {
  29899. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29900. }
  29901. },
  29902. enumerable: true,
  29903. configurable: true
  29904. });
  29905. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29906. /**
  29907. * Gets whether or not the texture contains RGBD data.
  29908. */
  29909. get: function () {
  29910. return this._texture != null && this._texture._isRGBD;
  29911. },
  29912. enumerable: true,
  29913. configurable: true
  29914. });
  29915. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29916. get: function () {
  29917. if (this._texture)
  29918. return this._texture._lodGenerationOffset;
  29919. return 0.0;
  29920. },
  29921. set: function (value) {
  29922. if (this._texture)
  29923. this._texture._lodGenerationOffset = value;
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29929. get: function () {
  29930. if (this._texture)
  29931. return this._texture._lodGenerationScale;
  29932. return 0.0;
  29933. },
  29934. set: function (value) {
  29935. if (this._texture)
  29936. this._texture._lodGenerationScale = value;
  29937. },
  29938. enumerable: true,
  29939. configurable: true
  29940. });
  29941. Object.defineProperty(BaseTexture.prototype, "uid", {
  29942. get: function () {
  29943. if (!this._uid) {
  29944. this._uid = BABYLON.Tools.RandomId();
  29945. }
  29946. return this._uid;
  29947. },
  29948. enumerable: true,
  29949. configurable: true
  29950. });
  29951. BaseTexture.prototype.toString = function () {
  29952. return this.name;
  29953. };
  29954. BaseTexture.prototype.getClassName = function () {
  29955. return "BaseTexture";
  29956. };
  29957. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29958. set: function (callback) {
  29959. if (this._onDisposeObserver) {
  29960. this.onDisposeObservable.remove(this._onDisposeObserver);
  29961. }
  29962. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29963. },
  29964. enumerable: true,
  29965. configurable: true
  29966. });
  29967. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29968. get: function () {
  29969. return true;
  29970. },
  29971. enumerable: true,
  29972. configurable: true
  29973. });
  29974. BaseTexture.prototype.getScene = function () {
  29975. return this._scene;
  29976. };
  29977. BaseTexture.prototype.getTextureMatrix = function () {
  29978. return BABYLON.Matrix.IdentityReadOnly;
  29979. };
  29980. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29981. return BABYLON.Matrix.IdentityReadOnly;
  29982. };
  29983. BaseTexture.prototype.getInternalTexture = function () {
  29984. return this._texture;
  29985. };
  29986. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29987. return !this.isBlocking || this.isReady();
  29988. };
  29989. BaseTexture.prototype.isReady = function () {
  29990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29991. this.delayLoad();
  29992. return false;
  29993. }
  29994. if (this._texture) {
  29995. return this._texture.isReady;
  29996. }
  29997. return false;
  29998. };
  29999. BaseTexture.prototype.getSize = function () {
  30000. if (this._texture) {
  30001. if (this._texture.width) {
  30002. this._cachedSize.width = this._texture.width;
  30003. this._cachedSize.height = this._texture.height;
  30004. return this._cachedSize;
  30005. }
  30006. if (this._texture._size) {
  30007. this._cachedSize.width = this._texture._size;
  30008. this._cachedSize.height = this._texture._size;
  30009. return this._cachedSize;
  30010. }
  30011. }
  30012. return this._cachedSize;
  30013. };
  30014. BaseTexture.prototype.getBaseSize = function () {
  30015. if (!this.isReady() || !this._texture)
  30016. return BABYLON.Size.Zero();
  30017. if (this._texture._size) {
  30018. return new BABYLON.Size(this._texture._size, this._texture._size);
  30019. }
  30020. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30021. };
  30022. BaseTexture.prototype.scale = function (ratio) {
  30023. };
  30024. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30025. get: function () {
  30026. return false;
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. /** @hidden */
  30032. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30033. if (!this._scene) {
  30034. return null;
  30035. }
  30036. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30037. for (var index = 0; index < texturesCache.length; index++) {
  30038. var texturesCacheEntry = texturesCache[index];
  30039. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30040. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30041. texturesCacheEntry.incrementReferences();
  30042. return texturesCacheEntry;
  30043. }
  30044. }
  30045. }
  30046. return null;
  30047. };
  30048. /** @hidden */
  30049. BaseTexture.prototype._rebuild = function () {
  30050. };
  30051. BaseTexture.prototype.delayLoad = function () {
  30052. };
  30053. BaseTexture.prototype.clone = function () {
  30054. return null;
  30055. };
  30056. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30057. get: function () {
  30058. if (!this._texture) {
  30059. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30060. }
  30061. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30067. get: function () {
  30068. if (!this._texture) {
  30069. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30070. }
  30071. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. /**
  30077. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30078. * This will returns an RGBA array buffer containing either in values (0-255) or
  30079. * float values (0-1) depending of the underlying buffer type.
  30080. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30081. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30082. * @param buffer defines a user defined buffer to fill with data (can be null)
  30083. * @returns The Array buffer containing the pixels data.
  30084. */
  30085. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30086. if (faceIndex === void 0) { faceIndex = 0; }
  30087. if (level === void 0) { level = 0; }
  30088. if (buffer === void 0) { buffer = null; }
  30089. if (!this._texture) {
  30090. return null;
  30091. }
  30092. var size = this.getSize();
  30093. var width = size.width;
  30094. var height = size.height;
  30095. var scene = this.getScene();
  30096. if (!scene) {
  30097. return null;
  30098. }
  30099. var engine = scene.getEngine();
  30100. if (level != 0) {
  30101. width = width / Math.pow(2, level);
  30102. height = height / Math.pow(2, level);
  30103. width = Math.round(width);
  30104. height = Math.round(height);
  30105. }
  30106. if (this._texture.isCube) {
  30107. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30108. }
  30109. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30110. };
  30111. BaseTexture.prototype.releaseInternalTexture = function () {
  30112. if (this._texture) {
  30113. this._texture.dispose();
  30114. this._texture = null;
  30115. }
  30116. };
  30117. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30118. get: function () {
  30119. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30120. return null;
  30121. }
  30122. if (!this._texture._sphericalPolynomial) {
  30123. this._texture._sphericalPolynomial =
  30124. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30125. }
  30126. return this._texture._sphericalPolynomial;
  30127. },
  30128. set: function (value) {
  30129. if (this._texture) {
  30130. this._texture._sphericalPolynomial = value;
  30131. }
  30132. },
  30133. enumerable: true,
  30134. configurable: true
  30135. });
  30136. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30137. get: function () {
  30138. if (this._texture) {
  30139. return this._texture._lodTextureHigh;
  30140. }
  30141. return null;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30147. get: function () {
  30148. if (this._texture) {
  30149. return this._texture._lodTextureMid;
  30150. }
  30151. return null;
  30152. },
  30153. enumerable: true,
  30154. configurable: true
  30155. });
  30156. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30157. get: function () {
  30158. if (this._texture) {
  30159. return this._texture._lodTextureLow;
  30160. }
  30161. return null;
  30162. },
  30163. enumerable: true,
  30164. configurable: true
  30165. });
  30166. BaseTexture.prototype.dispose = function () {
  30167. if (!this._scene) {
  30168. return;
  30169. }
  30170. // Animations
  30171. this._scene.stopAnimation(this);
  30172. // Remove from scene
  30173. this._scene._removePendingData(this);
  30174. var index = this._scene.textures.indexOf(this);
  30175. if (index >= 0) {
  30176. this._scene.textures.splice(index, 1);
  30177. }
  30178. if (this._texture === undefined) {
  30179. return;
  30180. }
  30181. // Release
  30182. this.releaseInternalTexture();
  30183. // Callback
  30184. this.onDisposeObservable.notifyObservers(this);
  30185. this.onDisposeObservable.clear();
  30186. };
  30187. BaseTexture.prototype.serialize = function () {
  30188. if (!this.name) {
  30189. return null;
  30190. }
  30191. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30192. // Animations
  30193. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30194. return serializationObject;
  30195. };
  30196. BaseTexture.WhenAllReady = function (textures, callback) {
  30197. var numRemaining = textures.length;
  30198. if (numRemaining === 0) {
  30199. callback();
  30200. return;
  30201. }
  30202. var _loop_1 = function () {
  30203. texture = textures[i];
  30204. if (texture.isReady()) {
  30205. if (--numRemaining === 0) {
  30206. callback();
  30207. }
  30208. }
  30209. else {
  30210. onLoadObservable = texture.onLoadObservable;
  30211. var onLoadCallback_1 = function () {
  30212. onLoadObservable.removeCallback(onLoadCallback_1);
  30213. if (--numRemaining === 0) {
  30214. callback();
  30215. }
  30216. };
  30217. onLoadObservable.add(onLoadCallback_1);
  30218. }
  30219. };
  30220. var texture, onLoadObservable;
  30221. for (var i = 0; i < textures.length; i++) {
  30222. _loop_1();
  30223. }
  30224. };
  30225. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30226. __decorate([
  30227. BABYLON.serialize()
  30228. ], BaseTexture.prototype, "name", void 0);
  30229. __decorate([
  30230. BABYLON.serialize("hasAlpha")
  30231. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30232. __decorate([
  30233. BABYLON.serialize()
  30234. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30235. __decorate([
  30236. BABYLON.serialize()
  30237. ], BaseTexture.prototype, "level", void 0);
  30238. __decorate([
  30239. BABYLON.serialize()
  30240. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30241. __decorate([
  30242. BABYLON.serialize("coordinatesMode")
  30243. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30244. __decorate([
  30245. BABYLON.serialize()
  30246. ], BaseTexture.prototype, "wrapU", void 0);
  30247. __decorate([
  30248. BABYLON.serialize()
  30249. ], BaseTexture.prototype, "wrapV", void 0);
  30250. __decorate([
  30251. BABYLON.serialize()
  30252. ], BaseTexture.prototype, "wrapR", void 0);
  30253. __decorate([
  30254. BABYLON.serialize()
  30255. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30256. __decorate([
  30257. BABYLON.serialize()
  30258. ], BaseTexture.prototype, "isCube", void 0);
  30259. __decorate([
  30260. BABYLON.serialize()
  30261. ], BaseTexture.prototype, "is3D", void 0);
  30262. __decorate([
  30263. BABYLON.serialize()
  30264. ], BaseTexture.prototype, "gammaSpace", void 0);
  30265. __decorate([
  30266. BABYLON.serialize()
  30267. ], BaseTexture.prototype, "invertZ", void 0);
  30268. __decorate([
  30269. BABYLON.serialize()
  30270. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30271. __decorate([
  30272. BABYLON.serialize()
  30273. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30274. __decorate([
  30275. BABYLON.serialize()
  30276. ], BaseTexture.prototype, "lodGenerationScale", null);
  30277. __decorate([
  30278. BABYLON.serialize()
  30279. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30280. return BaseTexture;
  30281. }());
  30282. BABYLON.BaseTexture = BaseTexture;
  30283. })(BABYLON || (BABYLON = {}));
  30284. //# sourceMappingURL=babylon.baseTexture.js.map
  30285. var BABYLON;
  30286. (function (BABYLON) {
  30287. var Texture = /** @class */ (function (_super) {
  30288. __extends(Texture, _super);
  30289. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30290. if (noMipmap === void 0) { noMipmap = false; }
  30291. if (invertY === void 0) { invertY = true; }
  30292. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30293. if (onLoad === void 0) { onLoad = null; }
  30294. if (onError === void 0) { onError = null; }
  30295. if (buffer === void 0) { buffer = null; }
  30296. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30297. var _this = _super.call(this, scene) || this;
  30298. _this.uOffset = 0;
  30299. _this.vOffset = 0;
  30300. _this.uScale = 1.0;
  30301. _this.vScale = 1.0;
  30302. _this.uAng = 0;
  30303. _this.vAng = 0;
  30304. _this.wAng = 0;
  30305. /**
  30306. * Defines the center of rotation (U)
  30307. */
  30308. _this.uRotationCenter = 0.5;
  30309. /**
  30310. * Defines the center of rotation (V)
  30311. */
  30312. _this.vRotationCenter = 0.5;
  30313. /**
  30314. * Defines the center of rotation (W)
  30315. */
  30316. _this.wRotationCenter = 0.5;
  30317. _this._isBlocking = true;
  30318. _this.name = url || "";
  30319. _this.url = url;
  30320. _this._noMipmap = noMipmap;
  30321. _this._invertY = invertY;
  30322. _this._samplingMode = samplingMode;
  30323. _this._buffer = buffer;
  30324. _this._deleteBuffer = deleteBuffer;
  30325. if (format) {
  30326. _this._format = format;
  30327. }
  30328. scene = _this.getScene();
  30329. if (!scene) {
  30330. return _this;
  30331. }
  30332. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30333. var load = function () {
  30334. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30335. _this.onLoadObservable.notifyObservers(_this);
  30336. }
  30337. if (onLoad) {
  30338. onLoad();
  30339. }
  30340. if (!_this.isBlocking && scene) {
  30341. scene.resetCachedMaterial();
  30342. }
  30343. };
  30344. if (!_this.url) {
  30345. _this._delayedOnLoad = load;
  30346. _this._delayedOnError = onError;
  30347. return _this;
  30348. }
  30349. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30350. if (!_this._texture) {
  30351. if (!scene.useDelayedTextureLoading) {
  30352. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30353. if (deleteBuffer) {
  30354. delete _this._buffer;
  30355. }
  30356. }
  30357. else {
  30358. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30359. _this._delayedOnLoad = load;
  30360. _this._delayedOnError = onError;
  30361. }
  30362. }
  30363. else {
  30364. if (_this._texture.isReady) {
  30365. BABYLON.Tools.SetImmediate(function () { return load(); });
  30366. }
  30367. else {
  30368. _this._texture.onLoadedObservable.add(load);
  30369. }
  30370. }
  30371. return _this;
  30372. }
  30373. Object.defineProperty(Texture.prototype, "noMipmap", {
  30374. get: function () {
  30375. return this._noMipmap;
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(Texture.prototype, "isBlocking", {
  30381. get: function () {
  30382. return this._isBlocking;
  30383. },
  30384. set: function (value) {
  30385. this._isBlocking = value;
  30386. },
  30387. enumerable: true,
  30388. configurable: true
  30389. });
  30390. Object.defineProperty(Texture.prototype, "samplingMode", {
  30391. get: function () {
  30392. return this._samplingMode;
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. /**
  30398. * Update the url (and optional buffer) of this texture if url was null during construction.
  30399. * @param url the url of the texture
  30400. * @param buffer the buffer of the texture (defaults to null)
  30401. */
  30402. Texture.prototype.updateURL = function (url, buffer) {
  30403. if (buffer === void 0) { buffer = null; }
  30404. if (this.url) {
  30405. throw new Error("URL is already set");
  30406. }
  30407. this.url = url;
  30408. this._buffer = buffer;
  30409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30410. this.delayLoad();
  30411. };
  30412. Texture.prototype.delayLoad = function () {
  30413. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30414. return;
  30415. }
  30416. var scene = this.getScene();
  30417. if (!scene) {
  30418. return;
  30419. }
  30420. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30421. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30422. if (!this._texture) {
  30423. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30424. if (this._deleteBuffer) {
  30425. delete this._buffer;
  30426. }
  30427. }
  30428. else {
  30429. if (this._delayedOnLoad) {
  30430. if (this._texture.isReady) {
  30431. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30432. }
  30433. else {
  30434. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30435. }
  30436. }
  30437. }
  30438. this._delayedOnLoad = null;
  30439. this._delayedOnError = null;
  30440. };
  30441. /**
  30442. * Default is Trilinear mode.
  30443. *
  30444. * | Value | Type | Description |
  30445. * | ----- | ------------------ | ----------- |
  30446. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30447. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30448. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30449. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30450. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30451. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30452. * | 7 | NEAREST_LINEAR | |
  30453. * | 8 | NEAREST_NEAREST | |
  30454. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30455. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30456. * | 11 | LINEAR_LINEAR | |
  30457. * | 12 | LINEAR_NEAREST | |
  30458. *
  30459. * > _mag_: magnification filter (close to the viewer)
  30460. * > _min_: minification filter (far from the viewer)
  30461. * > _mip_: filter used between mip map levels
  30462. *
  30463. */
  30464. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30465. if (!this._texture) {
  30466. return;
  30467. }
  30468. var scene = this.getScene();
  30469. if (!scene) {
  30470. return;
  30471. }
  30472. this._samplingMode = samplingMode;
  30473. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30474. };
  30475. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30476. x *= this.uScale;
  30477. y *= this.vScale;
  30478. x -= this.uRotationCenter * this.uScale;
  30479. y -= this.vRotationCenter * this.vScale;
  30480. z -= this.wRotationCenter;
  30481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30482. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30483. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30484. t.z += this.wRotationCenter;
  30485. };
  30486. Texture.prototype.getTextureMatrix = function () {
  30487. var _this = this;
  30488. if (this.uOffset === this._cachedUOffset &&
  30489. this.vOffset === this._cachedVOffset &&
  30490. this.uScale === this._cachedUScale &&
  30491. this.vScale === this._cachedVScale &&
  30492. this.uAng === this._cachedUAng &&
  30493. this.vAng === this._cachedVAng &&
  30494. this.wAng === this._cachedWAng) {
  30495. return this._cachedTextureMatrix;
  30496. }
  30497. this._cachedUOffset = this.uOffset;
  30498. this._cachedVOffset = this.vOffset;
  30499. this._cachedUScale = this.uScale;
  30500. this._cachedVScale = this.vScale;
  30501. this._cachedUAng = this.uAng;
  30502. this._cachedVAng = this.vAng;
  30503. this._cachedWAng = this.wAng;
  30504. if (!this._cachedTextureMatrix) {
  30505. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30506. this._rowGenerationMatrix = new BABYLON.Matrix();
  30507. this._t0 = BABYLON.Vector3.Zero();
  30508. this._t1 = BABYLON.Vector3.Zero();
  30509. this._t2 = BABYLON.Vector3.Zero();
  30510. }
  30511. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30512. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30513. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30514. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30515. this._t1.subtractInPlace(this._t0);
  30516. this._t2.subtractInPlace(this._t0);
  30517. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30518. this._cachedTextureMatrix.m[0] = this._t1.x;
  30519. this._cachedTextureMatrix.m[1] = this._t1.y;
  30520. this._cachedTextureMatrix.m[2] = this._t1.z;
  30521. this._cachedTextureMatrix.m[4] = this._t2.x;
  30522. this._cachedTextureMatrix.m[5] = this._t2.y;
  30523. this._cachedTextureMatrix.m[6] = this._t2.z;
  30524. this._cachedTextureMatrix.m[8] = this._t0.x;
  30525. this._cachedTextureMatrix.m[9] = this._t0.y;
  30526. this._cachedTextureMatrix.m[10] = this._t0.z;
  30527. var scene = this.getScene();
  30528. if (!scene) {
  30529. return this._cachedTextureMatrix;
  30530. }
  30531. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30532. return mat.hasTexture(_this);
  30533. });
  30534. return this._cachedTextureMatrix;
  30535. };
  30536. Texture.prototype.getReflectionTextureMatrix = function () {
  30537. var _this = this;
  30538. var scene = this.getScene();
  30539. if (!scene) {
  30540. return this._cachedTextureMatrix;
  30541. }
  30542. if (this.uOffset === this._cachedUOffset &&
  30543. this.vOffset === this._cachedVOffset &&
  30544. this.uScale === this._cachedUScale &&
  30545. this.vScale === this._cachedVScale &&
  30546. this.coordinatesMode === this._cachedCoordinatesMode) {
  30547. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30548. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30549. return this._cachedTextureMatrix;
  30550. }
  30551. }
  30552. else {
  30553. return this._cachedTextureMatrix;
  30554. }
  30555. }
  30556. if (!this._cachedTextureMatrix) {
  30557. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30558. }
  30559. if (!this._projectionModeMatrix) {
  30560. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30561. }
  30562. this._cachedUOffset = this.uOffset;
  30563. this._cachedVOffset = this.vOffset;
  30564. this._cachedUScale = this.uScale;
  30565. this._cachedVScale = this.vScale;
  30566. this._cachedCoordinatesMode = this.coordinatesMode;
  30567. switch (this.coordinatesMode) {
  30568. case Texture.PLANAR_MODE:
  30569. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30570. this._cachedTextureMatrix[0] = this.uScale;
  30571. this._cachedTextureMatrix[5] = this.vScale;
  30572. this._cachedTextureMatrix[12] = this.uOffset;
  30573. this._cachedTextureMatrix[13] = this.vOffset;
  30574. break;
  30575. case Texture.PROJECTION_MODE:
  30576. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30577. this._projectionModeMatrix.m[0] = 0.5;
  30578. this._projectionModeMatrix.m[5] = -0.5;
  30579. this._projectionModeMatrix.m[10] = 0.0;
  30580. this._projectionModeMatrix.m[12] = 0.5;
  30581. this._projectionModeMatrix.m[13] = 0.5;
  30582. this._projectionModeMatrix.m[14] = 1.0;
  30583. this._projectionModeMatrix.m[15] = 1.0;
  30584. var projectionMatrix = scene.getProjectionMatrix();
  30585. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30586. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30587. break;
  30588. default:
  30589. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30590. break;
  30591. }
  30592. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30593. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30594. });
  30595. return this._cachedTextureMatrix;
  30596. };
  30597. Texture.prototype.clone = function () {
  30598. var _this = this;
  30599. return BABYLON.SerializationHelper.Clone(function () {
  30600. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30601. }, this);
  30602. };
  30603. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30604. get: function () {
  30605. if (!this._onLoadObservable) {
  30606. this._onLoadObservable = new BABYLON.Observable();
  30607. }
  30608. return this._onLoadObservable;
  30609. },
  30610. enumerable: true,
  30611. configurable: true
  30612. });
  30613. Texture.prototype.serialize = function () {
  30614. var serializationObject = _super.prototype.serialize.call(this);
  30615. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30616. serializationObject.base64String = this._buffer;
  30617. serializationObject.name = serializationObject.name.replace("data:", "");
  30618. }
  30619. serializationObject.invertY = this._invertY;
  30620. serializationObject.samplingMode = this.samplingMode;
  30621. return serializationObject;
  30622. };
  30623. Texture.prototype.getClassName = function () {
  30624. return "Texture";
  30625. };
  30626. Texture.prototype.dispose = function () {
  30627. _super.prototype.dispose.call(this);
  30628. if (this._onLoadObservable) {
  30629. this._onLoadObservable.clear();
  30630. this._onLoadObservable = null;
  30631. }
  30632. this._delayedOnLoad = null;
  30633. this._delayedOnError = null;
  30634. };
  30635. // Statics
  30636. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30637. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30638. if (onLoad === void 0) { onLoad = null; }
  30639. if (onError === void 0) { onError = null; }
  30640. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30641. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30642. };
  30643. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30644. if (parsedTexture.customType) {
  30645. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30646. // Update Sampling Mode
  30647. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30648. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30649. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30650. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30651. }
  30652. }
  30653. return parsedCustomTexture;
  30654. }
  30655. if (parsedTexture.isCube) {
  30656. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30657. }
  30658. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30659. return null;
  30660. }
  30661. var texture = BABYLON.SerializationHelper.Parse(function () {
  30662. var generateMipMaps = true;
  30663. if (parsedTexture.noMipmap) {
  30664. generateMipMaps = false;
  30665. }
  30666. if (parsedTexture.mirrorPlane) {
  30667. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30668. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30669. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30670. return mirrorTexture;
  30671. }
  30672. else if (parsedTexture.isRenderTarget) {
  30673. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30674. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30675. return renderTargetTexture;
  30676. }
  30677. else {
  30678. var texture;
  30679. if (parsedTexture.base64String) {
  30680. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30681. }
  30682. else {
  30683. var url = rootUrl + parsedTexture.name;
  30684. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30685. url = parsedTexture.url;
  30686. }
  30687. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30688. }
  30689. return texture;
  30690. }
  30691. }, parsedTexture, scene);
  30692. // Update Sampling Mode
  30693. if (parsedTexture.samplingMode) {
  30694. var sampling = parsedTexture.samplingMode;
  30695. if (texture._samplingMode !== sampling) {
  30696. texture.updateSamplingMode(sampling);
  30697. }
  30698. }
  30699. // Animations
  30700. if (parsedTexture.animations) {
  30701. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30702. var parsedAnimation = parsedTexture.animations[animationIndex];
  30703. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30704. }
  30705. }
  30706. return texture;
  30707. };
  30708. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30709. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30710. if (noMipmap === void 0) { noMipmap = false; }
  30711. if (invertY === void 0) { invertY = true; }
  30712. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30713. if (onLoad === void 0) { onLoad = null; }
  30714. if (onError === void 0) { onError = null; }
  30715. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30716. if (name.substr(0, 5) !== "data:") {
  30717. name = "data:" + name;
  30718. }
  30719. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30720. };
  30721. // Constants
  30722. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30723. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30724. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30725. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30726. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30727. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30728. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30729. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30730. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30731. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30732. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30733. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30734. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30735. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30736. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30737. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30738. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30739. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30740. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30741. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30742. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30743. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30744. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30745. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30746. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30747. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30748. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30749. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30750. /**
  30751. * 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
  30752. */
  30753. Texture.UseSerializedUrlIfAny = false;
  30754. __decorate([
  30755. BABYLON.serialize()
  30756. ], Texture.prototype, "url", void 0);
  30757. __decorate([
  30758. BABYLON.serialize()
  30759. ], Texture.prototype, "uOffset", void 0);
  30760. __decorate([
  30761. BABYLON.serialize()
  30762. ], Texture.prototype, "vOffset", void 0);
  30763. __decorate([
  30764. BABYLON.serialize()
  30765. ], Texture.prototype, "uScale", void 0);
  30766. __decorate([
  30767. BABYLON.serialize()
  30768. ], Texture.prototype, "vScale", void 0);
  30769. __decorate([
  30770. BABYLON.serialize()
  30771. ], Texture.prototype, "uAng", void 0);
  30772. __decorate([
  30773. BABYLON.serialize()
  30774. ], Texture.prototype, "vAng", void 0);
  30775. __decorate([
  30776. BABYLON.serialize()
  30777. ], Texture.prototype, "wAng", void 0);
  30778. __decorate([
  30779. BABYLON.serialize()
  30780. ], Texture.prototype, "uRotationCenter", void 0);
  30781. __decorate([
  30782. BABYLON.serialize()
  30783. ], Texture.prototype, "vRotationCenter", void 0);
  30784. __decorate([
  30785. BABYLON.serialize()
  30786. ], Texture.prototype, "wRotationCenter", void 0);
  30787. __decorate([
  30788. BABYLON.serialize()
  30789. ], Texture.prototype, "isBlocking", null);
  30790. return Texture;
  30791. }(BABYLON.BaseTexture));
  30792. BABYLON.Texture = Texture;
  30793. })(BABYLON || (BABYLON = {}));
  30794. //# sourceMappingURL=babylon.texture.js.map
  30795. var BABYLON;
  30796. (function (BABYLON) {
  30797. /**
  30798. * @hidden
  30799. **/
  30800. var _InstancesBatch = /** @class */ (function () {
  30801. function _InstancesBatch() {
  30802. this.mustReturn = false;
  30803. this.visibleInstances = new Array();
  30804. this.renderSelf = new Array();
  30805. }
  30806. return _InstancesBatch;
  30807. }());
  30808. BABYLON._InstancesBatch = _InstancesBatch;
  30809. /**
  30810. * Class used to represent renderable models
  30811. */
  30812. var Mesh = /** @class */ (function (_super) {
  30813. __extends(Mesh, _super);
  30814. /**
  30815. * @constructor
  30816. * @param name The value used by scene.getMeshByName() to do a lookup.
  30817. * @param scene The scene to add this mesh to.
  30818. * @param parent The parent of this mesh, if it has one
  30819. * @param source An optional Mesh from which geometry is shared, cloned.
  30820. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30821. * When false, achieved by calling a clone(), also passing False.
  30822. * This will make creation of children, recursive.
  30823. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30824. */
  30825. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30826. if (scene === void 0) { scene = null; }
  30827. if (parent === void 0) { parent = null; }
  30828. if (source === void 0) { source = null; }
  30829. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30830. var _this = _super.call(this, name, scene) || this;
  30831. // Members
  30832. /**
  30833. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30834. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30835. */
  30836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30837. /**
  30838. * Gets the list of instances created from this mesh
  30839. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30840. */
  30841. _this.instances = new Array();
  30842. _this._LODLevels = new Array();
  30843. /** @hidden */
  30844. _this._visibleInstances = {};
  30845. _this._renderIdForInstances = new Array();
  30846. _this._batchCache = new _InstancesBatch();
  30847. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30848. // Use by builder only to know what orientation were the mesh build in.
  30849. /** @hidden */
  30850. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30851. /**
  30852. * Use this property to change the original side orientation defined at construction time
  30853. */
  30854. _this.overrideMaterialSideOrientation = null;
  30855. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30856. // Will be used to save a source mesh reference, If any
  30857. _this._source = null;
  30858. scene = _this.getScene();
  30859. if (source) {
  30860. // Geometry
  30861. if (source._geometry) {
  30862. source._geometry.applyToMesh(_this);
  30863. }
  30864. // Deep copy
  30865. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30866. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30867. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30868. ], ["_poseMatrix"]);
  30869. // Source mesh
  30870. _this._source = source;
  30871. // Construction Params
  30872. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30873. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30874. var myAnyThis = _this;
  30875. var myAnySource = source;
  30876. myAnyThis._closePath = myAnySource._closePath;
  30877. myAnyThis._idx = myAnySource._idx;
  30878. myAnyThis.dashSize = myAnySource.dashSize;
  30879. myAnyThis.gapSize = myAnySource.gapSize;
  30880. myAnyThis.path3D = myAnySource.path3D;
  30881. myAnyThis.pathArray = myAnySource.pathArray;
  30882. myAnyThis.arc = myAnySource.arc;
  30883. myAnyThis.radius = myAnySource.radius;
  30884. // Animation ranges
  30885. if (_this._source._ranges) {
  30886. var ranges = _this._source._ranges;
  30887. for (var name in ranges) {
  30888. if (!ranges.hasOwnProperty(name)) {
  30889. continue;
  30890. }
  30891. if (!ranges[name]) {
  30892. continue;
  30893. }
  30894. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30895. }
  30896. }
  30897. // Metadata
  30898. if (source.metadata && source.metadata.clone) {
  30899. _this.metadata = source.metadata.clone();
  30900. }
  30901. else {
  30902. _this.metadata = source.metadata;
  30903. }
  30904. // Tags
  30905. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30906. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30907. }
  30908. // Parent
  30909. _this.parent = source.parent;
  30910. // Pivot
  30911. _this.setPivotMatrix(source.getPivotMatrix());
  30912. _this.id = name + "." + source.id;
  30913. // Material
  30914. _this.material = source.material;
  30915. var index;
  30916. if (!doNotCloneChildren) {
  30917. // Children
  30918. var directDescendants = source.getDescendants(true);
  30919. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30920. var child = directDescendants[index_1];
  30921. if (child.clone) {
  30922. child.clone(name + "." + child.name, _this);
  30923. }
  30924. }
  30925. }
  30926. // Physics clone
  30927. var physicsEngine = _this.getScene().getPhysicsEngine();
  30928. if (clonePhysicsImpostor && physicsEngine) {
  30929. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30930. if (impostor) {
  30931. _this.physicsImpostor = impostor.clone(_this);
  30932. }
  30933. }
  30934. // Particles
  30935. for (index = 0; index < scene.particleSystems.length; index++) {
  30936. var system = scene.particleSystems[index];
  30937. if (system.emitter === source) {
  30938. system.clone(system.name, _this);
  30939. }
  30940. }
  30941. _this.refreshBoundingInfo();
  30942. _this.computeWorldMatrix(true);
  30943. }
  30944. // Parent
  30945. if (parent !== null) {
  30946. _this.parent = parent;
  30947. }
  30948. return _this;
  30949. }
  30950. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30951. /**
  30952. * An event triggered before rendering the mesh
  30953. */
  30954. get: function () {
  30955. if (!this._onBeforeRenderObservable) {
  30956. this._onBeforeRenderObservable = new BABYLON.Observable();
  30957. }
  30958. return this._onBeforeRenderObservable;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30964. /**
  30965. * An event triggered after rendering the mesh
  30966. */
  30967. get: function () {
  30968. if (!this._onAfterRenderObservable) {
  30969. this._onAfterRenderObservable = new BABYLON.Observable();
  30970. }
  30971. return this._onAfterRenderObservable;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30977. /**
  30978. * An event triggered before drawing the mesh
  30979. */
  30980. get: function () {
  30981. if (!this._onBeforeDrawObservable) {
  30982. this._onBeforeDrawObservable = new BABYLON.Observable();
  30983. }
  30984. return this._onBeforeDrawObservable;
  30985. },
  30986. enumerable: true,
  30987. configurable: true
  30988. });
  30989. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30990. /**
  30991. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  30992. */
  30993. set: function (callback) {
  30994. if (this._onBeforeDrawObserver) {
  30995. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30996. }
  30997. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30998. },
  30999. enumerable: true,
  31000. configurable: true
  31001. });
  31002. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31003. /**
  31004. * Gets or sets the morph target manager
  31005. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31006. */
  31007. get: function () {
  31008. return this._morphTargetManager;
  31009. },
  31010. set: function (value) {
  31011. if (this._morphTargetManager === value) {
  31012. return;
  31013. }
  31014. this._morphTargetManager = value;
  31015. this._syncGeometryWithMorphTargetManager();
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Mesh.prototype, "source", {
  31021. /**
  31022. * Gets the source mesh (the one used to clone this one from)
  31023. */
  31024. get: function () {
  31025. return this._source;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31031. /**
  31032. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31033. */
  31034. get: function () {
  31035. return this._unIndexed;
  31036. },
  31037. set: function (value) {
  31038. if (this._unIndexed !== value) {
  31039. this._unIndexed = value;
  31040. this._markSubMeshesAsAttributesDirty();
  31041. }
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. // Methods
  31047. /**
  31048. * Gets the class name
  31049. * @returns the string "Mesh".
  31050. */
  31051. Mesh.prototype.getClassName = function () {
  31052. return "Mesh";
  31053. };
  31054. /**
  31055. * Returns a description of this mesh
  31056. * @param fullDetails define if full details about this mesh must be used
  31057. * @returns a descriptive string representing this mesh
  31058. */
  31059. Mesh.prototype.toString = function (fullDetails) {
  31060. var ret = _super.prototype.toString.call(this, fullDetails);
  31061. ret += ", n vertices: " + this.getTotalVertices();
  31062. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31063. if (this.animations) {
  31064. for (var i = 0; i < this.animations.length; i++) {
  31065. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31066. }
  31067. }
  31068. if (fullDetails) {
  31069. if (this._geometry) {
  31070. var ib = this.getIndices();
  31071. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31072. if (vb && ib) {
  31073. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31074. }
  31075. }
  31076. else {
  31077. ret += ", flat shading: UNKNOWN";
  31078. }
  31079. }
  31080. return ret;
  31081. };
  31082. /** @hidden */
  31083. Mesh.prototype._unBindEffect = function () {
  31084. _super.prototype._unBindEffect.call(this);
  31085. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31086. var instance = _a[_i];
  31087. instance._unBindEffect();
  31088. }
  31089. };
  31090. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31091. /**
  31092. * Gets a boolean indicating if this mesh has LOD
  31093. */
  31094. get: function () {
  31095. return this._LODLevels.length > 0;
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. /**
  31101. * Gets the list of MeshLODLevel associated with the current mesh
  31102. * @returns an array of MeshLODLevel
  31103. */
  31104. Mesh.prototype.getLODLevels = function () {
  31105. return this._LODLevels;
  31106. };
  31107. Mesh.prototype._sortLODLevels = function () {
  31108. this._LODLevels.sort(function (a, b) {
  31109. if (a.distance < b.distance) {
  31110. return 1;
  31111. }
  31112. if (a.distance > b.distance) {
  31113. return -1;
  31114. }
  31115. return 0;
  31116. });
  31117. };
  31118. /**
  31119. * Add a mesh as LOD level triggered at the given distance.
  31120. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31121. * @param distance The distance from the center of the object to show this level
  31122. * @param mesh The mesh to be added as LOD level (can be null)
  31123. * @return This mesh (for chaining)
  31124. */
  31125. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31126. if (mesh && mesh._masterMesh) {
  31127. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31128. return this;
  31129. }
  31130. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31131. this._LODLevels.push(level);
  31132. if (mesh) {
  31133. mesh._masterMesh = this;
  31134. }
  31135. this._sortLODLevels();
  31136. return this;
  31137. };
  31138. /**
  31139. * Returns the LOD level mesh at the passed distance or null if not found.
  31140. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31141. * @param distance The distance from the center of the object to show this level
  31142. * @returns a Mesh or `null`
  31143. */
  31144. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31145. for (var index = 0; index < this._LODLevels.length; index++) {
  31146. var level = this._LODLevels[index];
  31147. if (level.distance === distance) {
  31148. return level.mesh;
  31149. }
  31150. }
  31151. return null;
  31152. };
  31153. /**
  31154. * Remove a mesh from the LOD array
  31155. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31156. * @param mesh defines the mesh to be removed
  31157. * @return This mesh (for chaining)
  31158. */
  31159. Mesh.prototype.removeLODLevel = function (mesh) {
  31160. for (var index = 0; index < this._LODLevels.length; index++) {
  31161. if (this._LODLevels[index].mesh === mesh) {
  31162. this._LODLevels.splice(index, 1);
  31163. if (mesh) {
  31164. mesh._masterMesh = null;
  31165. }
  31166. }
  31167. }
  31168. this._sortLODLevels();
  31169. return this;
  31170. };
  31171. /**
  31172. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31173. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31174. * @param camera defines the camera to use to compute distance
  31175. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31176. * @return This mesh (for chaining)
  31177. */
  31178. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31179. if (!this._LODLevels || this._LODLevels.length === 0) {
  31180. return this;
  31181. }
  31182. var bSphere;
  31183. if (boundingSphere) {
  31184. bSphere = boundingSphere;
  31185. }
  31186. else {
  31187. var boundingInfo = this.getBoundingInfo();
  31188. bSphere = boundingInfo.boundingSphere;
  31189. }
  31190. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31191. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31192. if (this.onLODLevelSelection) {
  31193. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31194. }
  31195. return this;
  31196. }
  31197. for (var index = 0; index < this._LODLevels.length; index++) {
  31198. var level = this._LODLevels[index];
  31199. if (level.distance < distanceToCamera) {
  31200. if (level.mesh) {
  31201. level.mesh._preActivate();
  31202. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31203. }
  31204. if (this.onLODLevelSelection) {
  31205. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31206. }
  31207. return level.mesh;
  31208. }
  31209. }
  31210. if (this.onLODLevelSelection) {
  31211. this.onLODLevelSelection(distanceToCamera, this, this);
  31212. }
  31213. return this;
  31214. };
  31215. Object.defineProperty(Mesh.prototype, "geometry", {
  31216. /**
  31217. * Gets the mesh internal Geometry object
  31218. */
  31219. get: function () {
  31220. return this._geometry;
  31221. },
  31222. enumerable: true,
  31223. configurable: true
  31224. });
  31225. /**
  31226. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31227. * @returns the total number of vertices
  31228. */
  31229. Mesh.prototype.getTotalVertices = function () {
  31230. if (this._geometry === null || this._geometry === undefined) {
  31231. return 0;
  31232. }
  31233. return this._geometry.getTotalVertices();
  31234. };
  31235. /**
  31236. * Returns the content of an associated vertex buffer
  31237. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31238. * - BABYLON.VertexBuffer.PositionKind
  31239. * - BABYLON.VertexBuffer.UVKind
  31240. * - BABYLON.VertexBuffer.UV2Kind
  31241. * - BABYLON.VertexBuffer.UV3Kind
  31242. * - BABYLON.VertexBuffer.UV4Kind
  31243. * - BABYLON.VertexBuffer.UV5Kind
  31244. * - BABYLON.VertexBuffer.UV6Kind
  31245. * - BABYLON.VertexBuffer.ColorKind
  31246. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31247. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31248. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31249. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31250. * @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
  31251. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31252. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31253. */
  31254. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31255. if (!this._geometry) {
  31256. return null;
  31257. }
  31258. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31259. };
  31260. /**
  31261. * Returns the mesh VertexBuffer object from the requested `kind`
  31262. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31263. * - BABYLON.VertexBuffer.PositionKind
  31264. * - BABYLON.VertexBuffer.UVKind
  31265. * - BABYLON.VertexBuffer.UV2Kind
  31266. * - BABYLON.VertexBuffer.UV3Kind
  31267. * - BABYLON.VertexBuffer.UV4Kind
  31268. * - BABYLON.VertexBuffer.UV5Kind
  31269. * - BABYLON.VertexBuffer.UV6Kind
  31270. * - BABYLON.VertexBuffer.ColorKind
  31271. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31272. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31273. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31274. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31275. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31276. */
  31277. Mesh.prototype.getVertexBuffer = function (kind) {
  31278. if (!this._geometry) {
  31279. return null;
  31280. }
  31281. return this._geometry.getVertexBuffer(kind);
  31282. };
  31283. /**
  31284. * Tests if a specific vertex buffer is associated with this mesh
  31285. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31286. * - BABYLON.VertexBuffer.PositionKind
  31287. * - BABYLON.VertexBuffer.UVKind
  31288. * - BABYLON.VertexBuffer.UV2Kind
  31289. * - BABYLON.VertexBuffer.UV3Kind
  31290. * - BABYLON.VertexBuffer.UV4Kind
  31291. * - BABYLON.VertexBuffer.UV5Kind
  31292. * - BABYLON.VertexBuffer.UV6Kind
  31293. * - BABYLON.VertexBuffer.ColorKind
  31294. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31295. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31296. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31297. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31298. * @returns a boolean
  31299. */
  31300. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31301. if (!this._geometry) {
  31302. if (this._delayInfo) {
  31303. return this._delayInfo.indexOf(kind) !== -1;
  31304. }
  31305. return false;
  31306. }
  31307. return this._geometry.isVerticesDataPresent(kind);
  31308. };
  31309. /**
  31310. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31311. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31312. * - BABYLON.VertexBuffer.PositionKind
  31313. * - BABYLON.VertexBuffer.UVKind
  31314. * - BABYLON.VertexBuffer.UV2Kind
  31315. * - BABYLON.VertexBuffer.UV3Kind
  31316. * - BABYLON.VertexBuffer.UV4Kind
  31317. * - BABYLON.VertexBuffer.UV5Kind
  31318. * - BABYLON.VertexBuffer.UV6Kind
  31319. * - BABYLON.VertexBuffer.ColorKind
  31320. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31321. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31322. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31323. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31324. * @returns a boolean
  31325. */
  31326. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31327. if (!this._geometry) {
  31328. if (this._delayInfo) {
  31329. return this._delayInfo.indexOf(kind) !== -1;
  31330. }
  31331. return false;
  31332. }
  31333. return this._geometry.isVertexBufferUpdatable(kind);
  31334. };
  31335. /**
  31336. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31337. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31338. * - BABYLON.VertexBuffer.PositionKind
  31339. * - BABYLON.VertexBuffer.UVKind
  31340. * - BABYLON.VertexBuffer.UV2Kind
  31341. * - BABYLON.VertexBuffer.UV3Kind
  31342. * - BABYLON.VertexBuffer.UV4Kind
  31343. * - BABYLON.VertexBuffer.UV5Kind
  31344. * - BABYLON.VertexBuffer.UV6Kind
  31345. * - BABYLON.VertexBuffer.ColorKind
  31346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31350. * @returns an array of strings
  31351. */
  31352. Mesh.prototype.getVerticesDataKinds = function () {
  31353. if (!this._geometry) {
  31354. var result = new Array();
  31355. if (this._delayInfo) {
  31356. this._delayInfo.forEach(function (kind, index, array) {
  31357. result.push(kind);
  31358. });
  31359. }
  31360. return result;
  31361. }
  31362. return this._geometry.getVerticesDataKinds();
  31363. };
  31364. /**
  31365. * Returns a positive integer : the total number of indices in this mesh geometry.
  31366. * @returns the numner of indices or zero if the mesh has no geometry.
  31367. */
  31368. Mesh.prototype.getTotalIndices = function () {
  31369. if (!this._geometry) {
  31370. return 0;
  31371. }
  31372. return this._geometry.getTotalIndices();
  31373. };
  31374. /**
  31375. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31376. * @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.
  31377. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31378. * @returns the indices array or an empty array if the mesh has no geometry
  31379. */
  31380. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31381. if (!this._geometry) {
  31382. return [];
  31383. }
  31384. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31385. };
  31386. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31387. get: function () {
  31388. return this._masterMesh !== null && this._masterMesh !== undefined;
  31389. },
  31390. enumerable: true,
  31391. configurable: true
  31392. });
  31393. /**
  31394. * Determine if the current mesh is ready to be rendered
  31395. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31396. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31397. * @returns true if all associated assets are ready (material, textures, shaders)
  31398. */
  31399. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31400. if (completeCheck === void 0) { completeCheck = false; }
  31401. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31402. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31403. return false;
  31404. }
  31405. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31406. return false;
  31407. }
  31408. if (!this.subMeshes || this.subMeshes.length === 0) {
  31409. return true;
  31410. }
  31411. if (!completeCheck) {
  31412. return true;
  31413. }
  31414. var engine = this.getEngine();
  31415. var scene = this.getScene();
  31416. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31417. this.computeWorldMatrix();
  31418. var mat = this.material || scene.defaultMaterial;
  31419. if (mat) {
  31420. if (mat.storeEffectOnSubMeshes) {
  31421. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31422. var subMesh = _a[_i];
  31423. var effectiveMaterial = subMesh.getMaterial();
  31424. if (effectiveMaterial) {
  31425. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31426. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31427. return false;
  31428. }
  31429. }
  31430. else {
  31431. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31432. return false;
  31433. }
  31434. }
  31435. }
  31436. }
  31437. }
  31438. else {
  31439. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31440. return false;
  31441. }
  31442. }
  31443. }
  31444. // Shadows
  31445. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31446. var light = _c[_b];
  31447. var generator = light.getShadowGenerator();
  31448. if (generator) {
  31449. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31450. var subMesh = _e[_d];
  31451. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31452. return false;
  31453. }
  31454. }
  31455. }
  31456. }
  31457. // LOD
  31458. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31459. var lod = _g[_f];
  31460. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31461. return false;
  31462. }
  31463. }
  31464. return true;
  31465. };
  31466. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31467. /**
  31468. * 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.
  31469. */
  31470. get: function () {
  31471. return this._areNormalsFrozen;
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. /**
  31477. * 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.
  31478. * @returns the current mesh
  31479. */
  31480. Mesh.prototype.freezeNormals = function () {
  31481. this._areNormalsFrozen = true;
  31482. return this;
  31483. };
  31484. /**
  31485. * 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
  31486. * @returns the current mesh
  31487. */
  31488. Mesh.prototype.unfreezeNormals = function () {
  31489. this._areNormalsFrozen = false;
  31490. return this;
  31491. };
  31492. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31493. /**
  31494. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31495. */
  31496. set: function (count) {
  31497. this._overridenInstanceCount = count;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. // Methods
  31503. /** @hidden */
  31504. Mesh.prototype._preActivate = function () {
  31505. var sceneRenderId = this.getScene().getRenderId();
  31506. if (this._preActivateId === sceneRenderId) {
  31507. return this;
  31508. }
  31509. this._preActivateId = sceneRenderId;
  31510. this._visibleInstances = null;
  31511. return this;
  31512. };
  31513. /** @hidden */
  31514. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31515. if (this._visibleInstances) {
  31516. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31517. }
  31518. return this;
  31519. };
  31520. /** @hidden */
  31521. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31522. if (!this._visibleInstances) {
  31523. this._visibleInstances = {};
  31524. this._visibleInstances.defaultRenderId = renderId;
  31525. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31526. }
  31527. if (!this._visibleInstances[renderId]) {
  31528. this._visibleInstances[renderId] = new Array();
  31529. }
  31530. this._visibleInstances[renderId].push(instance);
  31531. return this;
  31532. };
  31533. /**
  31534. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31535. * This means the mesh underlying bounding box and sphere are recomputed.
  31536. * @returns the current mesh
  31537. */
  31538. Mesh.prototype.refreshBoundingInfo = function () {
  31539. return this._refreshBoundingInfo(false);
  31540. };
  31541. /** @hidden */
  31542. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31543. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31544. return this;
  31545. }
  31546. var data = this._getPositionData(applySkeleton);
  31547. if (data) {
  31548. var bias = this.geometry ? this.geometry.boundingBias : null;
  31549. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31550. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31551. }
  31552. if (this.subMeshes) {
  31553. for (var index = 0; index < this.subMeshes.length; index++) {
  31554. this.subMeshes[index].refreshBoundingInfo();
  31555. }
  31556. }
  31557. this._updateBoundingInfo();
  31558. return this;
  31559. };
  31560. Mesh.prototype._getPositionData = function (applySkeleton) {
  31561. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31562. if (data && applySkeleton && this.skeleton) {
  31563. data = BABYLON.Tools.Slice(data);
  31564. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31565. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31566. if (matricesWeightsData && matricesIndicesData) {
  31567. var needExtras = this.numBoneInfluencers > 4;
  31568. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31569. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31570. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31571. var tempVector = BABYLON.Tmp.Vector3[0];
  31572. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31573. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31574. var matWeightIdx = 0;
  31575. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31576. finalMatrix.reset();
  31577. var inf;
  31578. var weight;
  31579. for (inf = 0; inf < 4; inf++) {
  31580. weight = matricesWeightsData[matWeightIdx + inf];
  31581. if (weight > 0) {
  31582. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31583. finalMatrix.addToSelf(tempMatrix);
  31584. }
  31585. }
  31586. if (needExtras) {
  31587. for (inf = 0; inf < 4; inf++) {
  31588. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31589. if (weight > 0) {
  31590. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31591. finalMatrix.addToSelf(tempMatrix);
  31592. }
  31593. }
  31594. }
  31595. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31596. tempVector.toArray(data, index);
  31597. }
  31598. }
  31599. }
  31600. return data;
  31601. };
  31602. /** @hidden */
  31603. Mesh.prototype._createGlobalSubMesh = function (force) {
  31604. var totalVertices = this.getTotalVertices();
  31605. if (!totalVertices || !this.getIndices()) {
  31606. return null;
  31607. }
  31608. // Check if we need to recreate the submeshes
  31609. if (this.subMeshes && this.subMeshes.length > 0) {
  31610. var ib = this.getIndices();
  31611. if (!ib) {
  31612. return null;
  31613. }
  31614. var totalIndices = ib.length;
  31615. var needToRecreate = false;
  31616. if (force) {
  31617. needToRecreate = true;
  31618. }
  31619. else {
  31620. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31621. var submesh = _a[_i];
  31622. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31623. needToRecreate = true;
  31624. break;
  31625. }
  31626. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31627. needToRecreate = true;
  31628. break;
  31629. }
  31630. }
  31631. }
  31632. if (!needToRecreate) {
  31633. return this.subMeshes[0];
  31634. }
  31635. }
  31636. this.releaseSubMeshes();
  31637. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31638. };
  31639. /**
  31640. * This function will subdivide the mesh into multiple submeshes
  31641. * @param count defines the expected number of submeshes
  31642. */
  31643. Mesh.prototype.subdivide = function (count) {
  31644. if (count < 1) {
  31645. return;
  31646. }
  31647. var totalIndices = this.getTotalIndices();
  31648. var subdivisionSize = (totalIndices / count) | 0;
  31649. var offset = 0;
  31650. // Ensure that subdivisionSize is a multiple of 3
  31651. while (subdivisionSize % 3 !== 0) {
  31652. subdivisionSize++;
  31653. }
  31654. this.releaseSubMeshes();
  31655. for (var index = 0; index < count; index++) {
  31656. if (offset >= totalIndices) {
  31657. break;
  31658. }
  31659. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31660. offset += subdivisionSize;
  31661. }
  31662. this.synchronizeInstances();
  31663. };
  31664. /**
  31665. * Copy a FloatArray into a specific associated vertex buffer
  31666. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31667. * - BABYLON.VertexBuffer.PositionKind
  31668. * - BABYLON.VertexBuffer.UVKind
  31669. * - BABYLON.VertexBuffer.UV2Kind
  31670. * - BABYLON.VertexBuffer.UV3Kind
  31671. * - BABYLON.VertexBuffer.UV4Kind
  31672. * - BABYLON.VertexBuffer.UV5Kind
  31673. * - BABYLON.VertexBuffer.UV6Kind
  31674. * - BABYLON.VertexBuffer.ColorKind
  31675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31679. * @param data defines the data source
  31680. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31681. * @param stride defines the data stride size (can be null)
  31682. * @returns the current mesh
  31683. */
  31684. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31685. if (updatable === void 0) { updatable = false; }
  31686. if (!this._geometry) {
  31687. var vertexData = new BABYLON.VertexData();
  31688. vertexData.set(data, kind);
  31689. var scene = this.getScene();
  31690. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31691. }
  31692. else {
  31693. this._geometry.setVerticesData(kind, data, updatable, stride);
  31694. }
  31695. return this;
  31696. };
  31697. /**
  31698. * Flags an associated vertex buffer as updatable
  31699. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31700. * - BABYLON.VertexBuffer.PositionKind
  31701. * - BABYLON.VertexBuffer.UVKind
  31702. * - BABYLON.VertexBuffer.UV2Kind
  31703. * - BABYLON.VertexBuffer.UV3Kind
  31704. * - BABYLON.VertexBuffer.UV4Kind
  31705. * - BABYLON.VertexBuffer.UV5Kind
  31706. * - BABYLON.VertexBuffer.UV6Kind
  31707. * - BABYLON.VertexBuffer.ColorKind
  31708. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31709. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31710. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31711. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31712. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31713. */
  31714. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31715. if (updatable === void 0) { updatable = true; }
  31716. var vb = this.getVertexBuffer(kind);
  31717. if (!vb || vb.isUpdatable() === updatable) {
  31718. return;
  31719. }
  31720. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31721. };
  31722. /**
  31723. * Sets the mesh global Vertex Buffer
  31724. * @param buffer defines the buffer to use
  31725. * @returns the current mesh
  31726. */
  31727. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31728. if (!this._geometry) {
  31729. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31730. }
  31731. this._geometry.setVerticesBuffer(buffer);
  31732. return this;
  31733. };
  31734. /**
  31735. * Update a specific associated vertex buffer
  31736. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31737. * - BABYLON.VertexBuffer.PositionKind
  31738. * - BABYLON.VertexBuffer.UVKind
  31739. * - BABYLON.VertexBuffer.UV2Kind
  31740. * - BABYLON.VertexBuffer.UV3Kind
  31741. * - BABYLON.VertexBuffer.UV4Kind
  31742. * - BABYLON.VertexBuffer.UV5Kind
  31743. * - BABYLON.VertexBuffer.UV6Kind
  31744. * - BABYLON.VertexBuffer.ColorKind
  31745. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31746. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31747. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31748. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31749. * @param data defines the data source
  31750. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31751. * @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)
  31752. * @returns the current mesh
  31753. */
  31754. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31755. if (!this._geometry) {
  31756. return this;
  31757. }
  31758. if (!makeItUnique) {
  31759. this._geometry.updateVerticesData(kind, data, updateExtends);
  31760. }
  31761. else {
  31762. this.makeGeometryUnique();
  31763. this.updateVerticesData(kind, data, updateExtends, false);
  31764. }
  31765. return this;
  31766. };
  31767. /**
  31768. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31769. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31770. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31771. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31772. * @returns the current mesh
  31773. */
  31774. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31775. if (computeNormals === void 0) { computeNormals = true; }
  31776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31777. if (!positions) {
  31778. return this;
  31779. }
  31780. positionFunction(positions);
  31781. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31782. if (computeNormals) {
  31783. var indices = this.getIndices();
  31784. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31785. if (!normals) {
  31786. return this;
  31787. }
  31788. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31789. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31790. }
  31791. return this;
  31792. };
  31793. /**
  31794. * Creates a un-shared specific occurence of the geometry for the mesh.
  31795. * @returns the current mesh
  31796. */
  31797. Mesh.prototype.makeGeometryUnique = function () {
  31798. if (!this._geometry) {
  31799. return this;
  31800. }
  31801. var oldGeometry = this._geometry;
  31802. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31803. oldGeometry.releaseForMesh(this, true);
  31804. geometry.applyToMesh(this);
  31805. return this;
  31806. };
  31807. /**
  31808. * Set the index buffer of this mesh
  31809. * @param indices defines the source data
  31810. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31811. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31812. * @returns the current mesh
  31813. */
  31814. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31815. if (totalVertices === void 0) { totalVertices = null; }
  31816. if (updatable === void 0) { updatable = false; }
  31817. if (!this._geometry) {
  31818. var vertexData = new BABYLON.VertexData();
  31819. vertexData.indices = indices;
  31820. var scene = this.getScene();
  31821. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31822. }
  31823. else {
  31824. this._geometry.setIndices(indices, totalVertices, updatable);
  31825. }
  31826. return this;
  31827. };
  31828. /**
  31829. * Update the current index buffer
  31830. * @param indices defines the source data
  31831. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31832. * @returns the current mesh
  31833. */
  31834. Mesh.prototype.updateIndices = function (indices, offset) {
  31835. if (!this._geometry) {
  31836. return this;
  31837. }
  31838. this._geometry.updateIndices(indices, offset);
  31839. return this;
  31840. };
  31841. /**
  31842. * Invert the geometry to move from a right handed system to a left handed one.
  31843. * @returns the current mesh
  31844. */
  31845. Mesh.prototype.toLeftHanded = function () {
  31846. if (!this._geometry) {
  31847. return this;
  31848. }
  31849. this._geometry.toLeftHanded();
  31850. return this;
  31851. };
  31852. /** @hidden */
  31853. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31854. if (!this._geometry) {
  31855. return this;
  31856. }
  31857. var engine = this.getScene().getEngine();
  31858. // Wireframe
  31859. var indexToBind;
  31860. if (this._unIndexed) {
  31861. indexToBind = null;
  31862. }
  31863. else {
  31864. switch (fillMode) {
  31865. case BABYLON.Material.PointFillMode:
  31866. indexToBind = null;
  31867. break;
  31868. case BABYLON.Material.WireFrameFillMode:
  31869. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31870. break;
  31871. default:
  31872. case BABYLON.Material.TriangleFillMode:
  31873. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31874. break;
  31875. }
  31876. }
  31877. // VBOs
  31878. this._geometry._bind(effect, indexToBind);
  31879. return this;
  31880. };
  31881. /** @hidden */
  31882. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31883. if (alternate === void 0) { alternate = false; }
  31884. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31885. return this;
  31886. }
  31887. if (this._onBeforeDrawObservable) {
  31888. this._onBeforeDrawObservable.notifyObservers(this);
  31889. }
  31890. var scene = this.getScene();
  31891. var engine = scene.getEngine();
  31892. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31893. // or triangles as points
  31894. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31895. }
  31896. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31897. // Triangles as wireframe
  31898. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31899. }
  31900. else {
  31901. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31902. }
  31903. if (scene._isAlternateRenderingEnabled && !alternate) {
  31904. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31905. if (!effect || !scene.activeCamera) {
  31906. return this;
  31907. }
  31908. scene._switchToAlternateCameraConfiguration(true);
  31909. this._effectiveMaterial.bindView(effect);
  31910. this._effectiveMaterial.bindViewProjection(effect);
  31911. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31912. this._draw(subMesh, fillMode, instancesCount, true);
  31913. engine.setViewport(scene.activeCamera.viewport);
  31914. scene._switchToAlternateCameraConfiguration(false);
  31915. this._effectiveMaterial.bindView(effect);
  31916. this._effectiveMaterial.bindViewProjection(effect);
  31917. }
  31918. return this;
  31919. };
  31920. /**
  31921. * Registers for this mesh a javascript function called just before the rendering process
  31922. * @param func defines the function to call before rendering this mesh
  31923. * @returns the current mesh
  31924. */
  31925. Mesh.prototype.registerBeforeRender = function (func) {
  31926. this.onBeforeRenderObservable.add(func);
  31927. return this;
  31928. };
  31929. /**
  31930. * Disposes a previously registered javascript function called before the rendering
  31931. * @param func defines the function to remove
  31932. * @returns the current mesh
  31933. */
  31934. Mesh.prototype.unregisterBeforeRender = function (func) {
  31935. this.onBeforeRenderObservable.removeCallback(func);
  31936. return this;
  31937. };
  31938. /**
  31939. * Registers for this mesh a javascript function called just after the rendering is complete
  31940. * @param func defines the function to call after rendering this mesh
  31941. * @returns the current mesh
  31942. */
  31943. Mesh.prototype.registerAfterRender = function (func) {
  31944. this.onAfterRenderObservable.add(func);
  31945. return this;
  31946. };
  31947. /**
  31948. * Disposes a previously registered javascript function called after the rendering.
  31949. * @param func defines the function to remove
  31950. * @returns the current mesh
  31951. */
  31952. Mesh.prototype.unregisterAfterRender = function (func) {
  31953. this.onAfterRenderObservable.removeCallback(func);
  31954. return this;
  31955. };
  31956. /** @hidden */
  31957. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31958. var scene = this.getScene();
  31959. this._batchCache.mustReturn = false;
  31960. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31961. this._batchCache.visibleInstances[subMeshId] = null;
  31962. if (this._visibleInstances) {
  31963. var currentRenderId = scene.getRenderId();
  31964. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31965. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31966. var selfRenderId = this._renderId;
  31967. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31968. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31969. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31970. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31971. }
  31972. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31973. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31974. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31975. this._batchCache.mustReturn = true;
  31976. return this._batchCache;
  31977. }
  31978. if (currentRenderId !== selfRenderId) {
  31979. this._batchCache.renderSelf[subMeshId] = false;
  31980. }
  31981. }
  31982. this._renderIdForInstances[subMeshId] = currentRenderId;
  31983. }
  31984. return this._batchCache;
  31985. };
  31986. /** @hidden */
  31987. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31988. var visibleInstances = batch.visibleInstances[subMesh._id];
  31989. if (!visibleInstances) {
  31990. return this;
  31991. }
  31992. var matricesCount = visibleInstances.length + 1;
  31993. var bufferSize = matricesCount * 16 * 4;
  31994. var currentInstancesBufferSize = this._instancesBufferSize;
  31995. var instancesBuffer = this._instancesBuffer;
  31996. while (this._instancesBufferSize < bufferSize) {
  31997. this._instancesBufferSize *= 2;
  31998. }
  31999. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32000. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32001. }
  32002. var offset = 0;
  32003. var instancesCount = 0;
  32004. var world = this.getWorldMatrix();
  32005. if (batch.renderSelf[subMesh._id]) {
  32006. world.copyToArray(this._instancesData, offset);
  32007. offset += 16;
  32008. instancesCount++;
  32009. }
  32010. if (visibleInstances) {
  32011. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32012. var instance = visibleInstances[instanceIndex];
  32013. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32014. offset += 16;
  32015. instancesCount++;
  32016. }
  32017. }
  32018. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32019. if (instancesBuffer) {
  32020. instancesBuffer.dispose();
  32021. }
  32022. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32023. this._instancesBuffer = instancesBuffer;
  32024. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32025. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32026. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32027. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32028. }
  32029. else {
  32030. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32031. }
  32032. this._bind(subMesh, effect, fillMode);
  32033. this._draw(subMesh, fillMode, instancesCount);
  32034. engine.unbindInstanceAttributes();
  32035. return this;
  32036. };
  32037. /** @hidden */
  32038. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32039. var scene = this.getScene();
  32040. var engine = scene.getEngine();
  32041. if (hardwareInstancedRendering) {
  32042. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32043. }
  32044. else {
  32045. if (batch.renderSelf[subMesh._id]) {
  32046. // Draw
  32047. if (onBeforeDraw) {
  32048. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32049. }
  32050. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32051. }
  32052. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32053. if (visibleInstancesForSubMesh) {
  32054. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32055. var instance = visibleInstancesForSubMesh[instanceIndex];
  32056. // World
  32057. var world = instance.getWorldMatrix();
  32058. if (onBeforeDraw) {
  32059. onBeforeDraw(true, world, effectiveMaterial);
  32060. }
  32061. // Draw
  32062. this._draw(subMesh, fillMode);
  32063. }
  32064. }
  32065. }
  32066. return this;
  32067. };
  32068. /**
  32069. * 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
  32070. * @param subMesh defines the subMesh to render
  32071. * @param enableAlphaMode defines if alpha mode can be changed
  32072. * @returns the current mesh
  32073. */
  32074. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32075. this._checkOcclusionQuery();
  32076. if (this._isOccluded) {
  32077. return this;
  32078. }
  32079. var scene = this.getScene();
  32080. // Managing instances
  32081. var batch = this._getInstancesRenderList(subMesh._id);
  32082. if (batch.mustReturn) {
  32083. return this;
  32084. }
  32085. // Checking geometry state
  32086. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32087. return this;
  32088. }
  32089. if (this._onBeforeRenderObservable) {
  32090. this._onBeforeRenderObservable.notifyObservers(this);
  32091. }
  32092. var engine = scene.getEngine();
  32093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32094. // Material
  32095. var material = subMesh.getMaterial();
  32096. if (!material) {
  32097. return this;
  32098. }
  32099. this._effectiveMaterial = material;
  32100. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32101. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32102. return this;
  32103. }
  32104. }
  32105. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32106. return this;
  32107. }
  32108. // Alpha mode
  32109. if (enableAlphaMode) {
  32110. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32111. }
  32112. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32113. var step = _a[_i];
  32114. step.action(this, subMesh, batch);
  32115. }
  32116. var effect;
  32117. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32118. effect = subMesh.effect;
  32119. }
  32120. else {
  32121. effect = this._effectiveMaterial.getEffect();
  32122. }
  32123. if (!effect) {
  32124. return this;
  32125. }
  32126. var sideOrientation = this.overrideMaterialSideOrientation;
  32127. if (sideOrientation == null) {
  32128. sideOrientation = this._effectiveMaterial.sideOrientation;
  32129. if (this._getWorldMatrixDeterminant() < 0) {
  32130. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32131. }
  32132. }
  32133. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32134. if (this._effectiveMaterial.forceDepthWrite) {
  32135. engine.setDepthWrite(true);
  32136. }
  32137. // Bind
  32138. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32139. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32140. this._bind(subMesh, effect, fillMode);
  32141. }
  32142. var world = this.getWorldMatrix();
  32143. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32144. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32145. }
  32146. else {
  32147. this._effectiveMaterial.bind(world, this);
  32148. }
  32149. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32150. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32151. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32152. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32153. }
  32154. // Draw
  32155. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32156. // Unbind
  32157. this._effectiveMaterial.unbind();
  32158. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32159. var step = _c[_b];
  32160. step.action(this, subMesh, batch);
  32161. }
  32162. if (this._onAfterRenderObservable) {
  32163. this._onAfterRenderObservable.notifyObservers(this);
  32164. }
  32165. return this;
  32166. };
  32167. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32168. if (isInstance && effectiveMaterial) {
  32169. effectiveMaterial.bindOnlyWorldMatrix(world);
  32170. }
  32171. };
  32172. /**
  32173. * Normalize matrix weights so that all vertices have a total weight set to 1
  32174. */
  32175. Mesh.prototype.cleanMatrixWeights = function () {
  32176. var epsilon = 1e-3;
  32177. var noInfluenceBoneIndex = 0.0;
  32178. if (this.skeleton) {
  32179. noInfluenceBoneIndex = this.skeleton.bones.length;
  32180. }
  32181. else {
  32182. return;
  32183. }
  32184. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32185. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32186. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32187. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32188. var influencers = this.numBoneInfluencers;
  32189. var size = matricesWeights.length;
  32190. for (var i = 0; i < size; i += 4) {
  32191. var weight = 0.0;
  32192. var firstZeroWeight = -1;
  32193. for (var j = 0; j < 4; j++) {
  32194. var w = matricesWeights[i + j];
  32195. weight += w;
  32196. if (w < epsilon && firstZeroWeight < 0) {
  32197. firstZeroWeight = j;
  32198. }
  32199. }
  32200. if (matricesWeightsExtra) {
  32201. for (var j = 0; j < 4; j++) {
  32202. var w = matricesWeightsExtra[i + j];
  32203. weight += w;
  32204. if (w < epsilon && firstZeroWeight < 0) {
  32205. firstZeroWeight = j + 4;
  32206. }
  32207. }
  32208. }
  32209. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32210. firstZeroWeight = influencers - 1;
  32211. }
  32212. if (weight > epsilon) {
  32213. var mweight = 1.0 / weight;
  32214. for (var j = 0; j < 4; j++) {
  32215. matricesWeights[i + j] *= mweight;
  32216. }
  32217. if (matricesWeightsExtra) {
  32218. for (var j = 0; j < 4; j++) {
  32219. matricesWeightsExtra[i + j] *= mweight;
  32220. }
  32221. }
  32222. }
  32223. else {
  32224. if (firstZeroWeight >= 4) {
  32225. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32226. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32227. }
  32228. else {
  32229. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32230. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32231. }
  32232. }
  32233. }
  32234. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32235. if (matricesIndicesExtra) {
  32236. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32237. }
  32238. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32239. if (matricesWeightsExtra) {
  32240. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32241. }
  32242. };
  32243. /** @hidden */
  32244. Mesh.prototype._checkDelayState = function () {
  32245. var scene = this.getScene();
  32246. if (this._geometry) {
  32247. this._geometry.load(scene);
  32248. }
  32249. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32250. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32251. this._queueLoad(scene);
  32252. }
  32253. return this;
  32254. };
  32255. Mesh.prototype._queueLoad = function (scene) {
  32256. var _this = this;
  32257. scene._addPendingData(this);
  32258. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32259. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32260. if (data instanceof ArrayBuffer) {
  32261. _this._delayLoadingFunction(data, _this);
  32262. }
  32263. else {
  32264. _this._delayLoadingFunction(JSON.parse(data), _this);
  32265. }
  32266. _this.instances.forEach(function (instance) {
  32267. instance._syncSubMeshes();
  32268. });
  32269. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32270. scene._removePendingData(_this);
  32271. }, function () { }, scene.database, getBinaryData);
  32272. return this;
  32273. };
  32274. /**
  32275. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32276. * A mesh is in the frustum if its bounding box intersects the frustum
  32277. * @param frustumPlanes defines the frustum to test
  32278. * @returns true if the mesh is in the frustum planes
  32279. */
  32280. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32281. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32282. return false;
  32283. }
  32284. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32285. return false;
  32286. }
  32287. this._checkDelayState();
  32288. return true;
  32289. };
  32290. /**
  32291. * Sets the mesh material by the material or multiMaterial `id` property
  32292. * @param id is a string identifying the material or the multiMaterial
  32293. * @returns the current mesh
  32294. */
  32295. Mesh.prototype.setMaterialByID = function (id) {
  32296. var materials = this.getScene().materials;
  32297. var index;
  32298. for (index = materials.length - 1; index > -1; index--) {
  32299. if (materials[index].id === id) {
  32300. this.material = materials[index];
  32301. return this;
  32302. }
  32303. }
  32304. // Multi
  32305. var multiMaterials = this.getScene().multiMaterials;
  32306. for (index = multiMaterials.length - 1; index > -1; index--) {
  32307. if (multiMaterials[index].id === id) {
  32308. this.material = multiMaterials[index];
  32309. return this;
  32310. }
  32311. }
  32312. return this;
  32313. };
  32314. /**
  32315. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32316. * @returns an array of IAnimatable
  32317. */
  32318. Mesh.prototype.getAnimatables = function () {
  32319. var results = new Array();
  32320. if (this.material) {
  32321. results.push(this.material);
  32322. }
  32323. if (this.skeleton) {
  32324. results.push(this.skeleton);
  32325. }
  32326. return results;
  32327. };
  32328. /**
  32329. * Modifies the mesh geometry according to the passed transformation matrix.
  32330. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32331. * The mesh normals are modified using the same transformation.
  32332. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32333. * @param transform defines the transform matrix to use
  32334. * @see http://doc.babylonjs.com/resources/baking_transformations
  32335. * @returns the current mesh
  32336. */
  32337. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32338. // Position
  32339. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32340. return this;
  32341. }
  32342. var submeshes = this.subMeshes.splice(0);
  32343. this._resetPointsArrayCache();
  32344. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32345. var temp = new Array();
  32346. var index;
  32347. for (index = 0; index < data.length; index += 3) {
  32348. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32349. }
  32350. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32351. // Normals
  32352. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32353. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32354. temp = [];
  32355. for (index = 0; index < data.length; index += 3) {
  32356. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32357. }
  32358. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32359. }
  32360. // flip faces?
  32361. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32362. this.flipFaces();
  32363. }
  32364. // Restore submeshes
  32365. this.releaseSubMeshes();
  32366. this.subMeshes = submeshes;
  32367. return this;
  32368. };
  32369. /**
  32370. * Modifies the mesh geometry according to its own current World Matrix.
  32371. * The mesh World Matrix is then reset.
  32372. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32373. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32374. * @see http://doc.babylonjs.com/resources/baking_transformations
  32375. * @returns the current mesh
  32376. */
  32377. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32378. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32379. this.scaling.copyFromFloats(1, 1, 1);
  32380. this.position.copyFromFloats(0, 0, 0);
  32381. this.rotation.copyFromFloats(0, 0, 0);
  32382. //only if quaternion is already set
  32383. if (this.rotationQuaternion) {
  32384. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32385. }
  32386. this._worldMatrix = BABYLON.Matrix.Identity();
  32387. return this;
  32388. };
  32389. Object.defineProperty(Mesh.prototype, "_positions", {
  32390. // Cache
  32391. /** @hidden */
  32392. get: function () {
  32393. if (this._geometry) {
  32394. return this._geometry._positions;
  32395. }
  32396. return null;
  32397. },
  32398. enumerable: true,
  32399. configurable: true
  32400. });
  32401. /** @hidden */
  32402. Mesh.prototype._resetPointsArrayCache = function () {
  32403. if (this._geometry) {
  32404. this._geometry._resetPointsArrayCache();
  32405. }
  32406. return this;
  32407. };
  32408. /** @hidden */
  32409. Mesh.prototype._generatePointsArray = function () {
  32410. if (this._geometry) {
  32411. return this._geometry._generatePointsArray();
  32412. }
  32413. return false;
  32414. };
  32415. /**
  32416. * Returns a new Mesh object generated from the current mesh properties.
  32417. * This method must not get confused with createInstance()
  32418. * @param name is a string, the name given to the new mesh
  32419. * @param newParent can be any Node object (default `null`)
  32420. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32421. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32422. * @returns a new mesh
  32423. */
  32424. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32425. if (name === void 0) { name = ""; }
  32426. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32427. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32428. };
  32429. /**
  32430. * Releases resources associated with this mesh.
  32431. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32432. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32433. */
  32434. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32435. var _this = this;
  32436. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32437. this.morphTargetManager = null;
  32438. if (this._geometry) {
  32439. this._geometry.releaseForMesh(this, true);
  32440. }
  32441. if (this._onBeforeDrawObservable) {
  32442. this._onBeforeDrawObservable.clear();
  32443. }
  32444. if (this._onBeforeRenderObservable) {
  32445. this._onBeforeRenderObservable.clear();
  32446. }
  32447. if (this._onAfterRenderObservable) {
  32448. this._onAfterRenderObservable.clear();
  32449. }
  32450. // Sources
  32451. var meshes = this.getScene().meshes;
  32452. meshes.forEach(function (abstractMesh) {
  32453. var mesh = abstractMesh;
  32454. if (mesh._source && mesh._source === _this) {
  32455. mesh._source = null;
  32456. }
  32457. });
  32458. this._source = null;
  32459. // Instances
  32460. if (this._instancesBuffer) {
  32461. this._instancesBuffer.dispose();
  32462. this._instancesBuffer = null;
  32463. }
  32464. while (this.instances.length) {
  32465. this.instances[0].dispose();
  32466. }
  32467. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32468. };
  32469. /**
  32470. * Modifies the mesh geometry according to a displacement map.
  32471. * 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.
  32472. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32473. * @param url is a string, the URL from the image file is to be downloaded.
  32474. * @param minHeight is the lower limit of the displacement.
  32475. * @param maxHeight is the upper limit of the displacement.
  32476. * @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.
  32477. * @param uvOffset is an optional vector2 used to offset UV.
  32478. * @param uvScale is an optional vector2 used to scale UV.
  32479. * @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.
  32480. * @returns the Mesh.
  32481. */
  32482. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32483. var _this = this;
  32484. if (forceUpdate === void 0) { forceUpdate = false; }
  32485. var scene = this.getScene();
  32486. var onload = function (img) {
  32487. // Getting height map data
  32488. var canvas = document.createElement("canvas");
  32489. var context = canvas.getContext("2d");
  32490. var heightMapWidth = img.width;
  32491. var heightMapHeight = img.height;
  32492. canvas.width = heightMapWidth;
  32493. canvas.height = heightMapHeight;
  32494. context.drawImage(img, 0, 0);
  32495. // Create VertexData from map data
  32496. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32497. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32498. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32499. //execute success callback, if set
  32500. if (onSuccess) {
  32501. onSuccess(_this);
  32502. }
  32503. };
  32504. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32505. return this;
  32506. };
  32507. /**
  32508. * Modifies the mesh geometry according to a displacementMap buffer.
  32509. * 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.
  32510. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32511. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32512. * @param heightMapWidth is the width of the buffer image.
  32513. * @param heightMapHeight is the height of the buffer image.
  32514. * @param minHeight is the lower limit of the displacement.
  32515. * @param maxHeight is the upper limit of the displacement.
  32516. * @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.
  32517. * @param uvOffset is an optional vector2 used to offset UV.
  32518. * @param uvScale is an optional vector2 used to scale UV.
  32519. * @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.
  32520. * @returns the Mesh.
  32521. */
  32522. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32523. if (forceUpdate === void 0) { forceUpdate = false; }
  32524. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32525. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32526. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32527. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32528. return this;
  32529. }
  32530. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32531. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32532. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32533. var position = BABYLON.Vector3.Zero();
  32534. var normal = BABYLON.Vector3.Zero();
  32535. var uv = BABYLON.Vector2.Zero();
  32536. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32537. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32538. for (var index = 0; index < positions.length; index += 3) {
  32539. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32540. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32541. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32542. // Compute height
  32543. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32544. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32545. var pos = (u + v * heightMapWidth) * 4;
  32546. var r = buffer[pos] / 255.0;
  32547. var g = buffer[pos + 1] / 255.0;
  32548. var b = buffer[pos + 2] / 255.0;
  32549. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32550. normal.normalize();
  32551. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32552. position = position.add(normal);
  32553. position.toArray(positions, index);
  32554. }
  32555. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32556. if (forceUpdate) {
  32557. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32558. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32559. }
  32560. else {
  32561. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32562. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32563. }
  32564. return this;
  32565. };
  32566. /**
  32567. * Modify the mesh to get a flat shading rendering.
  32568. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32569. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32570. * @returns current mesh
  32571. */
  32572. Mesh.prototype.convertToFlatShadedMesh = function () {
  32573. var kinds = this.getVerticesDataKinds();
  32574. var vbs = {};
  32575. var data = {};
  32576. var newdata = {};
  32577. var updatableNormals = false;
  32578. var kindIndex;
  32579. var kind;
  32580. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32581. kind = kinds[kindIndex];
  32582. var vertexBuffer = this.getVertexBuffer(kind);
  32583. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32584. updatableNormals = vertexBuffer.isUpdatable();
  32585. kinds.splice(kindIndex, 1);
  32586. kindIndex--;
  32587. continue;
  32588. }
  32589. vbs[kind] = vertexBuffer;
  32590. data[kind] = vbs[kind].getData();
  32591. newdata[kind] = [];
  32592. }
  32593. // Save previous submeshes
  32594. var previousSubmeshes = this.subMeshes.slice(0);
  32595. var indices = this.getIndices();
  32596. var totalIndices = this.getTotalIndices();
  32597. // Generating unique vertices per face
  32598. var index;
  32599. for (index = 0; index < totalIndices; index++) {
  32600. var vertexIndex = indices[index];
  32601. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32602. kind = kinds[kindIndex];
  32603. var stride = vbs[kind].getStrideSize();
  32604. for (var offset = 0; offset < stride; offset++) {
  32605. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32606. }
  32607. }
  32608. }
  32609. // Updating faces & normal
  32610. var normals = [];
  32611. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32612. for (index = 0; index < totalIndices; index += 3) {
  32613. indices[index] = index;
  32614. indices[index + 1] = index + 1;
  32615. indices[index + 2] = index + 2;
  32616. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32617. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32618. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32619. var p1p2 = p1.subtract(p2);
  32620. var p3p2 = p3.subtract(p2);
  32621. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32622. // Store same normals for every vertex
  32623. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32624. normals.push(normal.x);
  32625. normals.push(normal.y);
  32626. normals.push(normal.z);
  32627. }
  32628. }
  32629. this.setIndices(indices);
  32630. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32631. // Updating vertex buffers
  32632. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32633. kind = kinds[kindIndex];
  32634. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32635. }
  32636. // Updating submeshes
  32637. this.releaseSubMeshes();
  32638. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32639. var previousOne = previousSubmeshes[submeshIndex];
  32640. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32641. }
  32642. this.synchronizeInstances();
  32643. return this;
  32644. };
  32645. /**
  32646. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32647. * In other words, more vertices, no more indices and a single bigger VBO.
  32648. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32649. * @returns current mesh
  32650. */
  32651. Mesh.prototype.convertToUnIndexedMesh = function () {
  32652. var kinds = this.getVerticesDataKinds();
  32653. var vbs = {};
  32654. var data = {};
  32655. var newdata = {};
  32656. var kindIndex;
  32657. var kind;
  32658. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32659. kind = kinds[kindIndex];
  32660. var vertexBuffer = this.getVertexBuffer(kind);
  32661. vbs[kind] = vertexBuffer;
  32662. data[kind] = vbs[kind].getData();
  32663. newdata[kind] = [];
  32664. }
  32665. // Save previous submeshes
  32666. var previousSubmeshes = this.subMeshes.slice(0);
  32667. var indices = this.getIndices();
  32668. var totalIndices = this.getTotalIndices();
  32669. // Generating unique vertices per face
  32670. var index;
  32671. for (index = 0; index < totalIndices; index++) {
  32672. var vertexIndex = indices[index];
  32673. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32674. kind = kinds[kindIndex];
  32675. var stride = vbs[kind].getStrideSize();
  32676. for (var offset = 0; offset < stride; offset++) {
  32677. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32678. }
  32679. }
  32680. }
  32681. // Updating indices
  32682. for (index = 0; index < totalIndices; index += 3) {
  32683. indices[index] = index;
  32684. indices[index + 1] = index + 1;
  32685. indices[index + 2] = index + 2;
  32686. }
  32687. this.setIndices(indices);
  32688. // Updating vertex buffers
  32689. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32690. kind = kinds[kindIndex];
  32691. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32692. }
  32693. // Updating submeshes
  32694. this.releaseSubMeshes();
  32695. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32696. var previousOne = previousSubmeshes[submeshIndex];
  32697. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32698. }
  32699. this._unIndexed = true;
  32700. this.synchronizeInstances();
  32701. return this;
  32702. };
  32703. /**
  32704. * Inverses facet orientations.
  32705. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32706. * @param flipNormals will also inverts the normals
  32707. * @returns current mesh
  32708. */
  32709. Mesh.prototype.flipFaces = function (flipNormals) {
  32710. if (flipNormals === void 0) { flipNormals = false; }
  32711. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32712. var i;
  32713. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32714. for (i = 0; i < vertex_data.normals.length; i++) {
  32715. vertex_data.normals[i] *= -1;
  32716. }
  32717. }
  32718. if (vertex_data.indices) {
  32719. var temp;
  32720. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32721. // reassign indices
  32722. temp = vertex_data.indices[i + 1];
  32723. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32724. vertex_data.indices[i + 2] = temp;
  32725. }
  32726. }
  32727. vertex_data.applyToMesh(this);
  32728. return this;
  32729. };
  32730. // Instances
  32731. /**
  32732. * Creates a new InstancedMesh object from the mesh model.
  32733. * Warning : this method is not supported for Line mesh and LineSystem
  32734. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32735. * @param name defines the name of the new instance
  32736. * @returns a new InstancedMesh
  32737. */
  32738. Mesh.prototype.createInstance = function (name) {
  32739. return new BABYLON.InstancedMesh(name, this);
  32740. };
  32741. /**
  32742. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32743. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32744. * @returns the current mesh
  32745. */
  32746. Mesh.prototype.synchronizeInstances = function () {
  32747. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32748. var instance = this.instances[instanceIndex];
  32749. instance._syncSubMeshes();
  32750. }
  32751. return this;
  32752. };
  32753. /**
  32754. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32755. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32756. * This should be used together with the simplification to avoid disappearing triangles.
  32757. * @param successCallback an optional success callback to be called after the optimization finished.
  32758. * @returns the current mesh
  32759. */
  32760. Mesh.prototype.optimizeIndices = function (successCallback) {
  32761. var _this = this;
  32762. var indices = this.getIndices();
  32763. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32764. if (!positions || !indices) {
  32765. return this;
  32766. }
  32767. var vectorPositions = new Array();
  32768. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32769. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32770. }
  32771. var dupes = new Array();
  32772. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32773. var realPos = vectorPositions.length - 1 - iteration;
  32774. var testedPosition = vectorPositions[realPos];
  32775. for (var j = 0; j < realPos; ++j) {
  32776. var againstPosition = vectorPositions[j];
  32777. if (testedPosition.equals(againstPosition)) {
  32778. dupes[realPos] = j;
  32779. break;
  32780. }
  32781. }
  32782. }, function () {
  32783. for (var i = 0; i < indices.length; ++i) {
  32784. indices[i] = dupes[indices[i]] || indices[i];
  32785. }
  32786. //indices are now reordered
  32787. var originalSubMeshes = _this.subMeshes.slice(0);
  32788. _this.setIndices(indices);
  32789. _this.subMeshes = originalSubMeshes;
  32790. if (successCallback) {
  32791. successCallback(_this);
  32792. }
  32793. });
  32794. return this;
  32795. };
  32796. /**
  32797. * Serialize current mesh
  32798. * @param serializationObject defines the object which will receive the serialization data
  32799. */
  32800. Mesh.prototype.serialize = function (serializationObject) {
  32801. serializationObject.name = this.name;
  32802. serializationObject.id = this.id;
  32803. serializationObject.type = this.getClassName();
  32804. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32805. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32806. }
  32807. serializationObject.position = this.position.asArray();
  32808. if (this.rotationQuaternion) {
  32809. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32810. }
  32811. else if (this.rotation) {
  32812. serializationObject.rotation = this.rotation.asArray();
  32813. }
  32814. serializationObject.scaling = this.scaling.asArray();
  32815. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32816. serializationObject.isEnabled = this.isEnabled(false);
  32817. serializationObject.isVisible = this.isVisible;
  32818. serializationObject.infiniteDistance = this.infiniteDistance;
  32819. serializationObject.pickable = this.isPickable;
  32820. serializationObject.receiveShadows = this.receiveShadows;
  32821. serializationObject.billboardMode = this.billboardMode;
  32822. serializationObject.visibility = this.visibility;
  32823. serializationObject.checkCollisions = this.checkCollisions;
  32824. serializationObject.isBlocker = this.isBlocker;
  32825. // Parent
  32826. if (this.parent) {
  32827. serializationObject.parentId = this.parent.id;
  32828. }
  32829. // Geometry
  32830. serializationObject.isUnIndexed = this.isUnIndexed;
  32831. var geometry = this._geometry;
  32832. if (geometry) {
  32833. var geometryId = geometry.id;
  32834. serializationObject.geometryId = geometryId;
  32835. // SubMeshes
  32836. serializationObject.subMeshes = [];
  32837. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32838. var subMesh = this.subMeshes[subIndex];
  32839. serializationObject.subMeshes.push({
  32840. materialIndex: subMesh.materialIndex,
  32841. verticesStart: subMesh.verticesStart,
  32842. verticesCount: subMesh.verticesCount,
  32843. indexStart: subMesh.indexStart,
  32844. indexCount: subMesh.indexCount
  32845. });
  32846. }
  32847. }
  32848. // Material
  32849. if (this.material) {
  32850. serializationObject.materialId = this.material.id;
  32851. }
  32852. else {
  32853. this.material = null;
  32854. }
  32855. // Morph targets
  32856. if (this.morphTargetManager) {
  32857. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32858. }
  32859. // Skeleton
  32860. if (this.skeleton) {
  32861. serializationObject.skeletonId = this.skeleton.id;
  32862. }
  32863. // Physics
  32864. //TODO implement correct serialization for physics impostors.
  32865. var impostor = this.getPhysicsImpostor();
  32866. if (impostor) {
  32867. serializationObject.physicsMass = impostor.getParam("mass");
  32868. serializationObject.physicsFriction = impostor.getParam("friction");
  32869. serializationObject.physicsRestitution = impostor.getParam("mass");
  32870. serializationObject.physicsImpostor = impostor.type;
  32871. }
  32872. // Metadata
  32873. if (this.metadata) {
  32874. serializationObject.metadata = this.metadata;
  32875. }
  32876. // Instances
  32877. serializationObject.instances = [];
  32878. for (var index = 0; index < this.instances.length; index++) {
  32879. var instance = this.instances[index];
  32880. if (instance.doNotSerialize) {
  32881. continue;
  32882. }
  32883. var serializationInstance = {
  32884. name: instance.name,
  32885. id: instance.id,
  32886. position: instance.position.asArray(),
  32887. scaling: instance.scaling.asArray()
  32888. };
  32889. if (instance.parent) {
  32890. serializationInstance.parentId = instance.parent.id;
  32891. }
  32892. if (instance.rotationQuaternion) {
  32893. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32894. }
  32895. else if (instance.rotation) {
  32896. serializationInstance.rotation = instance.rotation.asArray();
  32897. }
  32898. serializationObject.instances.push(serializationInstance);
  32899. // Animations
  32900. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32901. serializationInstance.ranges = instance.serializeAnimationRanges();
  32902. }
  32903. //
  32904. // Animations
  32905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32906. serializationObject.ranges = this.serializeAnimationRanges();
  32907. // Layer mask
  32908. serializationObject.layerMask = this.layerMask;
  32909. // Alpha
  32910. serializationObject.alphaIndex = this.alphaIndex;
  32911. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32912. // Overlay
  32913. serializationObject.overlayAlpha = this.overlayAlpha;
  32914. serializationObject.overlayColor = this.overlayColor.asArray();
  32915. serializationObject.renderOverlay = this.renderOverlay;
  32916. // Fog
  32917. serializationObject.applyFog = this.applyFog;
  32918. // Action Manager
  32919. if (this.actionManager) {
  32920. serializationObject.actions = this.actionManager.serialize(this.name);
  32921. }
  32922. };
  32923. /** @hidden */
  32924. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32925. if (!this.geometry) {
  32926. return;
  32927. }
  32928. this._markSubMeshesAsAttributesDirty();
  32929. var morphTargetManager = this._morphTargetManager;
  32930. if (morphTargetManager && morphTargetManager.vertexCount) {
  32931. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32932. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32933. this.morphTargetManager = null;
  32934. return;
  32935. }
  32936. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32937. var morphTarget = morphTargetManager.getActiveTarget(index);
  32938. var positions = morphTarget.getPositions();
  32939. if (!positions) {
  32940. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32941. return;
  32942. }
  32943. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32944. var normals = morphTarget.getNormals();
  32945. if (normals) {
  32946. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32947. }
  32948. var tangents = morphTarget.getTangents();
  32949. if (tangents) {
  32950. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32951. }
  32952. }
  32953. }
  32954. else {
  32955. var index = 0;
  32956. // Positions
  32957. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32958. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32959. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32960. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32961. }
  32962. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32963. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32964. }
  32965. index++;
  32966. }
  32967. }
  32968. };
  32969. // Statics
  32970. /**
  32971. * Returns a new Mesh object parsed from the source provided.
  32972. * @param parsedMesh is the source
  32973. * @param scene defines the hosting scene
  32974. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  32975. * @returns a new Mesh
  32976. */
  32977. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32978. var mesh;
  32979. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32980. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32981. }
  32982. else {
  32983. mesh = new Mesh(parsedMesh.name, scene);
  32984. }
  32985. mesh.id = parsedMesh.id;
  32986. if (BABYLON.Tags) {
  32987. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32988. }
  32989. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32990. if (parsedMesh.metadata !== undefined) {
  32991. mesh.metadata = parsedMesh.metadata;
  32992. }
  32993. if (parsedMesh.rotationQuaternion) {
  32994. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32995. }
  32996. else if (parsedMesh.rotation) {
  32997. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32998. }
  32999. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33000. if (parsedMesh.localMatrix) {
  33001. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33002. }
  33003. else if (parsedMesh.pivotMatrix) {
  33004. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33005. }
  33006. mesh.setEnabled(parsedMesh.isEnabled);
  33007. mesh.isVisible = parsedMesh.isVisible;
  33008. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33009. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33010. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33011. if (parsedMesh.applyFog !== undefined) {
  33012. mesh.applyFog = parsedMesh.applyFog;
  33013. }
  33014. if (parsedMesh.pickable !== undefined) {
  33015. mesh.isPickable = parsedMesh.pickable;
  33016. }
  33017. if (parsedMesh.alphaIndex !== undefined) {
  33018. mesh.alphaIndex = parsedMesh.alphaIndex;
  33019. }
  33020. mesh.receiveShadows = parsedMesh.receiveShadows;
  33021. mesh.billboardMode = parsedMesh.billboardMode;
  33022. if (parsedMesh.visibility !== undefined) {
  33023. mesh.visibility = parsedMesh.visibility;
  33024. }
  33025. mesh.checkCollisions = parsedMesh.checkCollisions;
  33026. if (parsedMesh.isBlocker !== undefined) {
  33027. mesh.isBlocker = parsedMesh.isBlocker;
  33028. }
  33029. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33030. // freezeWorldMatrix
  33031. if (parsedMesh.freezeWorldMatrix) {
  33032. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33033. }
  33034. // Parent
  33035. if (parsedMesh.parentId) {
  33036. mesh._waitingParentId = parsedMesh.parentId;
  33037. }
  33038. // Actions
  33039. if (parsedMesh.actions !== undefined) {
  33040. mesh._waitingActions = parsedMesh.actions;
  33041. }
  33042. // Overlay
  33043. if (parsedMesh.overlayAlpha !== undefined) {
  33044. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33045. }
  33046. if (parsedMesh.overlayColor !== undefined) {
  33047. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33048. }
  33049. if (parsedMesh.renderOverlay !== undefined) {
  33050. mesh.renderOverlay = parsedMesh.renderOverlay;
  33051. }
  33052. // Geometry
  33053. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33054. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33055. if (parsedMesh.delayLoadingFile) {
  33056. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33057. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33058. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33059. if (parsedMesh._binaryInfo) {
  33060. mesh._binaryInfo = parsedMesh._binaryInfo;
  33061. }
  33062. mesh._delayInfo = [];
  33063. if (parsedMesh.hasUVs) {
  33064. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33065. }
  33066. if (parsedMesh.hasUVs2) {
  33067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33068. }
  33069. if (parsedMesh.hasUVs3) {
  33070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33071. }
  33072. if (parsedMesh.hasUVs4) {
  33073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33074. }
  33075. if (parsedMesh.hasUVs5) {
  33076. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33077. }
  33078. if (parsedMesh.hasUVs6) {
  33079. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33080. }
  33081. if (parsedMesh.hasColors) {
  33082. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33083. }
  33084. if (parsedMesh.hasMatricesIndices) {
  33085. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33086. }
  33087. if (parsedMesh.hasMatricesWeights) {
  33088. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33089. }
  33090. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33091. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33092. mesh._checkDelayState();
  33093. }
  33094. }
  33095. else {
  33096. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33097. }
  33098. // Material
  33099. if (parsedMesh.materialId) {
  33100. mesh.setMaterialByID(parsedMesh.materialId);
  33101. }
  33102. else {
  33103. mesh.material = null;
  33104. }
  33105. // Morph targets
  33106. if (parsedMesh.morphTargetManagerId > -1) {
  33107. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33108. }
  33109. // Skeleton
  33110. if (parsedMesh.skeletonId > -1) {
  33111. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33112. if (parsedMesh.numBoneInfluencers) {
  33113. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33114. }
  33115. }
  33116. // Animations
  33117. if (parsedMesh.animations) {
  33118. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33119. var parsedAnimation = parsedMesh.animations[animationIndex];
  33120. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33121. }
  33122. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33123. }
  33124. if (parsedMesh.autoAnimate) {
  33125. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33126. }
  33127. // Layer Mask
  33128. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33129. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33130. }
  33131. else {
  33132. mesh.layerMask = 0x0FFFFFFF;
  33133. }
  33134. // Physics
  33135. if (parsedMesh.physicsImpostor) {
  33136. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33137. mass: parsedMesh.physicsMass,
  33138. friction: parsedMesh.physicsFriction,
  33139. restitution: parsedMesh.physicsRestitution
  33140. }, scene);
  33141. }
  33142. // Instances
  33143. if (parsedMesh.instances) {
  33144. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33145. var parsedInstance = parsedMesh.instances[index];
  33146. var instance = mesh.createInstance(parsedInstance.name);
  33147. if (parsedInstance.id) {
  33148. instance.id = parsedInstance.id;
  33149. }
  33150. if (BABYLON.Tags) {
  33151. if (parsedInstance.tags) {
  33152. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33153. }
  33154. else {
  33155. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33156. }
  33157. }
  33158. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33159. if (parsedInstance.parentId) {
  33160. instance._waitingParentId = parsedInstance.parentId;
  33161. }
  33162. if (parsedInstance.rotationQuaternion) {
  33163. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33164. }
  33165. else if (parsedInstance.rotation) {
  33166. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33167. }
  33168. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33169. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33170. instance.checkCollisions = parsedInstance.checkCollisions;
  33171. }
  33172. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33173. instance.isPickable = parsedInstance.pickable;
  33174. }
  33175. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33176. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33177. }
  33178. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33179. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33180. }
  33181. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33182. instance.alphaIndex = parsedInstance.alphaIndex;
  33183. }
  33184. // Physics
  33185. if (parsedInstance.physicsImpostor) {
  33186. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33187. mass: parsedInstance.physicsMass,
  33188. friction: parsedInstance.physicsFriction,
  33189. restitution: parsedInstance.physicsRestitution
  33190. }, scene);
  33191. }
  33192. // Animation
  33193. if (parsedInstance.animations) {
  33194. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33195. parsedAnimation = parsedInstance.animations[animationIndex];
  33196. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33197. }
  33198. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33199. if (parsedInstance.autoAnimate) {
  33200. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33201. }
  33202. }
  33203. }
  33204. }
  33205. return mesh;
  33206. };
  33207. /**
  33208. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33209. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33210. * @param name defines the name of the mesh to create
  33211. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33212. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33213. * @param closePath creates a seam between the first and the last points of each path of the path array
  33214. * @param offset is taken in account only if the `pathArray` is containing a single path
  33215. * @param scene defines the hosting scene
  33216. * @param updatable defines if the mesh must be flagged as updatable
  33217. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33218. * @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)
  33219. * @returns a new Mesh
  33220. */
  33221. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33222. if (closeArray === void 0) { closeArray = false; }
  33223. if (updatable === void 0) { updatable = false; }
  33224. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33225. pathArray: pathArray,
  33226. closeArray: closeArray,
  33227. closePath: closePath,
  33228. offset: offset,
  33229. updatable: updatable,
  33230. sideOrientation: sideOrientation,
  33231. instance: instance
  33232. }, scene);
  33233. };
  33234. /**
  33235. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33236. * @param name defines the name of the mesh to create
  33237. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33238. * @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
  33239. * @param scene defines the hosting scene
  33240. * @param updatable defines if the mesh must be flagged as updatable
  33241. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33242. * @returns a new Mesh
  33243. */
  33244. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33245. if (scene === void 0) { scene = null; }
  33246. var options = {
  33247. radius: radius,
  33248. tessellation: tessellation,
  33249. sideOrientation: sideOrientation,
  33250. updatable: updatable
  33251. };
  33252. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33253. };
  33254. /**
  33255. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33256. * @param name defines the name of the mesh to create
  33257. * @param size sets the size (float) of each box side (default 1)
  33258. * @param scene defines the hosting scene
  33259. * @param updatable defines if the mesh must be flagged as updatable
  33260. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33261. * @returns a new Mesh
  33262. */
  33263. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33264. if (scene === void 0) { scene = null; }
  33265. var options = {
  33266. size: size,
  33267. sideOrientation: sideOrientation,
  33268. updatable: updatable
  33269. };
  33270. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33271. };
  33272. /**
  33273. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33274. * @param name defines the name of the mesh to create
  33275. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33276. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33277. * @param scene defines the hosting scene
  33278. * @param updatable defines if the mesh must be flagged as updatable
  33279. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33280. * @returns a new Mesh
  33281. */
  33282. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33283. var options = {
  33284. segments: segments,
  33285. diameterX: diameter,
  33286. diameterY: diameter,
  33287. diameterZ: diameter,
  33288. sideOrientation: sideOrientation,
  33289. updatable: updatable
  33290. };
  33291. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33292. };
  33293. /**
  33294. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33295. * @param name defines the name of the mesh to create
  33296. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33297. * @param diameterTop set the top cap diameter (floats, default 1)
  33298. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33299. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33300. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33301. * @param scene defines the hosting scene
  33302. * @param updatable defines if the mesh must be flagged as updatable
  33303. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33304. * @returns a new Mesh
  33305. */
  33306. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33307. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33308. if (scene !== undefined) {
  33309. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33310. updatable = scene;
  33311. }
  33312. scene = subdivisions;
  33313. subdivisions = 1;
  33314. }
  33315. var options = {
  33316. height: height,
  33317. diameterTop: diameterTop,
  33318. diameterBottom: diameterBottom,
  33319. tessellation: tessellation,
  33320. subdivisions: subdivisions,
  33321. sideOrientation: sideOrientation,
  33322. updatable: updatable
  33323. };
  33324. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33325. };
  33326. // Torus (Code from SharpDX.org)
  33327. /**
  33328. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33329. * @param name defines the name of the mesh to create
  33330. * @param diameter sets the diameter size (float) of the torus (default 1)
  33331. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33332. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33333. * @param scene defines the hosting scene
  33334. * @param updatable defines if the mesh must be flagged as updatable
  33335. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33336. * @returns a new Mesh
  33337. */
  33338. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33339. var options = {
  33340. diameter: diameter,
  33341. thickness: thickness,
  33342. tessellation: tessellation,
  33343. sideOrientation: sideOrientation,
  33344. updatable: updatable
  33345. };
  33346. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33347. };
  33348. /**
  33349. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33350. * @param name defines the name of the mesh to create
  33351. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33352. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33353. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33354. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33355. * @param p the number of windings on X axis (positive integers, default 2)
  33356. * @param q the number of windings on Y axis (positive integers, default 3)
  33357. * @param scene defines the hosting scene
  33358. * @param updatable defines if the mesh must be flagged as updatable
  33359. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33360. * @returns a new Mesh
  33361. */
  33362. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33363. var options = {
  33364. radius: radius,
  33365. tube: tube,
  33366. radialSegments: radialSegments,
  33367. tubularSegments: tubularSegments,
  33368. p: p,
  33369. q: q,
  33370. sideOrientation: sideOrientation,
  33371. updatable: updatable
  33372. };
  33373. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33374. };
  33375. /**
  33376. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33377. * @param name defines the name of the mesh to create
  33378. * @param points is an array successive Vector3
  33379. * @param scene defines the hosting scene
  33380. * @param updatable defines if the mesh must be flagged as updatable
  33381. * @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).
  33382. * @returns a new Mesh
  33383. */
  33384. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33385. if (scene === void 0) { scene = null; }
  33386. if (updatable === void 0) { updatable = false; }
  33387. if (instance === void 0) { instance = null; }
  33388. var options = {
  33389. points: points,
  33390. updatable: updatable,
  33391. instance: instance
  33392. };
  33393. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33394. };
  33395. /**
  33396. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33397. * @param name defines the name of the mesh to create
  33398. * @param points is an array successive Vector3
  33399. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33400. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33401. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33402. * @param scene defines the hosting scene
  33403. * @param updatable defines if the mesh must be flagged as updatable
  33404. * @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)
  33405. * @returns a new Mesh
  33406. */
  33407. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33408. if (scene === void 0) { scene = null; }
  33409. var options = {
  33410. points: points,
  33411. dashSize: dashSize,
  33412. gapSize: gapSize,
  33413. dashNb: dashNb,
  33414. updatable: updatable,
  33415. instance: instance
  33416. };
  33417. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33418. };
  33419. /**
  33420. * Creates a polygon mesh.
  33421. * Please consider using the same method from the MeshBuilder class instead.
  33422. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33423. * 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.
  33424. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33426. * Remember you can only change the shape positions, not their number when updating a polygon.
  33427. */
  33428. /**
  33429. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33430. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33431. * @param name defines the name of the mesh to create
  33432. * @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
  33433. * @param scene defines the hosting scene
  33434. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33435. * @param updatable defines if the mesh must be flagged as updatable
  33436. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33437. * @returns a new Mesh
  33438. */
  33439. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33440. var options = {
  33441. shape: shape,
  33442. holes: holes,
  33443. updatable: updatable,
  33444. sideOrientation: sideOrientation
  33445. };
  33446. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33447. };
  33448. /**
  33449. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33450. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33451. * @param name defines the name of the mesh to create
  33452. * @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
  33453. * @param depth defines the height of extrusion
  33454. * @param scene defines the hosting scene
  33455. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  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.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33461. var options = {
  33462. shape: shape,
  33463. holes: holes,
  33464. depth: depth,
  33465. updatable: updatable,
  33466. sideOrientation: sideOrientation
  33467. };
  33468. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33469. };
  33470. /**
  33471. * Creates an extruded shape mesh.
  33472. * 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
  33473. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33474. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33475. * @param name defines the name of the mesh to create
  33476. * @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
  33477. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33478. * @param scale is the value to scale the shape
  33479. * @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
  33480. * @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
  33481. * @param scene defines the hosting scene
  33482. * @param updatable defines if the mesh must be flagged as updatable
  33483. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33484. * @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)
  33485. * @returns a new Mesh
  33486. */
  33487. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33488. if (scene === void 0) { scene = null; }
  33489. var options = {
  33490. shape: shape,
  33491. path: path,
  33492. scale: scale,
  33493. rotation: rotation,
  33494. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33495. sideOrientation: sideOrientation,
  33496. instance: instance,
  33497. updatable: updatable
  33498. };
  33499. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33500. };
  33501. /**
  33502. * Creates an custom extruded shape mesh.
  33503. * The custom extrusion is a parametric shape.
  33504. * It has no predefined shape. Its final shape will depend on the input parameters.
  33505. * Please consider using the same method from the MeshBuilder class instead
  33506. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33507. * @param name defines the name of the mesh to create
  33508. * @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
  33509. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33510. * @param scaleFunction is a custom Javascript function called on each path point
  33511. * @param rotationFunction is a custom Javascript function called on each path point
  33512. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33513. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33514. * @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
  33515. * @param scene defines the hosting scene
  33516. * @param updatable defines if the mesh must be flagged as updatable
  33517. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33518. * @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)
  33519. * @returns a new Mesh
  33520. */
  33521. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33522. var options = {
  33523. shape: shape,
  33524. path: path,
  33525. scaleFunction: scaleFunction,
  33526. rotationFunction: rotationFunction,
  33527. ribbonCloseArray: ribbonCloseArray,
  33528. ribbonClosePath: ribbonClosePath,
  33529. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33530. sideOrientation: sideOrientation,
  33531. instance: instance,
  33532. updatable: updatable
  33533. };
  33534. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33535. };
  33536. /**
  33537. * Creates lathe mesh.
  33538. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33539. * Please consider using the same method from the MeshBuilder class instead
  33540. * @param name defines the name of the mesh to create
  33541. * @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
  33542. * @param radius is the radius value of the lathe
  33543. * @param tessellation is the side number of the lathe.
  33544. * @param scene defines the hosting scene
  33545. * @param updatable defines if the mesh must be flagged as updatable
  33546. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33547. * @returns a new Mesh
  33548. */
  33549. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33550. var options = {
  33551. shape: shape,
  33552. radius: radius,
  33553. tessellation: tessellation,
  33554. sideOrientation: sideOrientation,
  33555. updatable: updatable
  33556. };
  33557. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33558. };
  33559. /**
  33560. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33561. * @param name defines the name of the mesh to create
  33562. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33563. * @param scene defines the hosting scene
  33564. * @param updatable defines if the mesh must be flagged as updatable
  33565. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33566. * @returns a new Mesh
  33567. */
  33568. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33569. var options = {
  33570. size: size,
  33571. width: size,
  33572. height: size,
  33573. sideOrientation: sideOrientation,
  33574. updatable: updatable
  33575. };
  33576. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33577. };
  33578. /**
  33579. * Creates a ground mesh.
  33580. * Please consider using the same method from the MeshBuilder class instead
  33581. * @param name defines the name of the mesh to create
  33582. * @param width set the width of the ground
  33583. * @param height set the height of the ground
  33584. * @param subdivisions sets the number of subdivisions per side
  33585. * @param scene defines the hosting scene
  33586. * @param updatable defines if the mesh must be flagged as updatable
  33587. * @returns a new Mesh
  33588. */
  33589. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33590. var options = {
  33591. width: width,
  33592. height: height,
  33593. subdivisions: subdivisions,
  33594. updatable: updatable
  33595. };
  33596. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33597. };
  33598. /**
  33599. * Creates a tiled ground mesh.
  33600. * Please consider using the same method from the MeshBuilder class instead
  33601. * @param name defines the name of the mesh to create
  33602. * @param xmin set the ground minimum X coordinate
  33603. * @param zmin set the ground minimum Y coordinate
  33604. * @param xmax set the ground maximum X coordinate
  33605. * @param zmax set the ground maximum Z coordinate
  33606. * @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
  33607. * @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
  33608. * @param scene defines the hosting scene
  33609. * @param updatable defines if the mesh must be flagged as updatable
  33610. * @returns a new Mesh
  33611. */
  33612. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33613. var options = {
  33614. xmin: xmin,
  33615. zmin: zmin,
  33616. xmax: xmax,
  33617. zmax: zmax,
  33618. subdivisions: subdivisions,
  33619. precision: precision,
  33620. updatable: updatable
  33621. };
  33622. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33623. };
  33624. /**
  33625. * Creates a ground mesh from a height map.
  33626. * Please consider using the same method from the MeshBuilder class instead
  33627. * @see http://doc.babylonjs.com/babylon101/height_map
  33628. * @param name defines the name of the mesh to create
  33629. * @param url sets the URL of the height map image resource
  33630. * @param width set the ground width size
  33631. * @param height set the ground height size
  33632. * @param subdivisions sets the number of subdivision per side
  33633. * @param minHeight is the minimum altitude on the ground
  33634. * @param maxHeight is the maximum altitude on the ground
  33635. * @param scene defines the hosting scene
  33636. * @param updatable defines if the mesh must be flagged as updatable
  33637. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33638. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33639. * @returns a new Mesh
  33640. */
  33641. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33642. var options = {
  33643. width: width,
  33644. height: height,
  33645. subdivisions: subdivisions,
  33646. minHeight: minHeight,
  33647. maxHeight: maxHeight,
  33648. updatable: updatable,
  33649. onReady: onReady,
  33650. alphaFilter: alphaFilter
  33651. };
  33652. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33653. };
  33654. /**
  33655. * Creates a tube mesh.
  33656. * The tube is a parametric shape.
  33657. * It has no predefined shape. Its final shape will depend on the input parameters.
  33658. * Please consider using the same method from the MeshBuilder class instead
  33659. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33660. * @param name defines the name of the mesh to create
  33661. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33662. * @param radius sets the tube radius size
  33663. * @param tessellation is the number of sides on the tubular surface
  33664. * @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
  33665. * @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
  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. * @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)
  33670. * @returns a new Mesh
  33671. */
  33672. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33673. var options = {
  33674. path: path,
  33675. radius: radius,
  33676. tessellation: tessellation,
  33677. radiusFunction: radiusFunction,
  33678. arc: 1,
  33679. cap: cap,
  33680. updatable: updatable,
  33681. sideOrientation: sideOrientation,
  33682. instance: instance
  33683. };
  33684. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33685. };
  33686. /**
  33687. * Creates a polyhedron mesh.
  33688. * Please consider using the same method from the MeshBuilder class instead.
  33689. * * 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
  33690. * * The parameter `size` (positive float, default 1) sets the polygon size
  33691. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33692. * * 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`
  33693. * * 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
  33694. * * 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)`)
  33695. * * 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
  33696. * * 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
  33697. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33698. * * 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
  33699. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33700. * @param name defines the name of the mesh to create
  33701. * @param options defines the options used to create the mesh
  33702. * @param scene defines the hosting scene
  33703. * @returns a new Mesh
  33704. */
  33705. Mesh.CreatePolyhedron = function (name, options, scene) {
  33706. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33707. };
  33708. /**
  33709. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33710. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33711. * * 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`)
  33712. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33713. * * 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
  33714. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33715. * * 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
  33716. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33717. * @param name defines the name of the mesh
  33718. * @param options defines the options used to create the mesh
  33719. * @param scene defines the hosting scene
  33720. * @returns a new Mesh
  33721. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33722. */
  33723. Mesh.CreateIcoSphere = function (name, options, scene) {
  33724. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates a decal mesh.
  33728. * Please consider using the same method from the MeshBuilder class instead.
  33729. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33730. * @param name defines the name of the mesh
  33731. * @param sourceMesh defines the mesh receiving the decal
  33732. * @param position sets the position of the decal in world coordinates
  33733. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33734. * @param size sets the decal scaling
  33735. * @param angle sets the angle to rotate the decal
  33736. * @returns a new Mesh
  33737. */
  33738. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33739. var options = {
  33740. position: position,
  33741. normal: normal,
  33742. size: size,
  33743. angle: angle
  33744. };
  33745. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33746. };
  33747. // Skeletons
  33748. /**
  33749. * Prepare internal position array for software CPU skinning
  33750. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33751. */
  33752. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33753. if (!this._sourcePositions) {
  33754. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33755. if (!source) {
  33756. return this._sourcePositions;
  33757. }
  33758. this._sourcePositions = new Float32Array(source);
  33759. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33760. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33761. }
  33762. }
  33763. return this._sourcePositions;
  33764. };
  33765. /**
  33766. * Prepare internal normal array for software CPU skinning
  33767. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33768. */
  33769. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33770. if (!this._sourceNormals) {
  33771. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33772. if (!source) {
  33773. return this._sourceNormals;
  33774. }
  33775. this._sourceNormals = new Float32Array(source);
  33776. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33777. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33778. }
  33779. }
  33780. return this._sourceNormals;
  33781. };
  33782. /**
  33783. * Updates the vertex buffer by applying transformation from the bones
  33784. * @param skeleton defines the skeleton to apply to current mesh
  33785. * @returns the current mesh
  33786. */
  33787. Mesh.prototype.applySkeleton = function (skeleton) {
  33788. if (!this.geometry) {
  33789. return this;
  33790. }
  33791. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33792. return this;
  33793. }
  33794. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33796. return this;
  33797. }
  33798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33799. return this;
  33800. }
  33801. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33802. return this;
  33803. }
  33804. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33805. return this;
  33806. }
  33807. if (!this._sourcePositions) {
  33808. var submeshes = this.subMeshes.slice();
  33809. this.setPositionsForCPUSkinning();
  33810. this.subMeshes = submeshes;
  33811. }
  33812. if (!this._sourceNormals) {
  33813. this.setNormalsForCPUSkinning();
  33814. }
  33815. // positionsData checks for not being Float32Array will only pass at most once
  33816. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33817. if (!positionsData) {
  33818. return this;
  33819. }
  33820. if (!(positionsData instanceof Float32Array)) {
  33821. positionsData = new Float32Array(positionsData);
  33822. }
  33823. // normalsData checks for not being Float32Array will only pass at most once
  33824. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33825. if (!normalsData) {
  33826. return this;
  33827. }
  33828. if (!(normalsData instanceof Float32Array)) {
  33829. normalsData = new Float32Array(normalsData);
  33830. }
  33831. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33832. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33833. if (!matricesWeightsData || !matricesIndicesData) {
  33834. return this;
  33835. }
  33836. var needExtras = this.numBoneInfluencers > 4;
  33837. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33838. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33839. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33840. var tempVector3 = BABYLON.Vector3.Zero();
  33841. var finalMatrix = new BABYLON.Matrix();
  33842. var tempMatrix = new BABYLON.Matrix();
  33843. var matWeightIdx = 0;
  33844. var inf;
  33845. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33846. var weight;
  33847. for (inf = 0; inf < 4; inf++) {
  33848. weight = matricesWeightsData[matWeightIdx + inf];
  33849. if (weight > 0) {
  33850. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33851. finalMatrix.addToSelf(tempMatrix);
  33852. }
  33853. }
  33854. if (needExtras) {
  33855. for (inf = 0; inf < 4; inf++) {
  33856. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33857. if (weight > 0) {
  33858. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33859. finalMatrix.addToSelf(tempMatrix);
  33860. }
  33861. }
  33862. }
  33863. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33864. tempVector3.toArray(positionsData, index);
  33865. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33866. tempVector3.toArray(normalsData, index);
  33867. finalMatrix.reset();
  33868. }
  33869. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33870. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33871. return this;
  33872. };
  33873. // Tools
  33874. /**
  33875. * 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
  33876. * @param meshes defines the list of meshes to scan
  33877. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  33878. */
  33879. Mesh.MinMax = function (meshes) {
  33880. var minVector = null;
  33881. var maxVector = null;
  33882. meshes.forEach(function (mesh, index, array) {
  33883. var boundingInfo = mesh.getBoundingInfo();
  33884. var boundingBox = boundingInfo.boundingBox;
  33885. if (!minVector || !maxVector) {
  33886. minVector = boundingBox.minimumWorld;
  33887. maxVector = boundingBox.maximumWorld;
  33888. }
  33889. else {
  33890. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33891. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33892. }
  33893. });
  33894. if (!minVector || !maxVector) {
  33895. return {
  33896. min: BABYLON.Vector3.Zero(),
  33897. max: BABYLON.Vector3.Zero()
  33898. };
  33899. }
  33900. return {
  33901. min: minVector,
  33902. max: maxVector
  33903. };
  33904. };
  33905. /**
  33906. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  33907. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  33908. * @returns a vector3
  33909. */
  33910. Mesh.Center = function (meshesOrMinMaxVector) {
  33911. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33912. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33913. };
  33914. /**
  33915. * Merge the array of meshes into a single mesh for performance reasons.
  33916. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  33917. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  33918. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  33919. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33920. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  33921. * @returns a new mesh
  33922. */
  33923. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33924. if (disposeSource === void 0) { disposeSource = true; }
  33925. var index;
  33926. if (!allow32BitsIndices) {
  33927. var totalVertices = 0;
  33928. // Counting vertices
  33929. for (index = 0; index < meshes.length; index++) {
  33930. if (meshes[index]) {
  33931. totalVertices += meshes[index].getTotalVertices();
  33932. if (totalVertices > 65536) {
  33933. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33934. return null;
  33935. }
  33936. }
  33937. }
  33938. }
  33939. // Merge
  33940. var vertexData = null;
  33941. var otherVertexData;
  33942. var indiceArray = new Array();
  33943. var source = null;
  33944. for (index = 0; index < meshes.length; index++) {
  33945. if (meshes[index]) {
  33946. var wm = meshes[index].computeWorldMatrix(true);
  33947. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33948. otherVertexData.transform(wm);
  33949. if (vertexData) {
  33950. vertexData.merge(otherVertexData, allow32BitsIndices);
  33951. }
  33952. else {
  33953. vertexData = otherVertexData;
  33954. source = meshes[index];
  33955. }
  33956. if (subdivideWithSubMeshes) {
  33957. indiceArray.push(meshes[index].getTotalIndices());
  33958. }
  33959. }
  33960. }
  33961. source = source;
  33962. if (!meshSubclass) {
  33963. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33964. }
  33965. vertexData.applyToMesh(meshSubclass);
  33966. // Setting properties
  33967. meshSubclass.material = source.material;
  33968. meshSubclass.checkCollisions = source.checkCollisions;
  33969. // Cleaning
  33970. if (disposeSource) {
  33971. for (index = 0; index < meshes.length; index++) {
  33972. if (meshes[index]) {
  33973. meshes[index].dispose();
  33974. }
  33975. }
  33976. }
  33977. // Subdivide
  33978. if (subdivideWithSubMeshes) {
  33979. //-- removal of global submesh
  33980. meshSubclass.releaseSubMeshes();
  33981. index = 0;
  33982. var offset = 0;
  33983. //-- apply subdivision according to index table
  33984. while (index < indiceArray.length) {
  33985. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33986. offset += indiceArray[index];
  33987. index++;
  33988. }
  33989. }
  33990. return meshSubclass;
  33991. };
  33992. // Consts
  33993. /**
  33994. * Mesh side orientation : usually the external or front surface
  33995. */
  33996. Mesh.FRONTSIDE = 0;
  33997. /**
  33998. * Mesh side orientation : usually the internal or back surface
  33999. */
  34000. Mesh.BACKSIDE = 1;
  34001. /**
  34002. * Mesh side orientation : both internal and external or front and back surfaces
  34003. */
  34004. Mesh.DOUBLESIDE = 2;
  34005. /**
  34006. * Mesh side orientation : by default, `FRONTSIDE`
  34007. */
  34008. Mesh.DEFAULTSIDE = 0;
  34009. /**
  34010. * Mesh cap setting : no cap
  34011. */
  34012. Mesh.NO_CAP = 0;
  34013. /**
  34014. * Mesh cap setting : one cap at the beginning of the mesh
  34015. */
  34016. Mesh.CAP_START = 1;
  34017. /**
  34018. * Mesh cap setting : one cap at the end of the mesh
  34019. */
  34020. Mesh.CAP_END = 2;
  34021. /**
  34022. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34023. */
  34024. Mesh.CAP_ALL = 3;
  34025. return Mesh;
  34026. }(BABYLON.AbstractMesh));
  34027. BABYLON.Mesh = Mesh;
  34028. })(BABYLON || (BABYLON = {}));
  34029. //# sourceMappingURL=babylon.mesh.js.map
  34030. var BABYLON;
  34031. (function (BABYLON) {
  34032. var BaseSubMesh = /** @class */ (function () {
  34033. function BaseSubMesh() {
  34034. }
  34035. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34036. get: function () {
  34037. return this._materialEffect;
  34038. },
  34039. enumerable: true,
  34040. configurable: true
  34041. });
  34042. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34043. if (defines === void 0) { defines = null; }
  34044. if (this._materialEffect === effect) {
  34045. if (!effect) {
  34046. this._materialDefines = null;
  34047. }
  34048. return;
  34049. }
  34050. this._materialDefines = defines;
  34051. this._materialEffect = effect;
  34052. };
  34053. return BaseSubMesh;
  34054. }());
  34055. BABYLON.BaseSubMesh = BaseSubMesh;
  34056. var SubMesh = /** @class */ (function (_super) {
  34057. __extends(SubMesh, _super);
  34058. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34059. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34060. var _this = _super.call(this) || this;
  34061. _this.materialIndex = materialIndex;
  34062. _this.verticesStart = verticesStart;
  34063. _this.verticesCount = verticesCount;
  34064. _this.indexStart = indexStart;
  34065. _this.indexCount = indexCount;
  34066. /** @hidden */
  34067. _this._renderId = 0;
  34068. _this._mesh = mesh;
  34069. _this._renderingMesh = renderingMesh || mesh;
  34070. mesh.subMeshes.push(_this);
  34071. _this._trianglePlanes = [];
  34072. _this._id = mesh.subMeshes.length - 1;
  34073. if (createBoundingBox) {
  34074. _this.refreshBoundingInfo();
  34075. mesh.computeWorldMatrix(true);
  34076. }
  34077. return _this;
  34078. }
  34079. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34080. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34081. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34082. };
  34083. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34084. get: function () {
  34085. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. /**
  34091. * Returns the submesh BoudingInfo object.
  34092. */
  34093. SubMesh.prototype.getBoundingInfo = function () {
  34094. if (this.IsGlobal) {
  34095. return this._mesh.getBoundingInfo();
  34096. }
  34097. return this._boundingInfo;
  34098. };
  34099. /**
  34100. * Sets the submesh BoundingInfo.
  34101. * Return the SubMesh.
  34102. */
  34103. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34104. this._boundingInfo = boundingInfo;
  34105. return this;
  34106. };
  34107. /**
  34108. * Returns the mesh of the current submesh.
  34109. */
  34110. SubMesh.prototype.getMesh = function () {
  34111. return this._mesh;
  34112. };
  34113. /**
  34114. * Returns the rendering mesh of the submesh.
  34115. */
  34116. SubMesh.prototype.getRenderingMesh = function () {
  34117. return this._renderingMesh;
  34118. };
  34119. /**
  34120. * Returns the submesh material.
  34121. */
  34122. SubMesh.prototype.getMaterial = function () {
  34123. var rootMaterial = this._renderingMesh.material;
  34124. if (rootMaterial === null || rootMaterial === undefined) {
  34125. return this._mesh.getScene().defaultMaterial;
  34126. }
  34127. else if (rootMaterial.getSubMaterial) {
  34128. var multiMaterial = rootMaterial;
  34129. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34130. if (this._currentMaterial !== effectiveMaterial) {
  34131. this._currentMaterial = effectiveMaterial;
  34132. this._materialDefines = null;
  34133. }
  34134. return effectiveMaterial;
  34135. }
  34136. return rootMaterial;
  34137. };
  34138. // Methods
  34139. /**
  34140. * Sets a new updated BoundingInfo object to the submesh.
  34141. * Returns the SubMesh.
  34142. */
  34143. SubMesh.prototype.refreshBoundingInfo = function () {
  34144. this._lastColliderWorldVertices = null;
  34145. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34146. return this;
  34147. }
  34148. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34149. if (!data) {
  34150. this._boundingInfo = this._mesh.getBoundingInfo();
  34151. return this;
  34152. }
  34153. var indices = this._renderingMesh.getIndices();
  34154. var extend;
  34155. //is this the only submesh?
  34156. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34157. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34158. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34159. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34160. }
  34161. else {
  34162. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34163. }
  34164. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34165. return this;
  34166. };
  34167. /** @hidden */
  34168. SubMesh.prototype._checkCollision = function (collider) {
  34169. var boundingInfo = this.getBoundingInfo();
  34170. return boundingInfo._checkCollision(collider);
  34171. };
  34172. /**
  34173. * Updates the submesh BoundingInfo.
  34174. * Returns the Submesh.
  34175. */
  34176. SubMesh.prototype.updateBoundingInfo = function (world) {
  34177. var boundingInfo = this.getBoundingInfo();
  34178. if (!boundingInfo) {
  34179. this.refreshBoundingInfo();
  34180. boundingInfo = this.getBoundingInfo();
  34181. }
  34182. boundingInfo.update(world);
  34183. return this;
  34184. };
  34185. /**
  34186. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34187. * Boolean returned.
  34188. */
  34189. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34190. var boundingInfo = this.getBoundingInfo();
  34191. if (!boundingInfo) {
  34192. return false;
  34193. }
  34194. return boundingInfo.isInFrustum(frustumPlanes);
  34195. };
  34196. /**
  34197. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34198. * Boolean returned.
  34199. */
  34200. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34201. var boundingInfo = this.getBoundingInfo();
  34202. if (!boundingInfo) {
  34203. return false;
  34204. }
  34205. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34206. };
  34207. /**
  34208. * Renders the submesh.
  34209. * Returns it.
  34210. */
  34211. SubMesh.prototype.render = function (enableAlphaMode) {
  34212. this._renderingMesh.render(this, enableAlphaMode);
  34213. return this;
  34214. };
  34215. /**
  34216. * Returns a new Index Buffer.
  34217. * Type returned : WebGLBuffer.
  34218. */
  34219. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34220. if (!this._linesIndexBuffer) {
  34221. var linesIndices = [];
  34222. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34223. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34224. }
  34225. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34226. this.linesIndexCount = linesIndices.length;
  34227. }
  34228. return this._linesIndexBuffer;
  34229. };
  34230. /**
  34231. * True is the passed Ray intersects the submesh bounding box.
  34232. * Boolean returned.
  34233. */
  34234. SubMesh.prototype.canIntersects = function (ray) {
  34235. var boundingInfo = this.getBoundingInfo();
  34236. if (!boundingInfo) {
  34237. return false;
  34238. }
  34239. return ray.intersectsBox(boundingInfo.boundingBox);
  34240. };
  34241. /**
  34242. * Returns an object IntersectionInfo.
  34243. */
  34244. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34245. var intersectInfo = null;
  34246. var material = this.getMaterial();
  34247. if (!material) {
  34248. return null;
  34249. }
  34250. switch (material.fillMode) {
  34251. case BABYLON.Material.PointListDrawMode:
  34252. case BABYLON.Material.LineListDrawMode:
  34253. case BABYLON.Material.LineLoopDrawMode:
  34254. case BABYLON.Material.LineStripDrawMode:
  34255. case BABYLON.Material.TriangleFanDrawMode:
  34256. case BABYLON.Material.TriangleStripDrawMode:
  34257. return null;
  34258. }
  34259. // LineMesh first as it's also a Mesh...
  34260. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34261. var lineMesh = this._mesh;
  34262. // Line test
  34263. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34264. var p0 = positions[indices[index]];
  34265. var p1 = positions[indices[index + 1]];
  34266. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34267. if (length < 0) {
  34268. continue;
  34269. }
  34270. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34271. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34272. if (fastCheck) {
  34273. break;
  34274. }
  34275. }
  34276. }
  34277. }
  34278. else {
  34279. // Triangles test
  34280. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34281. var p0 = positions[indices[index]];
  34282. var p1 = positions[indices[index + 1]];
  34283. var p2 = positions[indices[index + 2]];
  34284. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34285. if (currentIntersectInfo) {
  34286. if (currentIntersectInfo.distance < 0) {
  34287. continue;
  34288. }
  34289. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34290. intersectInfo = currentIntersectInfo;
  34291. intersectInfo.faceId = index / 3;
  34292. if (fastCheck) {
  34293. break;
  34294. }
  34295. }
  34296. }
  34297. }
  34298. }
  34299. return intersectInfo;
  34300. };
  34301. /** @hidden */
  34302. SubMesh.prototype._rebuild = function () {
  34303. if (this._linesIndexBuffer) {
  34304. this._linesIndexBuffer = null;
  34305. }
  34306. };
  34307. // Clone
  34308. /**
  34309. * Creates a new Submesh from the passed Mesh.
  34310. */
  34311. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34312. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34313. if (!this.IsGlobal) {
  34314. var boundingInfo = this.getBoundingInfo();
  34315. if (!boundingInfo) {
  34316. return result;
  34317. }
  34318. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34319. }
  34320. return result;
  34321. };
  34322. // Dispose
  34323. /**
  34324. * Disposes the Submesh.
  34325. * Returns nothing.
  34326. */
  34327. SubMesh.prototype.dispose = function () {
  34328. if (this._linesIndexBuffer) {
  34329. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34330. this._linesIndexBuffer = null;
  34331. }
  34332. // Remove from mesh
  34333. var index = this._mesh.subMeshes.indexOf(this);
  34334. this._mesh.subMeshes.splice(index, 1);
  34335. };
  34336. // Statics
  34337. /**
  34338. * Creates a new Submesh from the passed parameters :
  34339. * - materialIndex (integer) : the index of the main mesh material.
  34340. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34341. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34342. * - mesh (Mesh) : the main mesh to create the submesh from.
  34343. * - renderingMesh (optional Mesh) : rendering mesh.
  34344. */
  34345. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34346. var minVertexIndex = Number.MAX_VALUE;
  34347. var maxVertexIndex = -Number.MAX_VALUE;
  34348. renderingMesh = (renderingMesh || mesh);
  34349. var indices = renderingMesh.getIndices();
  34350. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34351. var vertexIndex = indices[index];
  34352. if (vertexIndex < minVertexIndex)
  34353. minVertexIndex = vertexIndex;
  34354. if (vertexIndex > maxVertexIndex)
  34355. maxVertexIndex = vertexIndex;
  34356. }
  34357. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34358. };
  34359. return SubMesh;
  34360. }(BaseSubMesh));
  34361. BABYLON.SubMesh = SubMesh;
  34362. })(BABYLON || (BABYLON = {}));
  34363. //# sourceMappingURL=babylon.subMesh.js.map
  34364. var __assign = (this && this.__assign) || function () {
  34365. __assign = Object.assign || function(t) {
  34366. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34367. s = arguments[i];
  34368. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34369. t[p] = s[p];
  34370. }
  34371. return t;
  34372. };
  34373. return __assign.apply(this, arguments);
  34374. };
  34375. var BABYLON;
  34376. (function (BABYLON) {
  34377. /**
  34378. * Manages the defines for the Material
  34379. */
  34380. var MaterialDefines = /** @class */ (function () {
  34381. function MaterialDefines() {
  34382. this._isDirty = true;
  34383. /** @hidden */
  34384. this._areLightsDirty = true;
  34385. /** @hidden */
  34386. this._areAttributesDirty = true;
  34387. /** @hidden */
  34388. this._areTexturesDirty = true;
  34389. /** @hidden */
  34390. this._areFresnelDirty = true;
  34391. /** @hidden */
  34392. this._areMiscDirty = true;
  34393. /** @hidden */
  34394. this._areImageProcessingDirty = true;
  34395. /** @hidden */
  34396. this._normals = false;
  34397. /** @hidden */
  34398. this._uvs = false;
  34399. /** @hidden */
  34400. this._needNormals = false;
  34401. /** @hidden */
  34402. this._needUVs = false;
  34403. }
  34404. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34405. /**
  34406. * Specifies if the material needs to be re-calculated
  34407. */
  34408. get: function () {
  34409. return this._isDirty;
  34410. },
  34411. enumerable: true,
  34412. configurable: true
  34413. });
  34414. /**
  34415. * Marks the material to indicate that it has been re-calculated
  34416. */
  34417. MaterialDefines.prototype.markAsProcessed = function () {
  34418. this._isDirty = false;
  34419. this._areAttributesDirty = false;
  34420. this._areTexturesDirty = false;
  34421. this._areFresnelDirty = false;
  34422. this._areLightsDirty = false;
  34423. this._areMiscDirty = false;
  34424. this._areImageProcessingDirty = false;
  34425. };
  34426. /**
  34427. * Marks the material to indicate that it needs to be re-calculated
  34428. */
  34429. MaterialDefines.prototype.markAsUnprocessed = function () {
  34430. this._isDirty = true;
  34431. };
  34432. /**
  34433. * Marks the material to indicate all of its defines need to be re-calculated
  34434. */
  34435. MaterialDefines.prototype.markAllAsDirty = function () {
  34436. this._areTexturesDirty = true;
  34437. this._areAttributesDirty = true;
  34438. this._areLightsDirty = true;
  34439. this._areFresnelDirty = true;
  34440. this._areMiscDirty = true;
  34441. this._areImageProcessingDirty = true;
  34442. this._isDirty = true;
  34443. };
  34444. /**
  34445. * Marks the material to indicate that image processing needs to be re-calculated
  34446. */
  34447. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34448. this._areImageProcessingDirty = true;
  34449. this._isDirty = true;
  34450. };
  34451. /**
  34452. * Marks the material to indicate the lights need to be re-calculated
  34453. */
  34454. MaterialDefines.prototype.markAsLightDirty = function () {
  34455. this._areLightsDirty = true;
  34456. this._isDirty = true;
  34457. };
  34458. /**
  34459. * Marks the attribute state as changed
  34460. */
  34461. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34462. this._areAttributesDirty = true;
  34463. this._isDirty = true;
  34464. };
  34465. /**
  34466. * Marks the texture state as changed
  34467. */
  34468. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34469. this._areTexturesDirty = true;
  34470. this._isDirty = true;
  34471. };
  34472. /**
  34473. * Marks the fresnel state as changed
  34474. */
  34475. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34476. this._areFresnelDirty = true;
  34477. this._isDirty = true;
  34478. };
  34479. /**
  34480. * Marks the misc state as changed
  34481. */
  34482. MaterialDefines.prototype.markAsMiscDirty = function () {
  34483. this._areMiscDirty = true;
  34484. this._isDirty = true;
  34485. };
  34486. /**
  34487. * Rebuilds the material defines
  34488. */
  34489. MaterialDefines.prototype.rebuild = function () {
  34490. if (this._keys) {
  34491. delete this._keys;
  34492. }
  34493. this._keys = [];
  34494. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34495. var key = _a[_i];
  34496. if (key[0] === "_") {
  34497. continue;
  34498. }
  34499. this._keys.push(key);
  34500. }
  34501. };
  34502. /**
  34503. * Specifies if two material defines are equal
  34504. * @param other - A material define instance to compare to
  34505. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34506. */
  34507. MaterialDefines.prototype.isEqual = function (other) {
  34508. if (this._keys.length !== other._keys.length) {
  34509. return false;
  34510. }
  34511. for (var index = 0; index < this._keys.length; index++) {
  34512. var prop = this._keys[index];
  34513. if (this[prop] !== other[prop]) {
  34514. return false;
  34515. }
  34516. }
  34517. return true;
  34518. };
  34519. /**
  34520. * Clones this instance's defines to another instance
  34521. * @param other - material defines to clone values to
  34522. */
  34523. MaterialDefines.prototype.cloneTo = function (other) {
  34524. if (this._keys.length !== other._keys.length) {
  34525. other._keys = this._keys.slice(0);
  34526. }
  34527. for (var index = 0; index < this._keys.length; index++) {
  34528. var prop = this._keys[index];
  34529. other[prop] = this[prop];
  34530. }
  34531. };
  34532. /**
  34533. * Resets the material define values
  34534. */
  34535. MaterialDefines.prototype.reset = function () {
  34536. for (var index = 0; index < this._keys.length; index++) {
  34537. var prop = this._keys[index];
  34538. var type = typeof this[prop];
  34539. switch (type) {
  34540. case "number":
  34541. this[prop] = 0;
  34542. break;
  34543. case "string":
  34544. this[prop] = "";
  34545. break;
  34546. default:
  34547. this[prop] = false;
  34548. break;
  34549. }
  34550. }
  34551. };
  34552. /**
  34553. * Converts the material define values to a string
  34554. * @returns - String of material define information
  34555. */
  34556. MaterialDefines.prototype.toString = function () {
  34557. var result = "";
  34558. for (var index = 0; index < this._keys.length; index++) {
  34559. var prop = this._keys[index];
  34560. var value = this[prop];
  34561. var type = typeof value;
  34562. switch (type) {
  34563. case "number":
  34564. case "string":
  34565. result += "#define " + prop + " " + value + "\n";
  34566. break;
  34567. default:
  34568. if (value) {
  34569. result += "#define " + prop + "\n";
  34570. }
  34571. break;
  34572. }
  34573. }
  34574. return result;
  34575. };
  34576. return MaterialDefines;
  34577. }());
  34578. BABYLON.MaterialDefines = MaterialDefines;
  34579. /**
  34580. * Base class for the main features of a material in Babylon.js
  34581. */
  34582. var Material = /** @class */ (function () {
  34583. /**
  34584. * Creates a material instance
  34585. * @param name defines the name of the material
  34586. * @param scene defines the scene to reference
  34587. * @param doNotAdd specifies if the material should be added to the scene
  34588. */
  34589. function Material(name, scene, doNotAdd) {
  34590. /**
  34591. * Specifies if the ready state should be checked on each call
  34592. */
  34593. this.checkReadyOnEveryCall = false;
  34594. /**
  34595. * Specifies if the ready state should be checked once
  34596. */
  34597. this.checkReadyOnlyOnce = false;
  34598. /**
  34599. * The state of the material
  34600. */
  34601. this.state = "";
  34602. /**
  34603. * The alpha value of the material
  34604. */
  34605. this._alpha = 1.0;
  34606. /**
  34607. * Specifies if back face culling is enabled
  34608. */
  34609. this._backFaceCulling = true;
  34610. /**
  34611. * Gets a boolean indicating that current material needs to register RTT
  34612. */
  34613. this.hasRenderTargetTextures = false;
  34614. /**
  34615. * Specifies if the material should be serialized
  34616. */
  34617. this.doNotSerialize = false;
  34618. /**
  34619. * Specifies if the effect should be stored on sub meshes
  34620. */
  34621. this.storeEffectOnSubMeshes = false;
  34622. /**
  34623. * An event triggered when the material is disposed
  34624. */
  34625. this.onDisposeObservable = new BABYLON.Observable();
  34626. /**
  34627. * Stores the value of the alpha mode
  34628. */
  34629. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34630. /**
  34631. * Stores the state of the need depth pre-pass value
  34632. */
  34633. this._needDepthPrePass = false;
  34634. /**
  34635. * Specifies if depth writing should be disabled
  34636. */
  34637. this.disableDepthWrite = false;
  34638. /**
  34639. * Specifies if depth writing should be forced
  34640. */
  34641. this.forceDepthWrite = false;
  34642. /**
  34643. * Specifies if there should be a separate pass for culling
  34644. */
  34645. this.separateCullingPass = false;
  34646. /**
  34647. * Stores the state specifing if fog should be enabled
  34648. */
  34649. this._fogEnabled = true;
  34650. /**
  34651. * Stores the size of points
  34652. */
  34653. this.pointSize = 1.0;
  34654. /**
  34655. * Stores the z offset value
  34656. */
  34657. this.zOffset = 0;
  34658. /**
  34659. * @hidden
  34660. * Specifies if the material was previously ready
  34661. */
  34662. this._wasPreviouslyReady = false;
  34663. /**
  34664. * Stores the fill mode state
  34665. */
  34666. this._fillMode = Material.TriangleFillMode;
  34667. this.name = name;
  34668. this.id = name || BABYLON.Tools.RandomId();
  34669. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34670. this.uniqueId = this._scene.getUniqueId();
  34671. if (this._scene.useRightHandedSystem) {
  34672. this.sideOrientation = Material.ClockWiseSideOrientation;
  34673. }
  34674. else {
  34675. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34676. }
  34677. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34678. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34679. if (!doNotAdd) {
  34680. this._scene.materials.push(this);
  34681. }
  34682. }
  34683. Object.defineProperty(Material, "TriangleFillMode", {
  34684. /**
  34685. * Returns the triangle fill mode
  34686. */
  34687. get: function () {
  34688. return Material._TriangleFillMode;
  34689. },
  34690. enumerable: true,
  34691. configurable: true
  34692. });
  34693. Object.defineProperty(Material, "WireFrameFillMode", {
  34694. /**
  34695. * Returns the wireframe mode
  34696. */
  34697. get: function () {
  34698. return Material._WireFrameFillMode;
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. Object.defineProperty(Material, "PointFillMode", {
  34704. /**
  34705. * Returns the point fill mode
  34706. */
  34707. get: function () {
  34708. return Material._PointFillMode;
  34709. },
  34710. enumerable: true,
  34711. configurable: true
  34712. });
  34713. Object.defineProperty(Material, "PointListDrawMode", {
  34714. /**
  34715. * Returns the point list draw mode
  34716. */
  34717. get: function () {
  34718. return Material._PointListDrawMode;
  34719. },
  34720. enumerable: true,
  34721. configurable: true
  34722. });
  34723. Object.defineProperty(Material, "LineListDrawMode", {
  34724. /**
  34725. * Returns the line list draw mode
  34726. */
  34727. get: function () {
  34728. return Material._LineListDrawMode;
  34729. },
  34730. enumerable: true,
  34731. configurable: true
  34732. });
  34733. Object.defineProperty(Material, "LineLoopDrawMode", {
  34734. /**
  34735. * Returns the line loop draw mode
  34736. */
  34737. get: function () {
  34738. return Material._LineLoopDrawMode;
  34739. },
  34740. enumerable: true,
  34741. configurable: true
  34742. });
  34743. Object.defineProperty(Material, "LineStripDrawMode", {
  34744. /**
  34745. * Returns the line strip draw mode
  34746. */
  34747. get: function () {
  34748. return Material._LineStripDrawMode;
  34749. },
  34750. enumerable: true,
  34751. configurable: true
  34752. });
  34753. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34754. /**
  34755. * Returns the triangle strip draw mode
  34756. */
  34757. get: function () {
  34758. return Material._TriangleStripDrawMode;
  34759. },
  34760. enumerable: true,
  34761. configurable: true
  34762. });
  34763. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34764. /**
  34765. * Returns the triangle fan draw mode
  34766. */
  34767. get: function () {
  34768. return Material._TriangleFanDrawMode;
  34769. },
  34770. enumerable: true,
  34771. configurable: true
  34772. });
  34773. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34774. /**
  34775. * Returns the clock-wise side orientation
  34776. */
  34777. get: function () {
  34778. return Material._ClockWiseSideOrientation;
  34779. },
  34780. enumerable: true,
  34781. configurable: true
  34782. });
  34783. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34784. /**
  34785. * Returns the counter clock-wise side orientation
  34786. */
  34787. get: function () {
  34788. return Material._CounterClockWiseSideOrientation;
  34789. },
  34790. enumerable: true,
  34791. configurable: true
  34792. });
  34793. Object.defineProperty(Material.prototype, "alpha", {
  34794. /**
  34795. * Gets the alpha value of the material
  34796. */
  34797. get: function () {
  34798. return this._alpha;
  34799. },
  34800. /**
  34801. * Sets the alpha value of the material
  34802. */
  34803. set: function (value) {
  34804. if (this._alpha === value) {
  34805. return;
  34806. }
  34807. this._alpha = value;
  34808. this.markAsDirty(Material.MiscDirtyFlag);
  34809. },
  34810. enumerable: true,
  34811. configurable: true
  34812. });
  34813. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34814. /**
  34815. * Gets the back-face culling state
  34816. */
  34817. get: function () {
  34818. return this._backFaceCulling;
  34819. },
  34820. /**
  34821. * Sets the back-face culling state
  34822. */
  34823. set: function (value) {
  34824. if (this._backFaceCulling === value) {
  34825. return;
  34826. }
  34827. this._backFaceCulling = value;
  34828. this.markAsDirty(Material.TextureDirtyFlag);
  34829. },
  34830. enumerable: true,
  34831. configurable: true
  34832. });
  34833. Object.defineProperty(Material.prototype, "onDispose", {
  34834. /**
  34835. * Called during a dispose event
  34836. */
  34837. set: function (callback) {
  34838. if (this._onDisposeObserver) {
  34839. this.onDisposeObservable.remove(this._onDisposeObserver);
  34840. }
  34841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. Object.defineProperty(Material.prototype, "onBindObservable", {
  34847. /**
  34848. * An event triggered when the material is bound
  34849. */
  34850. get: function () {
  34851. if (!this._onBindObservable) {
  34852. this._onBindObservable = new BABYLON.Observable();
  34853. }
  34854. return this._onBindObservable;
  34855. },
  34856. enumerable: true,
  34857. configurable: true
  34858. });
  34859. Object.defineProperty(Material.prototype, "onBind", {
  34860. /**
  34861. * Called during a bind event
  34862. */
  34863. set: function (callback) {
  34864. if (this._onBindObserver) {
  34865. this.onBindObservable.remove(this._onBindObserver);
  34866. }
  34867. this._onBindObserver = this.onBindObservable.add(callback);
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34873. /**
  34874. * An event triggered when the material is unbound
  34875. */
  34876. get: function () {
  34877. if (!this._onUnBindObservable) {
  34878. this._onUnBindObservable = new BABYLON.Observable();
  34879. }
  34880. return this._onUnBindObservable;
  34881. },
  34882. enumerable: true,
  34883. configurable: true
  34884. });
  34885. Object.defineProperty(Material.prototype, "alphaMode", {
  34886. /**
  34887. * Gets the value of the alpha mode
  34888. */
  34889. get: function () {
  34890. return this._alphaMode;
  34891. },
  34892. /**
  34893. * Sets the value of the alpha mode.
  34894. *
  34895. * | Value | Type | Description |
  34896. * | --- | --- | --- |
  34897. * | 0 | ALPHA_DISABLE | |
  34898. * | 1 | ALPHA_ADD | |
  34899. * | 2 | ALPHA_COMBINE | |
  34900. * | 3 | ALPHA_SUBTRACT | |
  34901. * | 4 | ALPHA_MULTIPLY | |
  34902. * | 5 | ALPHA_MAXIMIZED | |
  34903. * | 6 | ALPHA_ONEONE | |
  34904. * | 7 | ALPHA_PREMULTIPLIED | |
  34905. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34906. * | 9 | ALPHA_INTERPOLATE | |
  34907. * | 10 | ALPHA_SCREENMODE | |
  34908. *
  34909. */
  34910. set: function (value) {
  34911. if (this._alphaMode === value) {
  34912. return;
  34913. }
  34914. this._alphaMode = value;
  34915. this.markAsDirty(Material.TextureDirtyFlag);
  34916. },
  34917. enumerable: true,
  34918. configurable: true
  34919. });
  34920. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34921. /**
  34922. * Gets the depth pre-pass value
  34923. */
  34924. get: function () {
  34925. return this._needDepthPrePass;
  34926. },
  34927. /**
  34928. * Sets the need depth pre-pass value
  34929. */
  34930. set: function (value) {
  34931. if (this._needDepthPrePass === value) {
  34932. return;
  34933. }
  34934. this._needDepthPrePass = value;
  34935. if (this._needDepthPrePass) {
  34936. this.checkReadyOnEveryCall = true;
  34937. }
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(Material.prototype, "fogEnabled", {
  34943. /**
  34944. * Gets the value of the fog enabled state
  34945. */
  34946. get: function () {
  34947. return this._fogEnabled;
  34948. },
  34949. /**
  34950. * Sets the state for enabling fog
  34951. */
  34952. set: function (value) {
  34953. if (this._fogEnabled === value) {
  34954. return;
  34955. }
  34956. this._fogEnabled = value;
  34957. this.markAsDirty(Material.MiscDirtyFlag);
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Object.defineProperty(Material.prototype, "wireframe", {
  34963. /**
  34964. * Gets a value specifying if wireframe mode is enabled
  34965. */
  34966. get: function () {
  34967. switch (this._fillMode) {
  34968. case Material.WireFrameFillMode:
  34969. case Material.LineListDrawMode:
  34970. case Material.LineLoopDrawMode:
  34971. case Material.LineStripDrawMode:
  34972. return true;
  34973. }
  34974. return this._scene.forceWireframe;
  34975. },
  34976. /**
  34977. * Sets the state of wireframe mode
  34978. */
  34979. set: function (value) {
  34980. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. Object.defineProperty(Material.prototype, "pointsCloud", {
  34986. /**
  34987. * Gets the value specifying if point clouds are enabled
  34988. */
  34989. get: function () {
  34990. switch (this._fillMode) {
  34991. case Material.PointFillMode:
  34992. case Material.PointListDrawMode:
  34993. return true;
  34994. }
  34995. return this._scene.forcePointsCloud;
  34996. },
  34997. /**
  34998. * Sets the state of point cloud mode
  34999. */
  35000. set: function (value) {
  35001. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35002. },
  35003. enumerable: true,
  35004. configurable: true
  35005. });
  35006. Object.defineProperty(Material.prototype, "fillMode", {
  35007. /**
  35008. * Gets the material fill mode
  35009. */
  35010. get: function () {
  35011. return this._fillMode;
  35012. },
  35013. /**
  35014. * Sets the material fill mode
  35015. */
  35016. set: function (value) {
  35017. if (this._fillMode === value) {
  35018. return;
  35019. }
  35020. this._fillMode = value;
  35021. this.markAsDirty(Material.MiscDirtyFlag);
  35022. },
  35023. enumerable: true,
  35024. configurable: true
  35025. });
  35026. /**
  35027. * Returns a string representation of the current material
  35028. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35029. * @returns a string with material information
  35030. */
  35031. Material.prototype.toString = function (fullDetails) {
  35032. var ret = "Name: " + this.name;
  35033. if (fullDetails) {
  35034. }
  35035. return ret;
  35036. };
  35037. /**
  35038. * Gets the class name of the material
  35039. * @returns a string with the class name of the material
  35040. */
  35041. Material.prototype.getClassName = function () {
  35042. return "Material";
  35043. };
  35044. Object.defineProperty(Material.prototype, "isFrozen", {
  35045. /**
  35046. * Specifies if updates for the material been locked
  35047. */
  35048. get: function () {
  35049. return this.checkReadyOnlyOnce;
  35050. },
  35051. enumerable: true,
  35052. configurable: true
  35053. });
  35054. /**
  35055. * Locks updates for the material
  35056. */
  35057. Material.prototype.freeze = function () {
  35058. this.checkReadyOnlyOnce = true;
  35059. };
  35060. /**
  35061. * Unlocks updates for the material
  35062. */
  35063. Material.prototype.unfreeze = function () {
  35064. this.checkReadyOnlyOnce = false;
  35065. };
  35066. /**
  35067. * Specifies if the material is ready to be used
  35068. * @param mesh defines the mesh to check
  35069. * @param useInstances specifies if instances should be used
  35070. * @returns a boolean indicating if the material is ready to be used
  35071. */
  35072. Material.prototype.isReady = function (mesh, useInstances) {
  35073. return true;
  35074. };
  35075. /**
  35076. * Specifies that the submesh is ready to be used
  35077. * @param mesh defines the mesh to check
  35078. * @param subMesh defines which submesh to check
  35079. * @param useInstances specifies that instances should be used
  35080. * @returns a boolean indicating that the submesh is ready or not
  35081. */
  35082. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35083. return false;
  35084. };
  35085. /**
  35086. * Returns the material effect
  35087. * @returns the effect associated with the material
  35088. */
  35089. Material.prototype.getEffect = function () {
  35090. return this._effect;
  35091. };
  35092. /**
  35093. * Returns the current scene
  35094. * @returns a Scene
  35095. */
  35096. Material.prototype.getScene = function () {
  35097. return this._scene;
  35098. };
  35099. /**
  35100. * Specifies if the material will require alpha blending
  35101. * @returns a boolean specifying if alpha blending is needed
  35102. */
  35103. Material.prototype.needAlphaBlending = function () {
  35104. return (this.alpha < 1.0);
  35105. };
  35106. /**
  35107. * Specifies if the mesh will require alpha blending
  35108. * @param mesh defines the mesh to check
  35109. * @returns a boolean specifying if alpha blending is needed for the mesh
  35110. */
  35111. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35112. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35113. };
  35114. /**
  35115. * Specifies if this material should be rendered in alpha test mode
  35116. * @returns a boolean specifying if an alpha test is needed.
  35117. */
  35118. Material.prototype.needAlphaTesting = function () {
  35119. return false;
  35120. };
  35121. /**
  35122. * Gets the texture used for the alpha test
  35123. * @returns the texture to use for alpha testing
  35124. */
  35125. Material.prototype.getAlphaTestTexture = function () {
  35126. return null;
  35127. };
  35128. /**
  35129. * Marks the material to indicate that it needs to be re-calculated
  35130. */
  35131. Material.prototype.markDirty = function () {
  35132. this._wasPreviouslyReady = false;
  35133. };
  35134. /** @hidden */
  35135. Material.prototype._preBind = function (effect, overrideOrientation) {
  35136. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35137. var engine = this._scene.getEngine();
  35138. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35139. var reverse = orientation === Material.ClockWiseSideOrientation;
  35140. engine.enableEffect(effect ? effect : this._effect);
  35141. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35142. return reverse;
  35143. };
  35144. /**
  35145. * Binds the material to the mesh
  35146. * @param world defines the world transformation matrix
  35147. * @param mesh defines the mesh to bind the material to
  35148. */
  35149. Material.prototype.bind = function (world, mesh) {
  35150. };
  35151. /**
  35152. * Binds the submesh to the material
  35153. * @param world defines the world transformation matrix
  35154. * @param mesh defines the mesh containing the submesh
  35155. * @param subMesh defines the submesh to bind the material to
  35156. */
  35157. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35158. };
  35159. /**
  35160. * Binds the world matrix to the material
  35161. * @param world defines the world transformation matrix
  35162. */
  35163. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35164. };
  35165. /**
  35166. * Binds the scene's uniform buffer to the effect.
  35167. * @param effect defines the effect to bind to the scene uniform buffer
  35168. * @param sceneUbo defines the uniform buffer storing scene data
  35169. */
  35170. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35171. sceneUbo.bindToEffect(effect, "Scene");
  35172. };
  35173. /**
  35174. * Binds the view matrix to the effect
  35175. * @param effect defines the effect to bind the view matrix to
  35176. */
  35177. Material.prototype.bindView = function (effect) {
  35178. if (!this._useUBO) {
  35179. effect.setMatrix("view", this.getScene().getViewMatrix());
  35180. }
  35181. else {
  35182. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35183. }
  35184. };
  35185. /**
  35186. * Binds the view projection matrix to the effect
  35187. * @param effect defines the effect to bind the view projection matrix to
  35188. */
  35189. Material.prototype.bindViewProjection = function (effect) {
  35190. if (!this._useUBO) {
  35191. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35192. }
  35193. else {
  35194. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35195. }
  35196. };
  35197. /**
  35198. * Specifies if material alpha testing should be turned on for the mesh
  35199. * @param mesh defines the mesh to check
  35200. */
  35201. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35202. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35203. };
  35204. /**
  35205. * Processes to execute after binding the material to a mesh
  35206. * @param mesh defines the rendered mesh
  35207. */
  35208. Material.prototype._afterBind = function (mesh) {
  35209. this._scene._cachedMaterial = this;
  35210. if (mesh) {
  35211. this._scene._cachedVisibility = mesh.visibility;
  35212. }
  35213. else {
  35214. this._scene._cachedVisibility = 1;
  35215. }
  35216. if (this._onBindObservable && mesh) {
  35217. this._onBindObservable.notifyObservers(mesh);
  35218. }
  35219. if (this.disableDepthWrite) {
  35220. var engine = this._scene.getEngine();
  35221. this._cachedDepthWriteState = engine.getDepthWrite();
  35222. engine.setDepthWrite(false);
  35223. }
  35224. };
  35225. /**
  35226. * Unbinds the material from the mesh
  35227. */
  35228. Material.prototype.unbind = function () {
  35229. if (this._onUnBindObservable) {
  35230. this._onUnBindObservable.notifyObservers(this);
  35231. }
  35232. if (this.disableDepthWrite) {
  35233. var engine = this._scene.getEngine();
  35234. engine.setDepthWrite(this._cachedDepthWriteState);
  35235. }
  35236. };
  35237. /**
  35238. * Gets the active textures from the material
  35239. * @returns an array of textures
  35240. */
  35241. Material.prototype.getActiveTextures = function () {
  35242. return [];
  35243. };
  35244. /**
  35245. * Specifies if the material uses a texture
  35246. * @param texture defines the texture to check against the material
  35247. * @returns a boolean specifying if the material uses the texture
  35248. */
  35249. Material.prototype.hasTexture = function (texture) {
  35250. return false;
  35251. };
  35252. /**
  35253. * Makes a duplicate of the material, and gives it a new name
  35254. * @param name defines the new name for the duplicated material
  35255. * @returns the cloned material
  35256. */
  35257. Material.prototype.clone = function (name) {
  35258. return null;
  35259. };
  35260. /**
  35261. * Gets the meshes bound to the material
  35262. * @returns an array of meshes bound to the material
  35263. */
  35264. Material.prototype.getBindedMeshes = function () {
  35265. var result = new Array();
  35266. for (var index = 0; index < this._scene.meshes.length; index++) {
  35267. var mesh = this._scene.meshes[index];
  35268. if (mesh.material === this) {
  35269. result.push(mesh);
  35270. }
  35271. }
  35272. return result;
  35273. };
  35274. /**
  35275. * Force shader compilation
  35276. * @param mesh defines the mesh associated with this material
  35277. * @param onCompiled defines a function to execute once the material is compiled
  35278. * @param options defines the options to configure the compilation
  35279. */
  35280. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35281. var _this = this;
  35282. var localOptions = __assign({ clipPlane: false }, options);
  35283. var subMesh = new BABYLON.BaseSubMesh();
  35284. var scene = this.getScene();
  35285. var checkReady = function () {
  35286. if (!_this._scene || !_this._scene.getEngine()) {
  35287. return;
  35288. }
  35289. if (subMesh._materialDefines) {
  35290. subMesh._materialDefines._renderId = -1;
  35291. }
  35292. var clipPlaneState = scene.clipPlane;
  35293. if (localOptions.clipPlane) {
  35294. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35295. }
  35296. if (_this.storeEffectOnSubMeshes) {
  35297. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35298. if (onCompiled) {
  35299. onCompiled(_this);
  35300. }
  35301. }
  35302. else {
  35303. setTimeout(checkReady, 16);
  35304. }
  35305. }
  35306. else {
  35307. if (_this.isReady(mesh)) {
  35308. if (onCompiled) {
  35309. onCompiled(_this);
  35310. }
  35311. }
  35312. else {
  35313. setTimeout(checkReady, 16);
  35314. }
  35315. }
  35316. if (localOptions.clipPlane) {
  35317. scene.clipPlane = clipPlaneState;
  35318. }
  35319. };
  35320. checkReady();
  35321. };
  35322. /**
  35323. * Force shader compilation
  35324. * @param mesh defines the mesh that will use this material
  35325. * @param options defines additional options for compiling the shaders
  35326. * @returns a promise that resolves when the compilation completes
  35327. */
  35328. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35329. var _this = this;
  35330. return new Promise(function (resolve) {
  35331. _this.forceCompilation(mesh, function () {
  35332. resolve();
  35333. }, options);
  35334. });
  35335. };
  35336. /**
  35337. * Marks a define in the material to indicate that it needs to be re-computed
  35338. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35339. */
  35340. Material.prototype.markAsDirty = function (flag) {
  35341. if (flag & Material.TextureDirtyFlag) {
  35342. this._markAllSubMeshesAsTexturesDirty();
  35343. }
  35344. if (flag & Material.LightDirtyFlag) {
  35345. this._markAllSubMeshesAsLightsDirty();
  35346. }
  35347. if (flag & Material.FresnelDirtyFlag) {
  35348. this._markAllSubMeshesAsFresnelDirty();
  35349. }
  35350. if (flag & Material.AttributesDirtyFlag) {
  35351. this._markAllSubMeshesAsAttributesDirty();
  35352. }
  35353. if (flag & Material.MiscDirtyFlag) {
  35354. this._markAllSubMeshesAsMiscDirty();
  35355. }
  35356. this.getScene().resetCachedMaterial();
  35357. };
  35358. /**
  35359. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35360. * @param func defines a function which checks material defines against the submeshes
  35361. */
  35362. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35363. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35364. var mesh = _a[_i];
  35365. if (!mesh.subMeshes) {
  35366. continue;
  35367. }
  35368. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35369. var subMesh = _c[_b];
  35370. if (subMesh.getMaterial() !== this) {
  35371. continue;
  35372. }
  35373. if (!subMesh._materialDefines) {
  35374. continue;
  35375. }
  35376. func(subMesh._materialDefines);
  35377. }
  35378. }
  35379. };
  35380. /**
  35381. * Indicates that image processing needs to be re-calculated for all submeshes
  35382. */
  35383. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35384. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35385. };
  35386. /**
  35387. * Indicates that textures need to be re-calculated for all submeshes
  35388. */
  35389. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35390. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35391. };
  35392. /**
  35393. * Indicates that fresnel needs to be re-calculated for all submeshes
  35394. */
  35395. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35396. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35397. };
  35398. /**
  35399. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35400. */
  35401. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35402. this._markAllSubMeshesAsDirty(function (defines) {
  35403. defines.markAsFresnelDirty();
  35404. defines.markAsMiscDirty();
  35405. });
  35406. };
  35407. /**
  35408. * Indicates that lights need to be re-calculated for all submeshes
  35409. */
  35410. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35411. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35412. };
  35413. /**
  35414. * Indicates that attributes need to be re-calculated for all submeshes
  35415. */
  35416. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35417. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35418. };
  35419. /**
  35420. * Indicates that misc needs to be re-calculated for all submeshes
  35421. */
  35422. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35423. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35424. };
  35425. /**
  35426. * Indicates that textures and misc need to be re-calculated for all submeshes
  35427. */
  35428. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35429. this._markAllSubMeshesAsDirty(function (defines) {
  35430. defines.markAsTexturesDirty();
  35431. defines.markAsMiscDirty();
  35432. });
  35433. };
  35434. /**
  35435. * Disposes the material
  35436. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35437. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35438. */
  35439. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35440. // Animations
  35441. this.getScene().stopAnimation(this);
  35442. this.getScene().freeProcessedMaterials();
  35443. // Remove from scene
  35444. var index = this._scene.materials.indexOf(this);
  35445. if (index >= 0) {
  35446. this._scene.materials.splice(index, 1);
  35447. }
  35448. // Remove from meshes
  35449. for (index = 0; index < this._scene.meshes.length; index++) {
  35450. var mesh = this._scene.meshes[index];
  35451. if (mesh.material === this) {
  35452. mesh.material = null;
  35453. if (mesh.geometry) {
  35454. var geometry = (mesh.geometry);
  35455. if (this.storeEffectOnSubMeshes) {
  35456. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35457. var subMesh = _a[_i];
  35458. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35459. if (forceDisposeEffect && subMesh._materialEffect) {
  35460. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35461. }
  35462. }
  35463. }
  35464. else {
  35465. geometry._releaseVertexArrayObject(this._effect);
  35466. }
  35467. }
  35468. }
  35469. }
  35470. this._uniformBuffer.dispose();
  35471. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35472. if (forceDisposeEffect && this._effect) {
  35473. if (!this.storeEffectOnSubMeshes) {
  35474. this._scene.getEngine()._releaseEffect(this._effect);
  35475. }
  35476. this._effect = null;
  35477. }
  35478. // Callback
  35479. this.onDisposeObservable.notifyObservers(this);
  35480. this.onDisposeObservable.clear();
  35481. if (this._onBindObservable) {
  35482. this._onBindObservable.clear();
  35483. }
  35484. if (this._onUnBindObservable) {
  35485. this._onUnBindObservable.clear();
  35486. }
  35487. };
  35488. /**
  35489. * Serializes this material
  35490. * @returns the serialized material object
  35491. */
  35492. Material.prototype.serialize = function () {
  35493. return BABYLON.SerializationHelper.Serialize(this);
  35494. };
  35495. /**
  35496. * Creates a MultiMaterial from parsed MultiMaterial data.
  35497. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35498. * @param scene defines the hosting scene
  35499. * @returns a new MultiMaterial
  35500. */
  35501. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35502. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35503. multiMaterial.id = parsedMultiMaterial.id;
  35504. if (BABYLON.Tags) {
  35505. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35506. }
  35507. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35508. var subMatId = parsedMultiMaterial.materials[matIndex];
  35509. if (subMatId) {
  35510. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35511. }
  35512. else {
  35513. multiMaterial.subMaterials.push(null);
  35514. }
  35515. }
  35516. return multiMaterial;
  35517. };
  35518. /**
  35519. * Creates a material from parsed material data
  35520. * @param parsedMaterial defines parsed material data
  35521. * @param scene defines the hosting scene
  35522. * @param rootUrl defines the root URL to use to load textures
  35523. * @returns a new material
  35524. */
  35525. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35526. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35527. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35528. }
  35529. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35530. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35531. if (!BABYLON.LegacyPBRMaterial) {
  35532. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35533. return;
  35534. }
  35535. }
  35536. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35537. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35538. };
  35539. // Triangle views
  35540. Material._TriangleFillMode = 0;
  35541. Material._WireFrameFillMode = 1;
  35542. Material._PointFillMode = 2;
  35543. // Draw modes
  35544. Material._PointListDrawMode = 3;
  35545. Material._LineListDrawMode = 4;
  35546. Material._LineLoopDrawMode = 5;
  35547. Material._LineStripDrawMode = 6;
  35548. Material._TriangleStripDrawMode = 7;
  35549. Material._TriangleFanDrawMode = 8;
  35550. /**
  35551. * Stores the clock-wise side orientation
  35552. */
  35553. Material._ClockWiseSideOrientation = 0;
  35554. /**
  35555. * Stores the counter clock-wise side orientation
  35556. */
  35557. Material._CounterClockWiseSideOrientation = 1;
  35558. /**
  35559. * The dirty texture flag value
  35560. */
  35561. Material.TextureDirtyFlag = 1;
  35562. /**
  35563. * The dirty light flag value
  35564. */
  35565. Material.LightDirtyFlag = 2;
  35566. /**
  35567. * The dirty fresnel flag value
  35568. */
  35569. Material.FresnelDirtyFlag = 4;
  35570. /**
  35571. * The dirty attribute flag value
  35572. */
  35573. Material.AttributesDirtyFlag = 8;
  35574. /**
  35575. * The dirty misc flag value
  35576. */
  35577. Material.MiscDirtyFlag = 16;
  35578. /**
  35579. * The all dirty flag value
  35580. */
  35581. Material.AllDirtyFlag = 31;
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], Material.prototype, "id", void 0);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], Material.prototype, "uniqueId", void 0);
  35588. __decorate([
  35589. BABYLON.serialize()
  35590. ], Material.prototype, "name", void 0);
  35591. __decorate([
  35592. BABYLON.serialize()
  35593. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35594. __decorate([
  35595. BABYLON.serialize()
  35596. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35597. __decorate([
  35598. BABYLON.serialize()
  35599. ], Material.prototype, "state", void 0);
  35600. __decorate([
  35601. BABYLON.serialize("alpha")
  35602. ], Material.prototype, "_alpha", void 0);
  35603. __decorate([
  35604. BABYLON.serialize("backFaceCulling")
  35605. ], Material.prototype, "_backFaceCulling", void 0);
  35606. __decorate([
  35607. BABYLON.serialize()
  35608. ], Material.prototype, "sideOrientation", void 0);
  35609. __decorate([
  35610. BABYLON.serialize("alphaMode")
  35611. ], Material.prototype, "_alphaMode", void 0);
  35612. __decorate([
  35613. BABYLON.serialize()
  35614. ], Material.prototype, "_needDepthPrePass", void 0);
  35615. __decorate([
  35616. BABYLON.serialize()
  35617. ], Material.prototype, "disableDepthWrite", void 0);
  35618. __decorate([
  35619. BABYLON.serialize()
  35620. ], Material.prototype, "forceDepthWrite", void 0);
  35621. __decorate([
  35622. BABYLON.serialize()
  35623. ], Material.prototype, "separateCullingPass", void 0);
  35624. __decorate([
  35625. BABYLON.serialize("fogEnabled")
  35626. ], Material.prototype, "_fogEnabled", void 0);
  35627. __decorate([
  35628. BABYLON.serialize()
  35629. ], Material.prototype, "pointSize", void 0);
  35630. __decorate([
  35631. BABYLON.serialize()
  35632. ], Material.prototype, "zOffset", void 0);
  35633. __decorate([
  35634. BABYLON.serialize()
  35635. ], Material.prototype, "wireframe", null);
  35636. __decorate([
  35637. BABYLON.serialize()
  35638. ], Material.prototype, "pointsCloud", null);
  35639. __decorate([
  35640. BABYLON.serialize()
  35641. ], Material.prototype, "fillMode", null);
  35642. return Material;
  35643. }());
  35644. BABYLON.Material = Material;
  35645. })(BABYLON || (BABYLON = {}));
  35646. //# sourceMappingURL=babylon.material.js.map
  35647. var BABYLON;
  35648. (function (BABYLON) {
  35649. var UniformBuffer = /** @class */ (function () {
  35650. /**
  35651. * Uniform buffer objects.
  35652. *
  35653. * Handles blocks of uniform on the GPU.
  35654. *
  35655. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35656. *
  35657. * For more information, please refer to :
  35658. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35659. */
  35660. function UniformBuffer(engine, data, dynamic) {
  35661. this._engine = engine;
  35662. this._noUBO = !engine.supportsUniformBuffers;
  35663. this._dynamic = dynamic;
  35664. this._data = data || [];
  35665. this._uniformLocations = {};
  35666. this._uniformSizes = {};
  35667. this._uniformLocationPointer = 0;
  35668. this._needSync = false;
  35669. if (this._noUBO) {
  35670. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35671. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35672. this.updateFloat = this._updateFloatForEffect;
  35673. this.updateFloat2 = this._updateFloat2ForEffect;
  35674. this.updateFloat3 = this._updateFloat3ForEffect;
  35675. this.updateFloat4 = this._updateFloat4ForEffect;
  35676. this.updateMatrix = this._updateMatrixForEffect;
  35677. this.updateVector3 = this._updateVector3ForEffect;
  35678. this.updateVector4 = this._updateVector4ForEffect;
  35679. this.updateColor3 = this._updateColor3ForEffect;
  35680. this.updateColor4 = this._updateColor4ForEffect;
  35681. }
  35682. else {
  35683. this._engine._uniformBuffers.push(this);
  35684. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35685. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35686. this.updateFloat = this._updateFloatForUniform;
  35687. this.updateFloat2 = this._updateFloat2ForUniform;
  35688. this.updateFloat3 = this._updateFloat3ForUniform;
  35689. this.updateFloat4 = this._updateFloat4ForUniform;
  35690. this.updateMatrix = this._updateMatrixForUniform;
  35691. this.updateVector3 = this._updateVector3ForUniform;
  35692. this.updateVector4 = this._updateVector4ForUniform;
  35693. this.updateColor3 = this._updateColor3ForUniform;
  35694. this.updateColor4 = this._updateColor4ForUniform;
  35695. }
  35696. }
  35697. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35698. // Properties
  35699. /**
  35700. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35701. * or just falling back on setUniformXXX calls.
  35702. */
  35703. get: function () {
  35704. return !this._noUBO;
  35705. },
  35706. enumerable: true,
  35707. configurable: true
  35708. });
  35709. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35710. /**
  35711. * Indicates if the WebGL underlying uniform buffer is in sync
  35712. * with the javascript cache data.
  35713. */
  35714. get: function () {
  35715. return !this._needSync;
  35716. },
  35717. enumerable: true,
  35718. configurable: true
  35719. });
  35720. /**
  35721. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35722. * Also, a dynamic UniformBuffer will disable cache verification and always
  35723. * update the underlying WebGL uniform buffer to the GPU.
  35724. */
  35725. UniformBuffer.prototype.isDynamic = function () {
  35726. return this._dynamic !== undefined;
  35727. };
  35728. /**
  35729. * The data cache on JS side.
  35730. */
  35731. UniformBuffer.prototype.getData = function () {
  35732. return this._bufferData;
  35733. };
  35734. /**
  35735. * The underlying WebGL Uniform buffer.
  35736. */
  35737. UniformBuffer.prototype.getBuffer = function () {
  35738. return this._buffer;
  35739. };
  35740. /**
  35741. * std140 layout specifies how to align data within an UBO structure.
  35742. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35743. * for specs.
  35744. */
  35745. UniformBuffer.prototype._fillAlignment = function (size) {
  35746. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35747. // and 4x4 matrices
  35748. // TODO : change if other types are used
  35749. var alignment;
  35750. if (size <= 2) {
  35751. alignment = size;
  35752. }
  35753. else {
  35754. alignment = 4;
  35755. }
  35756. if ((this._uniformLocationPointer % alignment) !== 0) {
  35757. var oldPointer = this._uniformLocationPointer;
  35758. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35759. var diff = this._uniformLocationPointer - oldPointer;
  35760. for (var i = 0; i < diff; i++) {
  35761. this._data.push(0);
  35762. }
  35763. }
  35764. };
  35765. /**
  35766. * Adds an uniform in the buffer.
  35767. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35768. * for the layout to be correct !
  35769. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35770. * @param {number|number[]} size Data size, or data directly.
  35771. */
  35772. UniformBuffer.prototype.addUniform = function (name, size) {
  35773. if (this._noUBO) {
  35774. return;
  35775. }
  35776. if (this._uniformLocations[name] !== undefined) {
  35777. // Already existing uniform
  35778. return;
  35779. }
  35780. // This function must be called in the order of the shader layout !
  35781. // size can be the size of the uniform, or data directly
  35782. var data;
  35783. if (size instanceof Array) {
  35784. data = size;
  35785. size = data.length;
  35786. }
  35787. else {
  35788. size = size;
  35789. data = [];
  35790. // Fill with zeros
  35791. for (var i = 0; i < size; i++) {
  35792. data.push(0);
  35793. }
  35794. }
  35795. this._fillAlignment(size);
  35796. this._uniformSizes[name] = size;
  35797. this._uniformLocations[name] = this._uniformLocationPointer;
  35798. this._uniformLocationPointer += size;
  35799. for (var i = 0; i < size; i++) {
  35800. this._data.push(data[i]);
  35801. }
  35802. this._needSync = true;
  35803. };
  35804. /**
  35805. * Wrapper for addUniform.
  35806. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35807. * @param {Matrix} mat A 4x4 matrix.
  35808. */
  35809. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35810. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35811. };
  35812. /**
  35813. * Wrapper for addUniform.
  35814. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35815. * @param {number} x
  35816. * @param {number} y
  35817. */
  35818. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35819. var temp = [x, y];
  35820. this.addUniform(name, temp);
  35821. };
  35822. /**
  35823. * Wrapper for addUniform.
  35824. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35825. * @param {number} x
  35826. * @param {number} y
  35827. * @param {number} z
  35828. */
  35829. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35830. var temp = [x, y, z];
  35831. this.addUniform(name, temp);
  35832. };
  35833. /**
  35834. * Wrapper for addUniform.
  35835. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35836. * @param {Color3} color
  35837. */
  35838. UniformBuffer.prototype.addColor3 = function (name, color) {
  35839. var temp = new Array();
  35840. color.toArray(temp);
  35841. this.addUniform(name, temp);
  35842. };
  35843. /**
  35844. * Wrapper for addUniform.
  35845. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35846. * @param {Color3} color
  35847. * @param {number} alpha
  35848. */
  35849. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35850. var temp = new Array();
  35851. color.toArray(temp);
  35852. temp.push(alpha);
  35853. this.addUniform(name, temp);
  35854. };
  35855. /**
  35856. * Wrapper for addUniform.
  35857. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35858. * @param {Vector3} vector
  35859. */
  35860. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35861. var temp = new Array();
  35862. vector.toArray(temp);
  35863. this.addUniform(name, temp);
  35864. };
  35865. /**
  35866. * Wrapper for addUniform.
  35867. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35868. */
  35869. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35870. this.addUniform(name, 12);
  35871. };
  35872. /**
  35873. * Wrapper for addUniform.
  35874. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35875. */
  35876. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35877. this.addUniform(name, 8);
  35878. };
  35879. /**
  35880. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35881. */
  35882. UniformBuffer.prototype.create = function () {
  35883. if (this._noUBO) {
  35884. return;
  35885. }
  35886. if (this._buffer) {
  35887. return; // nothing to do
  35888. }
  35889. // See spec, alignment must be filled as a vec4
  35890. this._fillAlignment(4);
  35891. this._bufferData = new Float32Array(this._data);
  35892. this._rebuild();
  35893. this._needSync = true;
  35894. };
  35895. /** @hidden */
  35896. UniformBuffer.prototype._rebuild = function () {
  35897. if (this._noUBO) {
  35898. return;
  35899. }
  35900. if (this._dynamic) {
  35901. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35902. }
  35903. else {
  35904. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35905. }
  35906. };
  35907. /**
  35908. * Updates the WebGL Uniform Buffer on the GPU.
  35909. * If the `dynamic` flag is set to true, no cache comparison is done.
  35910. * Otherwise, the buffer will be updated only if the cache differs.
  35911. */
  35912. UniformBuffer.prototype.update = function () {
  35913. if (!this._buffer) {
  35914. this.create();
  35915. return;
  35916. }
  35917. if (!this._dynamic && !this._needSync) {
  35918. return;
  35919. }
  35920. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35921. this._needSync = false;
  35922. };
  35923. /**
  35924. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35925. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35926. * @param {number[]|Float32Array} data Flattened data
  35927. * @param {number} size Size of the data.
  35928. */
  35929. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35930. var location = this._uniformLocations[uniformName];
  35931. if (location === undefined) {
  35932. if (this._buffer) {
  35933. // Cannot add an uniform if the buffer is already created
  35934. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35935. return;
  35936. }
  35937. this.addUniform(uniformName, size);
  35938. location = this._uniformLocations[uniformName];
  35939. }
  35940. if (!this._buffer) {
  35941. this.create();
  35942. }
  35943. if (!this._dynamic) {
  35944. // Cache for static uniform buffers
  35945. var changed = false;
  35946. for (var i = 0; i < size; i++) {
  35947. if (this._bufferData[location + i] !== data[i]) {
  35948. changed = true;
  35949. this._bufferData[location + i] = data[i];
  35950. }
  35951. }
  35952. this._needSync = this._needSync || changed;
  35953. }
  35954. else {
  35955. // No cache for dynamic
  35956. for (var i = 0; i < size; i++) {
  35957. this._bufferData[location + i] = data[i];
  35958. }
  35959. }
  35960. };
  35961. // Update methods
  35962. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35963. // To match std140, matrix must be realigned
  35964. for (var i = 0; i < 3; i++) {
  35965. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35966. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35967. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35968. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35969. }
  35970. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35971. };
  35972. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35973. this._currentEffect.setMatrix3x3(name, matrix);
  35974. };
  35975. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35976. this._currentEffect.setMatrix2x2(name, matrix);
  35977. };
  35978. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35979. // To match std140, matrix must be realigned
  35980. for (var i = 0; i < 2; i++) {
  35981. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35982. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35983. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35984. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35985. }
  35986. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35987. };
  35988. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35989. this._currentEffect.setFloat(name, x);
  35990. };
  35991. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35992. UniformBuffer._tempBuffer[0] = x;
  35993. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35994. };
  35995. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35996. if (suffix === void 0) { suffix = ""; }
  35997. this._currentEffect.setFloat2(name + suffix, x, y);
  35998. };
  35999. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36000. if (suffix === void 0) { suffix = ""; }
  36001. UniformBuffer._tempBuffer[0] = x;
  36002. UniformBuffer._tempBuffer[1] = y;
  36003. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36004. };
  36005. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36006. if (suffix === void 0) { suffix = ""; }
  36007. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36008. };
  36009. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36010. if (suffix === void 0) { suffix = ""; }
  36011. UniformBuffer._tempBuffer[0] = x;
  36012. UniformBuffer._tempBuffer[1] = y;
  36013. UniformBuffer._tempBuffer[2] = z;
  36014. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36015. };
  36016. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36017. if (suffix === void 0) { suffix = ""; }
  36018. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36019. };
  36020. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36021. if (suffix === void 0) { suffix = ""; }
  36022. UniformBuffer._tempBuffer[0] = x;
  36023. UniformBuffer._tempBuffer[1] = y;
  36024. UniformBuffer._tempBuffer[2] = z;
  36025. UniformBuffer._tempBuffer[3] = w;
  36026. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36027. };
  36028. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36029. this._currentEffect.setMatrix(name, mat);
  36030. };
  36031. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36032. this.updateUniform(name, mat.toArray(), 16);
  36033. };
  36034. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36035. this._currentEffect.setVector3(name, vector);
  36036. };
  36037. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36038. vector.toArray(UniformBuffer._tempBuffer);
  36039. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36040. };
  36041. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36042. this._currentEffect.setVector4(name, vector);
  36043. };
  36044. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36045. vector.toArray(UniformBuffer._tempBuffer);
  36046. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36047. };
  36048. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36049. if (suffix === void 0) { suffix = ""; }
  36050. this._currentEffect.setColor3(name + suffix, color);
  36051. };
  36052. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36053. if (suffix === void 0) { suffix = ""; }
  36054. color.toArray(UniformBuffer._tempBuffer);
  36055. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36056. };
  36057. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36058. if (suffix === void 0) { suffix = ""; }
  36059. this._currentEffect.setColor4(name + suffix, color, alpha);
  36060. };
  36061. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36062. if (suffix === void 0) { suffix = ""; }
  36063. color.toArray(UniformBuffer._tempBuffer);
  36064. UniformBuffer._tempBuffer[3] = alpha;
  36065. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36066. };
  36067. /**
  36068. * Sets a sampler uniform on the effect.
  36069. * @param {string} name Name of the sampler.
  36070. * @param {Texture} texture
  36071. */
  36072. UniformBuffer.prototype.setTexture = function (name, texture) {
  36073. this._currentEffect.setTexture(name, texture);
  36074. };
  36075. /**
  36076. * Directly updates the value of the uniform in the cache AND on the GPU.
  36077. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36078. * @param {number[]|Float32Array} data Flattened data
  36079. */
  36080. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36081. this.updateUniform(uniformName, data, data.length);
  36082. this.update();
  36083. };
  36084. /**
  36085. * Binds this uniform buffer to an effect.
  36086. * @param {Effect} effect
  36087. * @param {string} name Name of the uniform block in the shader.
  36088. */
  36089. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36090. this._currentEffect = effect;
  36091. if (this._noUBO || !this._buffer) {
  36092. return;
  36093. }
  36094. effect.bindUniformBuffer(this._buffer, name);
  36095. };
  36096. /**
  36097. * Disposes the uniform buffer.
  36098. */
  36099. UniformBuffer.prototype.dispose = function () {
  36100. if (this._noUBO) {
  36101. return;
  36102. }
  36103. var index = this._engine._uniformBuffers.indexOf(this);
  36104. if (index !== -1) {
  36105. this._engine._uniformBuffers.splice(index, 1);
  36106. }
  36107. if (!this._buffer) {
  36108. return;
  36109. }
  36110. if (this._engine._releaseBuffer(this._buffer)) {
  36111. this._buffer = null;
  36112. }
  36113. };
  36114. // Pool for avoiding memory leaks
  36115. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36116. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36117. return UniformBuffer;
  36118. }());
  36119. BABYLON.UniformBuffer = UniformBuffer;
  36120. })(BABYLON || (BABYLON = {}));
  36121. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36122. var BABYLON;
  36123. (function (BABYLON) {
  36124. /**
  36125. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36126. */
  36127. var VertexData = /** @class */ (function () {
  36128. function VertexData() {
  36129. }
  36130. /**
  36131. * Uses the passed data array to set the set the values for the specified kind of data
  36132. * @param data a linear array of floating numbers
  36133. * @param kind the type of data that is being set, eg positions, colors etc
  36134. */
  36135. VertexData.prototype.set = function (data, kind) {
  36136. switch (kind) {
  36137. case BABYLON.VertexBuffer.PositionKind:
  36138. this.positions = data;
  36139. break;
  36140. case BABYLON.VertexBuffer.NormalKind:
  36141. this.normals = data;
  36142. break;
  36143. case BABYLON.VertexBuffer.TangentKind:
  36144. this.tangents = data;
  36145. break;
  36146. case BABYLON.VertexBuffer.UVKind:
  36147. this.uvs = data;
  36148. break;
  36149. case BABYLON.VertexBuffer.UV2Kind:
  36150. this.uvs2 = data;
  36151. break;
  36152. case BABYLON.VertexBuffer.UV3Kind:
  36153. this.uvs3 = data;
  36154. break;
  36155. case BABYLON.VertexBuffer.UV4Kind:
  36156. this.uvs4 = data;
  36157. break;
  36158. case BABYLON.VertexBuffer.UV5Kind:
  36159. this.uvs5 = data;
  36160. break;
  36161. case BABYLON.VertexBuffer.UV6Kind:
  36162. this.uvs6 = data;
  36163. break;
  36164. case BABYLON.VertexBuffer.ColorKind:
  36165. this.colors = data;
  36166. break;
  36167. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36168. this.matricesIndices = data;
  36169. break;
  36170. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36171. this.matricesWeights = data;
  36172. break;
  36173. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36174. this.matricesIndicesExtra = data;
  36175. break;
  36176. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36177. this.matricesWeightsExtra = data;
  36178. break;
  36179. }
  36180. };
  36181. /**
  36182. * Associates the vertexData to the passed Mesh.
  36183. * Sets it as updatable or not (default `false`)
  36184. * @param mesh the mesh the vertexData is applied to
  36185. * @param updatable when used and having the value true allows new data to update the vertexData
  36186. * @returns the VertexData
  36187. */
  36188. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36189. this._applyTo(mesh, updatable);
  36190. return this;
  36191. };
  36192. /**
  36193. * Associates the vertexData to the passed Geometry.
  36194. * Sets it as updatable or not (default `false`)
  36195. * @param geometry the geometry the vertexData is applied to
  36196. * @param updatable when used and having the value true allows new data to update the vertexData
  36197. * @returns VertexData
  36198. */
  36199. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36200. this._applyTo(geometry, updatable);
  36201. return this;
  36202. };
  36203. /**
  36204. * Updates the associated mesh
  36205. * @param mesh the mesh to be updated
  36206. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36207. * @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
  36208. * @returns VertexData
  36209. */
  36210. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36211. this._update(mesh);
  36212. return this;
  36213. };
  36214. /**
  36215. * Updates the associated geometry
  36216. * @param geometry the geometry to be updated
  36217. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36218. * @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
  36219. * @returns VertexData.
  36220. */
  36221. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36222. this._update(geometry);
  36223. return this;
  36224. };
  36225. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36226. if (updatable === void 0) { updatable = false; }
  36227. if (this.positions) {
  36228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36229. }
  36230. if (this.normals) {
  36231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36232. }
  36233. if (this.tangents) {
  36234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36235. }
  36236. if (this.uvs) {
  36237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36238. }
  36239. if (this.uvs2) {
  36240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36241. }
  36242. if (this.uvs3) {
  36243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36244. }
  36245. if (this.uvs4) {
  36246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36247. }
  36248. if (this.uvs5) {
  36249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36250. }
  36251. if (this.uvs6) {
  36252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36253. }
  36254. if (this.colors) {
  36255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36256. }
  36257. if (this.matricesIndices) {
  36258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36259. }
  36260. if (this.matricesWeights) {
  36261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36262. }
  36263. if (this.matricesIndicesExtra) {
  36264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36265. }
  36266. if (this.matricesWeightsExtra) {
  36267. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36268. }
  36269. if (this.indices) {
  36270. meshOrGeometry.setIndices(this.indices, null, updatable);
  36271. }
  36272. else {
  36273. meshOrGeometry.setIndices([], null);
  36274. }
  36275. return this;
  36276. };
  36277. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36278. if (this.positions) {
  36279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36280. }
  36281. if (this.normals) {
  36282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36283. }
  36284. if (this.tangents) {
  36285. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36286. }
  36287. if (this.uvs) {
  36288. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36289. }
  36290. if (this.uvs2) {
  36291. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36292. }
  36293. if (this.uvs3) {
  36294. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36295. }
  36296. if (this.uvs4) {
  36297. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36298. }
  36299. if (this.uvs5) {
  36300. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36301. }
  36302. if (this.uvs6) {
  36303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36304. }
  36305. if (this.colors) {
  36306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36307. }
  36308. if (this.matricesIndices) {
  36309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36310. }
  36311. if (this.matricesWeights) {
  36312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36313. }
  36314. if (this.matricesIndicesExtra) {
  36315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36316. }
  36317. if (this.matricesWeightsExtra) {
  36318. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36319. }
  36320. if (this.indices) {
  36321. meshOrGeometry.setIndices(this.indices, null);
  36322. }
  36323. return this;
  36324. };
  36325. /**
  36326. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36327. * @param matrix the transforming matrix
  36328. * @returns the VertexData
  36329. */
  36330. VertexData.prototype.transform = function (matrix) {
  36331. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36332. var transformed = BABYLON.Vector3.Zero();
  36333. var index;
  36334. if (this.positions) {
  36335. var position = BABYLON.Vector3.Zero();
  36336. for (index = 0; index < this.positions.length; index += 3) {
  36337. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36338. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36339. this.positions[index] = transformed.x;
  36340. this.positions[index + 1] = transformed.y;
  36341. this.positions[index + 2] = transformed.z;
  36342. }
  36343. }
  36344. if (this.normals) {
  36345. var normal = BABYLON.Vector3.Zero();
  36346. for (index = 0; index < this.normals.length; index += 3) {
  36347. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36348. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36349. this.normals[index] = transformed.x;
  36350. this.normals[index + 1] = transformed.y;
  36351. this.normals[index + 2] = transformed.z;
  36352. }
  36353. }
  36354. if (this.tangents) {
  36355. var tangent = BABYLON.Vector4.Zero();
  36356. var tangentTransformed = BABYLON.Vector4.Zero();
  36357. for (index = 0; index < this.tangents.length; index += 4) {
  36358. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36359. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36360. this.tangents[index] = tangentTransformed.x;
  36361. this.tangents[index + 1] = tangentTransformed.y;
  36362. this.tangents[index + 2] = tangentTransformed.z;
  36363. this.tangents[index + 3] = tangentTransformed.w;
  36364. }
  36365. }
  36366. if (flip && this.indices) {
  36367. for (index = 0; index < this.indices.length; index += 3) {
  36368. var tmp = this.indices[index + 1];
  36369. this.indices[index + 1] = this.indices[index + 2];
  36370. this.indices[index + 2] = tmp;
  36371. }
  36372. }
  36373. return this;
  36374. };
  36375. /**
  36376. * Merges the passed VertexData into the current one
  36377. * @param other the VertexData to be merged into the current one
  36378. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36379. * @returns the modified VertexData
  36380. */
  36381. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36382. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36383. this._validate();
  36384. other._validate();
  36385. if (!this.normals !== !other.normals ||
  36386. !this.tangents !== !other.tangents ||
  36387. !this.uvs !== !other.uvs ||
  36388. !this.uvs2 !== !other.uvs2 ||
  36389. !this.uvs3 !== !other.uvs3 ||
  36390. !this.uvs4 !== !other.uvs4 ||
  36391. !this.uvs5 !== !other.uvs5 ||
  36392. !this.uvs6 !== !other.uvs6 ||
  36393. !this.colors !== !other.colors ||
  36394. !this.matricesIndices !== !other.matricesIndices ||
  36395. !this.matricesWeights !== !other.matricesWeights ||
  36396. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36397. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36398. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36399. }
  36400. if (other.indices) {
  36401. if (!this.indices) {
  36402. this.indices = [];
  36403. }
  36404. var offset = this.positions ? this.positions.length / 3 : 0;
  36405. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36406. if (isSrcTypedArray) {
  36407. var len = this.indices.length + other.indices.length;
  36408. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36409. temp.set(this.indices);
  36410. var decal = this.indices.length;
  36411. for (var index = 0; index < other.indices.length; index++) {
  36412. temp[decal + index] = other.indices[index] + offset;
  36413. }
  36414. this.indices = temp;
  36415. }
  36416. else {
  36417. for (var index = 0; index < other.indices.length; index++) {
  36418. this.indices.push(other.indices[index] + offset);
  36419. }
  36420. }
  36421. }
  36422. this.positions = this._mergeElement(this.positions, other.positions);
  36423. this.normals = this._mergeElement(this.normals, other.normals);
  36424. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36425. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36426. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36427. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36428. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36429. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36430. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36431. this.colors = this._mergeElement(this.colors, other.colors);
  36432. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36433. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36434. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36435. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36436. return this;
  36437. };
  36438. VertexData.prototype._mergeElement = function (source, other) {
  36439. if (!source) {
  36440. return other;
  36441. }
  36442. if (!other) {
  36443. return source;
  36444. }
  36445. var len = other.length + source.length;
  36446. var isSrcTypedArray = source instanceof Float32Array;
  36447. var isOthTypedArray = other instanceof Float32Array;
  36448. // use non-loop method when the source is Float32Array
  36449. if (isSrcTypedArray) {
  36450. var ret32 = new Float32Array(len);
  36451. ret32.set(source);
  36452. ret32.set(other, source.length);
  36453. return ret32;
  36454. // source is number[], when other is also use concat
  36455. }
  36456. else if (!isOthTypedArray) {
  36457. return source.concat(other);
  36458. // source is a number[], but other is a Float32Array, loop required
  36459. }
  36460. else {
  36461. var ret = source.slice(0); // copy source to a separate array
  36462. for (var i = 0, len = other.length; i < len; i++) {
  36463. ret.push(other[i]);
  36464. }
  36465. return ret;
  36466. }
  36467. };
  36468. VertexData.prototype._validate = function () {
  36469. if (!this.positions) {
  36470. throw new Error("Positions are required");
  36471. }
  36472. var getElementCount = function (kind, values) {
  36473. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36474. if ((values.length % stride) !== 0) {
  36475. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36476. }
  36477. return values.length / stride;
  36478. };
  36479. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36480. var validateElementCount = function (kind, values) {
  36481. var elementCount = getElementCount(kind, values);
  36482. if (elementCount !== positionsElementCount) {
  36483. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36484. }
  36485. };
  36486. if (this.normals)
  36487. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36488. if (this.tangents)
  36489. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36490. if (this.uvs)
  36491. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36492. if (this.uvs2)
  36493. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36494. if (this.uvs3)
  36495. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36496. if (this.uvs4)
  36497. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36498. if (this.uvs5)
  36499. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36500. if (this.uvs6)
  36501. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36502. if (this.colors)
  36503. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36504. if (this.matricesIndices)
  36505. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36506. if (this.matricesWeights)
  36507. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36508. if (this.matricesIndicesExtra)
  36509. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36510. if (this.matricesWeightsExtra)
  36511. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36512. };
  36513. /**
  36514. * Serializes the VertexData
  36515. * @returns a serialized object
  36516. */
  36517. VertexData.prototype.serialize = function () {
  36518. var serializationObject = this.serialize();
  36519. if (this.positions) {
  36520. serializationObject.positions = this.positions;
  36521. }
  36522. if (this.normals) {
  36523. serializationObject.normals = this.normals;
  36524. }
  36525. if (this.tangents) {
  36526. serializationObject.tangents = this.tangents;
  36527. }
  36528. if (this.uvs) {
  36529. serializationObject.uvs = this.uvs;
  36530. }
  36531. if (this.uvs2) {
  36532. serializationObject.uvs2 = this.uvs2;
  36533. }
  36534. if (this.uvs3) {
  36535. serializationObject.uvs3 = this.uvs3;
  36536. }
  36537. if (this.uvs4) {
  36538. serializationObject.uvs4 = this.uvs4;
  36539. }
  36540. if (this.uvs5) {
  36541. serializationObject.uvs5 = this.uvs5;
  36542. }
  36543. if (this.uvs6) {
  36544. serializationObject.uvs6 = this.uvs6;
  36545. }
  36546. if (this.colors) {
  36547. serializationObject.colors = this.colors;
  36548. }
  36549. if (this.matricesIndices) {
  36550. serializationObject.matricesIndices = this.matricesIndices;
  36551. serializationObject.matricesIndices._isExpanded = true;
  36552. }
  36553. if (this.matricesWeights) {
  36554. serializationObject.matricesWeights = this.matricesWeights;
  36555. }
  36556. if (this.matricesIndicesExtra) {
  36557. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36558. serializationObject.matricesIndicesExtra._isExpanded = true;
  36559. }
  36560. if (this.matricesWeightsExtra) {
  36561. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36562. }
  36563. serializationObject.indices = this.indices;
  36564. return serializationObject;
  36565. };
  36566. // Statics
  36567. /**
  36568. * Extracts the vertexData from a mesh
  36569. * @param mesh the mesh from which to extract the VertexData
  36570. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36571. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36572. * @returns the object VertexData associated to the passed mesh
  36573. */
  36574. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36575. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36576. };
  36577. /**
  36578. * Extracts the vertexData from the geometry
  36579. * @param geometry the geometry from which to extract the VertexData
  36580. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36581. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36582. * @returns the object VertexData associated to the passed mesh
  36583. */
  36584. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36585. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36586. };
  36587. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36588. var result = new VertexData();
  36589. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36590. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36591. }
  36592. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36593. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36594. }
  36595. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36596. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36597. }
  36598. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36599. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36600. }
  36601. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36602. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36603. }
  36604. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36605. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36606. }
  36607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36608. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36609. }
  36610. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36611. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36612. }
  36613. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36614. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36615. }
  36616. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36617. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36618. }
  36619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36620. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36621. }
  36622. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36623. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36624. }
  36625. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36626. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36627. }
  36628. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36629. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36630. }
  36631. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36632. return result;
  36633. };
  36634. /**
  36635. * Creates the VertexData for a Ribbon
  36636. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36637. * * pathArray array of paths, each of which an array of successive Vector3
  36638. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36639. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36640. * * 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
  36641. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36642. * * 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)
  36643. * * 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)
  36644. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36645. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36646. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36647. * @returns the VertexData of the ribbon
  36648. */
  36649. VertexData.CreateRibbon = function (options) {
  36650. var pathArray = options.pathArray;
  36651. var closeArray = options.closeArray || false;
  36652. var closePath = options.closePath || false;
  36653. var invertUV = options.invertUV || false;
  36654. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36655. var offset = options.offset || defaultOffset;
  36656. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36658. var customUV = options.uvs;
  36659. var customColors = options.colors;
  36660. var positions = [];
  36661. var indices = [];
  36662. var normals = [];
  36663. var uvs = [];
  36664. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36665. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36666. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36667. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36668. var minlg; // minimal length among all paths from pathArray
  36669. var lg = []; // array of path lengths : nb of vertex per path
  36670. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36671. var p; // path iterator
  36672. var i; // point iterator
  36673. var j; // point iterator
  36674. // if single path in pathArray
  36675. if (pathArray.length < 2) {
  36676. var ar1 = [];
  36677. var ar2 = [];
  36678. for (i = 0; i < pathArray[0].length - offset; i++) {
  36679. ar1.push(pathArray[0][i]);
  36680. ar2.push(pathArray[0][i + offset]);
  36681. }
  36682. pathArray = [ar1, ar2];
  36683. }
  36684. // positions and horizontal distances (u)
  36685. var idc = 0;
  36686. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36687. var path;
  36688. var l;
  36689. minlg = pathArray[0].length;
  36690. var vectlg;
  36691. var dist;
  36692. for (p = 0; p < pathArray.length; p++) {
  36693. uTotalDistance[p] = 0;
  36694. us[p] = [0];
  36695. path = pathArray[p];
  36696. l = path.length;
  36697. minlg = (minlg < l) ? minlg : l;
  36698. j = 0;
  36699. while (j < l) {
  36700. positions.push(path[j].x, path[j].y, path[j].z);
  36701. if (j > 0) {
  36702. vectlg = path[j].subtract(path[j - 1]).length();
  36703. dist = vectlg + uTotalDistance[p];
  36704. us[p].push(dist);
  36705. uTotalDistance[p] = dist;
  36706. }
  36707. j++;
  36708. }
  36709. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36710. j--;
  36711. positions.push(path[0].x, path[0].y, path[0].z);
  36712. vectlg = path[j].subtract(path[0]).length();
  36713. dist = vectlg + uTotalDistance[p];
  36714. us[p].push(dist);
  36715. uTotalDistance[p] = dist;
  36716. }
  36717. lg[p] = l + closePathCorr;
  36718. idx[p] = idc;
  36719. idc += (l + closePathCorr);
  36720. }
  36721. // vertical distances (v)
  36722. var path1;
  36723. var path2;
  36724. var vertex1 = null;
  36725. var vertex2 = null;
  36726. for (i = 0; i < minlg + closePathCorr; i++) {
  36727. vTotalDistance[i] = 0;
  36728. vs[i] = [0];
  36729. for (p = 0; p < pathArray.length - 1; p++) {
  36730. path1 = pathArray[p];
  36731. path2 = pathArray[p + 1];
  36732. if (i === minlg) { // closePath
  36733. vertex1 = path1[0];
  36734. vertex2 = path2[0];
  36735. }
  36736. else {
  36737. vertex1 = path1[i];
  36738. vertex2 = path2[i];
  36739. }
  36740. vectlg = vertex2.subtract(vertex1).length();
  36741. dist = vectlg + vTotalDistance[i];
  36742. vs[i].push(dist);
  36743. vTotalDistance[i] = dist;
  36744. }
  36745. if (closeArray && vertex2 && vertex1) {
  36746. path1 = pathArray[p];
  36747. path2 = pathArray[0];
  36748. if (i === minlg) { // closePath
  36749. vertex2 = path2[0];
  36750. }
  36751. vectlg = vertex2.subtract(vertex1).length();
  36752. dist = vectlg + vTotalDistance[i];
  36753. vTotalDistance[i] = dist;
  36754. }
  36755. }
  36756. // uvs
  36757. var u;
  36758. var v;
  36759. if (customUV) {
  36760. for (p = 0; p < customUV.length; p++) {
  36761. uvs.push(customUV[p].x, customUV[p].y);
  36762. }
  36763. }
  36764. else {
  36765. for (p = 0; p < pathArray.length; p++) {
  36766. for (i = 0; i < minlg + closePathCorr; i++) {
  36767. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36768. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36769. if (invertUV) {
  36770. uvs.push(v, u);
  36771. }
  36772. else {
  36773. uvs.push(u, v);
  36774. }
  36775. }
  36776. }
  36777. }
  36778. // indices
  36779. p = 0; // path index
  36780. var pi = 0; // positions array index
  36781. var l1 = lg[p] - 1; // path1 length
  36782. var l2 = lg[p + 1] - 1; // path2 length
  36783. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36784. var shft = idx[1] - idx[0]; // shift
  36785. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36786. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36787. // 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
  36788. indices.push(pi, pi + shft, pi + 1);
  36789. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36790. pi += 1;
  36791. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36792. p++;
  36793. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36794. shft = idx[0] - idx[p];
  36795. l1 = lg[p] - 1;
  36796. l2 = lg[0] - 1;
  36797. }
  36798. else {
  36799. shft = idx[p + 1] - idx[p];
  36800. l1 = lg[p] - 1;
  36801. l2 = lg[p + 1] - 1;
  36802. }
  36803. pi = idx[p];
  36804. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36805. }
  36806. }
  36807. // normals
  36808. VertexData.ComputeNormals(positions, indices, normals);
  36809. if (closePath) { // update both the first and last vertex normals to their average value
  36810. var indexFirst = 0;
  36811. var indexLast = 0;
  36812. for (p = 0; p < pathArray.length; p++) {
  36813. indexFirst = idx[p] * 3;
  36814. if (p + 1 < pathArray.length) {
  36815. indexLast = (idx[p + 1] - 1) * 3;
  36816. }
  36817. else {
  36818. indexLast = normals.length - 3;
  36819. }
  36820. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36821. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36822. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36823. normals[indexLast] = normals[indexFirst];
  36824. normals[indexLast + 1] = normals[indexFirst + 1];
  36825. normals[indexLast + 2] = normals[indexFirst + 2];
  36826. }
  36827. }
  36828. // sides
  36829. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36830. // Colors
  36831. var colors = null;
  36832. if (customColors) {
  36833. colors = new Float32Array(customColors.length * 4);
  36834. for (var c = 0; c < customColors.length; c++) {
  36835. colors[c * 4] = customColors[c].r;
  36836. colors[c * 4 + 1] = customColors[c].g;
  36837. colors[c * 4 + 2] = customColors[c].b;
  36838. colors[c * 4 + 3] = customColors[c].a;
  36839. }
  36840. }
  36841. // Result
  36842. var vertexData = new VertexData();
  36843. var positions32 = new Float32Array(positions);
  36844. var normals32 = new Float32Array(normals);
  36845. var uvs32 = new Float32Array(uvs);
  36846. vertexData.indices = indices;
  36847. vertexData.positions = positions32;
  36848. vertexData.normals = normals32;
  36849. vertexData.uvs = uvs32;
  36850. if (colors) {
  36851. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36852. }
  36853. if (closePath) {
  36854. vertexData._idx = idx;
  36855. }
  36856. return vertexData;
  36857. };
  36858. /**
  36859. * Creates the VertexData for a box
  36860. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36861. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36862. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36863. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36864. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36865. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36866. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36867. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36868. * * 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)
  36869. * * 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)
  36870. * @returns the VertexData of the box
  36871. */
  36872. VertexData.CreateBox = function (options) {
  36873. var normalsSource = [
  36874. new BABYLON.Vector3(0, 0, 1),
  36875. new BABYLON.Vector3(0, 0, -1),
  36876. new BABYLON.Vector3(1, 0, 0),
  36877. new BABYLON.Vector3(-1, 0, 0),
  36878. new BABYLON.Vector3(0, 1, 0),
  36879. new BABYLON.Vector3(0, -1, 0)
  36880. ];
  36881. var indices = [];
  36882. var positions = [];
  36883. var normals = [];
  36884. var uvs = [];
  36885. var width = options.width || options.size || 1;
  36886. var height = options.height || options.size || 1;
  36887. var depth = options.depth || options.size || 1;
  36888. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36889. var faceUV = options.faceUV || new Array(6);
  36890. var faceColors = options.faceColors;
  36891. var colors = [];
  36892. // default face colors and UV if undefined
  36893. for (var f = 0; f < 6; f++) {
  36894. if (faceUV[f] === undefined) {
  36895. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36896. }
  36897. if (faceColors && faceColors[f] === undefined) {
  36898. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36899. }
  36900. }
  36901. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36902. // Create each face in turn.
  36903. for (var index = 0; index < normalsSource.length; index++) {
  36904. var normal = normalsSource[index];
  36905. // Get two vectors perpendicular to the face normal and to each other.
  36906. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36907. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36908. // Six indices (two triangles) per face.
  36909. var verticesLength = positions.length / 3;
  36910. indices.push(verticesLength);
  36911. indices.push(verticesLength + 1);
  36912. indices.push(verticesLength + 2);
  36913. indices.push(verticesLength);
  36914. indices.push(verticesLength + 2);
  36915. indices.push(verticesLength + 3);
  36916. // Four vertices per face.
  36917. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36918. positions.push(vertex.x, vertex.y, vertex.z);
  36919. normals.push(normal.x, normal.y, normal.z);
  36920. uvs.push(faceUV[index].z, faceUV[index].w);
  36921. if (faceColors) {
  36922. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36923. }
  36924. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36925. positions.push(vertex.x, vertex.y, vertex.z);
  36926. normals.push(normal.x, normal.y, normal.z);
  36927. uvs.push(faceUV[index].x, faceUV[index].w);
  36928. if (faceColors) {
  36929. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36930. }
  36931. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36932. positions.push(vertex.x, vertex.y, vertex.z);
  36933. normals.push(normal.x, normal.y, normal.z);
  36934. uvs.push(faceUV[index].x, faceUV[index].y);
  36935. if (faceColors) {
  36936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36937. }
  36938. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36939. positions.push(vertex.x, vertex.y, vertex.z);
  36940. normals.push(normal.x, normal.y, normal.z);
  36941. uvs.push(faceUV[index].z, faceUV[index].y);
  36942. if (faceColors) {
  36943. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36944. }
  36945. }
  36946. // sides
  36947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36948. // Result
  36949. var vertexData = new VertexData();
  36950. vertexData.indices = indices;
  36951. vertexData.positions = positions;
  36952. vertexData.normals = normals;
  36953. vertexData.uvs = uvs;
  36954. if (faceColors) {
  36955. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36956. vertexData.colors = totalColors;
  36957. }
  36958. return vertexData;
  36959. };
  36960. /**
  36961. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36962. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36963. * * segments sets the number of horizontal strips optional, default 32
  36964. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36965. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36966. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36967. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36968. * * 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
  36969. * * 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
  36970. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36971. * * 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)
  36972. * * 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)
  36973. * @returns the VertexData of the ellipsoid
  36974. */
  36975. VertexData.CreateSphere = function (options) {
  36976. var segments = options.segments || 32;
  36977. var diameterX = options.diameterX || options.diameter || 1;
  36978. var diameterY = options.diameterY || options.diameter || 1;
  36979. var diameterZ = options.diameterZ || options.diameter || 1;
  36980. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36981. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36983. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36984. var totalZRotationSteps = 2 + segments;
  36985. var totalYRotationSteps = 2 * totalZRotationSteps;
  36986. var indices = [];
  36987. var positions = [];
  36988. var normals = [];
  36989. var uvs = [];
  36990. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36991. var normalizedZ = zRotationStep / totalZRotationSteps;
  36992. var angleZ = normalizedZ * Math.PI * slice;
  36993. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36994. var normalizedY = yRotationStep / totalYRotationSteps;
  36995. var angleY = normalizedY * Math.PI * 2 * arc;
  36996. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36997. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36998. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36999. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37000. var vertex = complete.multiply(radius);
  37001. var normal = complete.divide(radius).normalize();
  37002. positions.push(vertex.x, vertex.y, vertex.z);
  37003. normals.push(normal.x, normal.y, normal.z);
  37004. uvs.push(normalizedY, normalizedZ);
  37005. }
  37006. if (zRotationStep > 0) {
  37007. var verticesCount = positions.length / 3;
  37008. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37009. indices.push((firstIndex));
  37010. indices.push((firstIndex + 1));
  37011. indices.push(firstIndex + totalYRotationSteps + 1);
  37012. indices.push((firstIndex + totalYRotationSteps + 1));
  37013. indices.push((firstIndex + 1));
  37014. indices.push((firstIndex + totalYRotationSteps + 2));
  37015. }
  37016. }
  37017. }
  37018. // Sides
  37019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37020. // Result
  37021. var vertexData = new VertexData();
  37022. vertexData.indices = indices;
  37023. vertexData.positions = positions;
  37024. vertexData.normals = normals;
  37025. vertexData.uvs = uvs;
  37026. return vertexData;
  37027. };
  37028. /**
  37029. * Creates the VertexData for a cylinder, cone or prism
  37030. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37031. * * height sets the height (y direction) of the cylinder, optional, default 2
  37032. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37033. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37034. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37035. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37036. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37037. * * 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
  37038. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37039. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37040. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37041. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37042. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37043. * * 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)
  37044. * * 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)
  37045. * @returns the VertexData of the cylinder, cone or prism
  37046. */
  37047. VertexData.CreateCylinder = function (options) {
  37048. var height = options.height || 2;
  37049. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37050. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37051. var tessellation = options.tessellation || 24;
  37052. var subdivisions = options.subdivisions || 1;
  37053. var hasRings = options.hasRings ? true : false;
  37054. var enclose = options.enclose ? true : false;
  37055. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37056. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37057. var faceUV = options.faceUV || new Array(3);
  37058. var faceColors = options.faceColors;
  37059. // default face colors and UV if undefined
  37060. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37061. var ringNb = (hasRings) ? subdivisions : 1;
  37062. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37063. var f;
  37064. for (f = 0; f < surfaceNb; f++) {
  37065. if (faceColors && faceColors[f] === undefined) {
  37066. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37067. }
  37068. }
  37069. for (f = 0; f < surfaceNb; f++) {
  37070. if (faceUV && faceUV[f] === undefined) {
  37071. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37072. }
  37073. }
  37074. var indices = new Array();
  37075. var positions = new Array();
  37076. var normals = new Array();
  37077. var uvs = new Array();
  37078. var colors = new Array();
  37079. var angle_step = Math.PI * 2 * arc / tessellation;
  37080. var angle;
  37081. var h;
  37082. var radius;
  37083. var tan = (diameterBottom - diameterTop) / 2 / height;
  37084. var ringVertex = BABYLON.Vector3.Zero();
  37085. var ringNormal = BABYLON.Vector3.Zero();
  37086. var ringFirstVertex = BABYLON.Vector3.Zero();
  37087. var ringFirstNormal = BABYLON.Vector3.Zero();
  37088. var quadNormal = BABYLON.Vector3.Zero();
  37089. var Y = BABYLON.Axis.Y;
  37090. // positions, normals, uvs
  37091. var i;
  37092. var j;
  37093. var r;
  37094. var ringIdx = 1;
  37095. var s = 1; // surface index
  37096. var cs = 0;
  37097. var v = 0;
  37098. for (i = 0; i <= subdivisions; i++) {
  37099. h = i / subdivisions;
  37100. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37101. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37102. for (r = 0; r < ringIdx; r++) {
  37103. if (hasRings) {
  37104. s += r;
  37105. }
  37106. if (enclose) {
  37107. s += 2 * r;
  37108. }
  37109. for (j = 0; j <= tessellation; j++) {
  37110. angle = j * angle_step;
  37111. // position
  37112. ringVertex.x = Math.cos(-angle) * radius;
  37113. ringVertex.y = -height / 2 + h * height;
  37114. ringVertex.z = Math.sin(-angle) * radius;
  37115. // normal
  37116. if (diameterTop === 0 && i === subdivisions) {
  37117. // if no top cap, reuse former normals
  37118. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37119. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37120. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37121. }
  37122. else {
  37123. ringNormal.x = ringVertex.x;
  37124. ringNormal.z = ringVertex.z;
  37125. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37126. ringNormal.normalize();
  37127. }
  37128. // keep first ring vertex values for enclose
  37129. if (j === 0) {
  37130. ringFirstVertex.copyFrom(ringVertex);
  37131. ringFirstNormal.copyFrom(ringNormal);
  37132. }
  37133. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37134. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37135. if (hasRings) {
  37136. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37137. }
  37138. else {
  37139. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37140. }
  37141. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37142. if (faceColors) {
  37143. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37144. }
  37145. }
  37146. // if enclose, add four vertices and their dedicated normals
  37147. if (arc !== 1 && enclose) {
  37148. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37149. positions.push(0, ringVertex.y, 0);
  37150. positions.push(0, ringVertex.y, 0);
  37151. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37152. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37153. quadNormal.normalize();
  37154. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37155. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37156. quadNormal.normalize();
  37157. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37158. if (hasRings) {
  37159. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37160. }
  37161. else {
  37162. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37163. }
  37164. uvs.push(faceUV[s + 1].x, v);
  37165. uvs.push(faceUV[s + 1].z, v);
  37166. if (hasRings) {
  37167. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37168. }
  37169. else {
  37170. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37171. }
  37172. uvs.push(faceUV[s + 2].x, v);
  37173. uvs.push(faceUV[s + 2].z, v);
  37174. if (faceColors) {
  37175. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37176. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37177. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37178. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37179. }
  37180. }
  37181. if (cs !== s) {
  37182. cs = s;
  37183. }
  37184. }
  37185. }
  37186. // indices
  37187. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37188. var s;
  37189. i = 0;
  37190. for (s = 0; s < subdivisions; s++) {
  37191. var i0 = 0;
  37192. var i1 = 0;
  37193. var i2 = 0;
  37194. var i3 = 0;
  37195. for (j = 0; j < tessellation; j++) {
  37196. i0 = i * (e + 1) + j;
  37197. i1 = (i + 1) * (e + 1) + j;
  37198. i2 = i * (e + 1) + (j + 1);
  37199. i3 = (i + 1) * (e + 1) + (j + 1);
  37200. indices.push(i0, i1, i2);
  37201. indices.push(i3, i2, i1);
  37202. }
  37203. if (arc !== 1 && enclose) { // if enclose, add two quads
  37204. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37205. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37206. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37207. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37208. }
  37209. i = (hasRings) ? (i + 2) : (i + 1);
  37210. }
  37211. // Caps
  37212. var createCylinderCap = function (isTop) {
  37213. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37214. if (radius === 0) {
  37215. return;
  37216. }
  37217. // Cap positions, normals & uvs
  37218. var angle;
  37219. var circleVector;
  37220. var i;
  37221. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37222. var c = null;
  37223. if (faceColors) {
  37224. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37225. }
  37226. // cap center
  37227. var vbase = positions.length / 3;
  37228. var offset = isTop ? height / 2 : -height / 2;
  37229. var center = new BABYLON.Vector3(0, offset, 0);
  37230. positions.push(center.x, center.y, center.z);
  37231. normals.push(0, isTop ? 1 : -1, 0);
  37232. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37233. if (c) {
  37234. colors.push(c.r, c.g, c.b, c.a);
  37235. }
  37236. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37237. for (i = 0; i <= tessellation; i++) {
  37238. angle = Math.PI * 2 * i * arc / tessellation;
  37239. var cos = Math.cos(-angle);
  37240. var sin = Math.sin(-angle);
  37241. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37242. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37243. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37244. normals.push(0, isTop ? 1 : -1, 0);
  37245. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37246. if (c) {
  37247. colors.push(c.r, c.g, c.b, c.a);
  37248. }
  37249. }
  37250. // Cap indices
  37251. for (i = 0; i < tessellation; i++) {
  37252. if (!isTop) {
  37253. indices.push(vbase);
  37254. indices.push(vbase + (i + 1));
  37255. indices.push(vbase + (i + 2));
  37256. }
  37257. else {
  37258. indices.push(vbase);
  37259. indices.push(vbase + (i + 2));
  37260. indices.push(vbase + (i + 1));
  37261. }
  37262. }
  37263. };
  37264. // add caps to geometry
  37265. createCylinderCap(false);
  37266. createCylinderCap(true);
  37267. // Sides
  37268. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37269. var vertexData = new VertexData();
  37270. vertexData.indices = indices;
  37271. vertexData.positions = positions;
  37272. vertexData.normals = normals;
  37273. vertexData.uvs = uvs;
  37274. if (faceColors) {
  37275. vertexData.colors = colors;
  37276. }
  37277. return vertexData;
  37278. };
  37279. /**
  37280. * Creates the VertexData for a torus
  37281. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37282. * * diameter the diameter of the torus, optional default 1
  37283. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37284. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37285. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37286. * * 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)
  37287. * * 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)
  37288. * @returns the VertexData of the torus
  37289. */
  37290. VertexData.CreateTorus = function (options) {
  37291. var indices = [];
  37292. var positions = [];
  37293. var normals = [];
  37294. var uvs = [];
  37295. var diameter = options.diameter || 1;
  37296. var thickness = options.thickness || 0.5;
  37297. var tessellation = options.tessellation || 16;
  37298. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37299. var stride = tessellation + 1;
  37300. for (var i = 0; i <= tessellation; i++) {
  37301. var u = i / tessellation;
  37302. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37303. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37304. for (var j = 0; j <= tessellation; j++) {
  37305. var v = 1 - j / tessellation;
  37306. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37307. var dx = Math.cos(innerAngle);
  37308. var dy = Math.sin(innerAngle);
  37309. // Create a vertex.
  37310. var normal = new BABYLON.Vector3(dx, dy, 0);
  37311. var position = normal.scale(thickness / 2);
  37312. var textureCoordinate = new BABYLON.Vector2(u, v);
  37313. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37314. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37315. positions.push(position.x, position.y, position.z);
  37316. normals.push(normal.x, normal.y, normal.z);
  37317. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37318. // And create indices for two triangles.
  37319. var nextI = (i + 1) % stride;
  37320. var nextJ = (j + 1) % stride;
  37321. indices.push(i * stride + j);
  37322. indices.push(i * stride + nextJ);
  37323. indices.push(nextI * stride + j);
  37324. indices.push(i * stride + nextJ);
  37325. indices.push(nextI * stride + nextJ);
  37326. indices.push(nextI * stride + j);
  37327. }
  37328. }
  37329. // Sides
  37330. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37331. // Result
  37332. var vertexData = new VertexData();
  37333. vertexData.indices = indices;
  37334. vertexData.positions = positions;
  37335. vertexData.normals = normals;
  37336. vertexData.uvs = uvs;
  37337. return vertexData;
  37338. };
  37339. /**
  37340. * Creates the VertexData of the LineSystem
  37341. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37342. * - lines an array of lines, each line being an array of successive Vector3
  37343. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37344. * @returns the VertexData of the LineSystem
  37345. */
  37346. VertexData.CreateLineSystem = function (options) {
  37347. var indices = [];
  37348. var positions = [];
  37349. var lines = options.lines;
  37350. var colors = options.colors;
  37351. var vertexColors = [];
  37352. var idx = 0;
  37353. for (var l = 0; l < lines.length; l++) {
  37354. var points = lines[l];
  37355. for (var index = 0; index < points.length; index++) {
  37356. positions.push(points[index].x, points[index].y, points[index].z);
  37357. if (colors) {
  37358. var color = colors[l];
  37359. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37360. }
  37361. if (index > 0) {
  37362. indices.push(idx - 1);
  37363. indices.push(idx);
  37364. }
  37365. idx++;
  37366. }
  37367. }
  37368. var vertexData = new VertexData();
  37369. vertexData.indices = indices;
  37370. vertexData.positions = positions;
  37371. if (colors) {
  37372. vertexData.colors = vertexColors;
  37373. }
  37374. return vertexData;
  37375. };
  37376. /**
  37377. * Create the VertexData for a DashedLines
  37378. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37379. * - points an array successive Vector3
  37380. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37381. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37382. * - dashNb the intended total number of dashes, optional, default 200
  37383. * @returns the VertexData for the DashedLines
  37384. */
  37385. VertexData.CreateDashedLines = function (options) {
  37386. var dashSize = options.dashSize || 3;
  37387. var gapSize = options.gapSize || 1;
  37388. var dashNb = options.dashNb || 200;
  37389. var points = options.points;
  37390. var positions = new Array();
  37391. var indices = new Array();
  37392. var curvect = BABYLON.Vector3.Zero();
  37393. var lg = 0;
  37394. var nb = 0;
  37395. var shft = 0;
  37396. var dashshft = 0;
  37397. var curshft = 0;
  37398. var idx = 0;
  37399. var i = 0;
  37400. for (i = 0; i < points.length - 1; i++) {
  37401. points[i + 1].subtractToRef(points[i], curvect);
  37402. lg += curvect.length();
  37403. }
  37404. shft = lg / dashNb;
  37405. dashshft = dashSize * shft / (dashSize + gapSize);
  37406. for (i = 0; i < points.length - 1; i++) {
  37407. points[i + 1].subtractToRef(points[i], curvect);
  37408. nb = Math.floor(curvect.length() / shft);
  37409. curvect.normalize();
  37410. for (var j = 0; j < nb; j++) {
  37411. curshft = shft * j;
  37412. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37413. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37414. indices.push(idx, idx + 1);
  37415. idx += 2;
  37416. }
  37417. }
  37418. // Result
  37419. var vertexData = new VertexData();
  37420. vertexData.positions = positions;
  37421. vertexData.indices = indices;
  37422. return vertexData;
  37423. };
  37424. /**
  37425. * Creates the VertexData for a Ground
  37426. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37427. * - width the width (x direction) of the ground, optional, default 1
  37428. * - height the height (z direction) of the ground, optional, default 1
  37429. * - subdivisions the number of subdivisions per side, optional, default 1
  37430. * @returns the VertexData of the Ground
  37431. */
  37432. VertexData.CreateGround = function (options) {
  37433. var indices = [];
  37434. var positions = [];
  37435. var normals = [];
  37436. var uvs = [];
  37437. var row, col;
  37438. var width = options.width || 1;
  37439. var height = options.height || 1;
  37440. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37441. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37442. for (row = 0; row <= subdivisionsY; row++) {
  37443. for (col = 0; col <= subdivisionsX; col++) {
  37444. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37445. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37446. positions.push(position.x, position.y, position.z);
  37447. normals.push(normal.x, normal.y, normal.z);
  37448. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37449. }
  37450. }
  37451. for (row = 0; row < subdivisionsY; row++) {
  37452. for (col = 0; col < subdivisionsX; col++) {
  37453. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37454. indices.push(col + 1 + row * (subdivisionsX + 1));
  37455. indices.push(col + row * (subdivisionsX + 1));
  37456. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37457. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37458. indices.push(col + row * (subdivisionsX + 1));
  37459. }
  37460. }
  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 for a TiledGround by subdividing the ground into tiles
  37471. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37472. * * xmin the ground minimum X coordinate, optional, default -1
  37473. * * zmin the ground minimum Z coordinate, optional, default -1
  37474. * * xmax the ground maximum X coordinate, optional, default 1
  37475. * * zmax the ground maximum Z coordinate, optional, default 1
  37476. * * 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}
  37477. * * 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}
  37478. * @returns the VertexData of the TiledGround
  37479. */
  37480. VertexData.CreateTiledGround = function (options) {
  37481. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37482. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37483. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37484. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37485. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37486. var precision = options.precision || { w: 1, h: 1 };
  37487. var indices = new Array();
  37488. var positions = new Array();
  37489. var normals = new Array();
  37490. var uvs = new Array();
  37491. var row, col, tileRow, tileCol;
  37492. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37493. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37494. precision.w = (precision.w < 1) ? 1 : precision.w;
  37495. precision.h = (precision.h < 1) ? 1 : precision.h;
  37496. var tileSize = {
  37497. 'w': (xmax - xmin) / subdivisions.w,
  37498. 'h': (zmax - zmin) / subdivisions.h
  37499. };
  37500. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37501. // Indices
  37502. var base = positions.length / 3;
  37503. var rowLength = precision.w + 1;
  37504. for (row = 0; row < precision.h; row++) {
  37505. for (col = 0; col < precision.w; col++) {
  37506. var square = [
  37507. base + col + row * rowLength,
  37508. base + (col + 1) + row * rowLength,
  37509. base + (col + 1) + (row + 1) * rowLength,
  37510. base + col + (row + 1) * rowLength
  37511. ];
  37512. indices.push(square[1]);
  37513. indices.push(square[2]);
  37514. indices.push(square[3]);
  37515. indices.push(square[0]);
  37516. indices.push(square[1]);
  37517. indices.push(square[3]);
  37518. }
  37519. }
  37520. // Position, normals and uvs
  37521. var position = BABYLON.Vector3.Zero();
  37522. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37523. for (row = 0; row <= precision.h; row++) {
  37524. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37525. for (col = 0; col <= precision.w; col++) {
  37526. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37527. position.y = 0;
  37528. positions.push(position.x, position.y, position.z);
  37529. normals.push(normal.x, normal.y, normal.z);
  37530. uvs.push(col / precision.w, row / precision.h);
  37531. }
  37532. }
  37533. }
  37534. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37535. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37536. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37537. }
  37538. }
  37539. // Result
  37540. var vertexData = new VertexData();
  37541. vertexData.indices = indices;
  37542. vertexData.positions = positions;
  37543. vertexData.normals = normals;
  37544. vertexData.uvs = uvs;
  37545. return vertexData;
  37546. };
  37547. /**
  37548. * Creates the VertexData of the Ground designed from a heightmap
  37549. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37550. * * width the width (x direction) of the ground
  37551. * * height the height (z direction) of the ground
  37552. * * subdivisions the number of subdivisions per side
  37553. * * minHeight the minimum altitude on the ground, optional, default 0
  37554. * * maxHeight the maximum altitude on the ground, optional default 1
  37555. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37556. * * buffer the array holding the image color data
  37557. * * bufferWidth the width of image
  37558. * * bufferHeight the height of image
  37559. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37560. * @returns the VertexData of the Ground designed from a heightmap
  37561. */
  37562. VertexData.CreateGroundFromHeightMap = function (options) {
  37563. var indices = [];
  37564. var positions = [];
  37565. var normals = [];
  37566. var uvs = [];
  37567. var row, col;
  37568. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37569. var alphaFilter = options.alphaFilter || 0.0;
  37570. // Vertices
  37571. for (row = 0; row <= options.subdivisions; row++) {
  37572. for (col = 0; col <= options.subdivisions; col++) {
  37573. 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));
  37574. // Compute height
  37575. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37576. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37577. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37578. var r = options.buffer[pos] / 255.0;
  37579. var g = options.buffer[pos + 1] / 255.0;
  37580. var b = options.buffer[pos + 2] / 255.0;
  37581. var a = options.buffer[pos + 3] / 255.0;
  37582. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37583. // If our alpha channel is not within our filter then we will assign a 'special' height
  37584. // Then when building the indices, we will ignore any vertex that is using the special height
  37585. if (a >= alphaFilter)
  37586. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37587. else {
  37588. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37589. }
  37590. // Add vertex
  37591. positions.push(position.x, position.y, position.z);
  37592. normals.push(0, 0, 0);
  37593. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37594. }
  37595. }
  37596. // Indices
  37597. for (row = 0; row < options.subdivisions; row++) {
  37598. for (col = 0; col < options.subdivisions; col++) {
  37599. // Calculate Indices
  37600. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37601. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37602. var idx3 = (col + row * (options.subdivisions + 1));
  37603. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37604. // Check that all indices are visible (based on our special height)
  37605. // Only display the vertex if all Indices are visible
  37606. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37607. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37608. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37609. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37610. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37611. indices.push(idx1);
  37612. indices.push(idx2);
  37613. indices.push(idx3);
  37614. }
  37615. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37616. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37617. indices.push(idx4);
  37618. indices.push(idx1);
  37619. indices.push(idx3);
  37620. }
  37621. }
  37622. }
  37623. // Normals
  37624. VertexData.ComputeNormals(positions, indices, normals);
  37625. // Result
  37626. var vertexData = new VertexData();
  37627. vertexData.indices = indices;
  37628. vertexData.positions = positions;
  37629. vertexData.normals = normals;
  37630. vertexData.uvs = uvs;
  37631. return vertexData;
  37632. };
  37633. /**
  37634. * Creates the VertexData for a Plane
  37635. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37636. * * size sets the width and height of the plane to the value of size, optional default 1
  37637. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37638. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37639. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37640. * * 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)
  37641. * * 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)
  37642. * @returns the VertexData of the box
  37643. */
  37644. VertexData.CreatePlane = function (options) {
  37645. var indices = [];
  37646. var positions = [];
  37647. var normals = [];
  37648. var uvs = [];
  37649. var width = options.width || options.size || 1;
  37650. var height = options.height || options.size || 1;
  37651. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37652. // Vertices
  37653. var halfWidth = width / 2.0;
  37654. var halfHeight = height / 2.0;
  37655. positions.push(-halfWidth, -halfHeight, 0);
  37656. normals.push(0, 0, -1.0);
  37657. uvs.push(0.0, 0.0);
  37658. positions.push(halfWidth, -halfHeight, 0);
  37659. normals.push(0, 0, -1.0);
  37660. uvs.push(1.0, 0.0);
  37661. positions.push(halfWidth, halfHeight, 0);
  37662. normals.push(0, 0, -1.0);
  37663. uvs.push(1.0, 1.0);
  37664. positions.push(-halfWidth, halfHeight, 0);
  37665. normals.push(0, 0, -1.0);
  37666. uvs.push(0.0, 1.0);
  37667. // Indices
  37668. indices.push(0);
  37669. indices.push(1);
  37670. indices.push(2);
  37671. indices.push(0);
  37672. indices.push(2);
  37673. indices.push(3);
  37674. // Sides
  37675. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37676. // Result
  37677. var vertexData = new VertexData();
  37678. vertexData.indices = indices;
  37679. vertexData.positions = positions;
  37680. vertexData.normals = normals;
  37681. vertexData.uvs = uvs;
  37682. return vertexData;
  37683. };
  37684. /**
  37685. * Creates the VertexData of the Disc or regular Polygon
  37686. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37687. * * radius the radius of the disc, optional default 0.5
  37688. * * tessellation the number of polygon sides, optional, default 64
  37689. * * 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
  37690. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37691. * * 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)
  37692. * * 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)
  37693. * @returns the VertexData of the box
  37694. */
  37695. VertexData.CreateDisc = function (options) {
  37696. var positions = new Array();
  37697. var indices = new Array();
  37698. var normals = new Array();
  37699. var uvs = new Array();
  37700. var radius = options.radius || 0.5;
  37701. var tessellation = options.tessellation || 64;
  37702. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37703. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37704. // positions and uvs
  37705. positions.push(0, 0, 0); // disc center first
  37706. uvs.push(0.5, 0.5);
  37707. var theta = Math.PI * 2 * arc;
  37708. var step = theta / tessellation;
  37709. for (var a = 0; a < theta; a += step) {
  37710. var x = Math.cos(a);
  37711. var y = Math.sin(a);
  37712. var u = (x + 1) / 2;
  37713. var v = (1 - y) / 2;
  37714. positions.push(radius * x, radius * y, 0);
  37715. uvs.push(u, v);
  37716. }
  37717. if (arc === 1) {
  37718. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37719. uvs.push(uvs[2], uvs[3]);
  37720. }
  37721. //indices
  37722. var vertexNb = positions.length / 3;
  37723. for (var i = 1; i < vertexNb - 1; i++) {
  37724. indices.push(i + 1, 0, i);
  37725. }
  37726. // result
  37727. VertexData.ComputeNormals(positions, indices, normals);
  37728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37729. var vertexData = new VertexData();
  37730. vertexData.indices = indices;
  37731. vertexData.positions = positions;
  37732. vertexData.normals = normals;
  37733. vertexData.uvs = uvs;
  37734. return vertexData;
  37735. };
  37736. /**
  37737. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37738. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37739. * @param polygon a mesh built from polygonTriangulation.build()
  37740. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37741. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37742. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37743. * @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)
  37744. * @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)
  37745. * @returns the VertexData of the Polygon
  37746. */
  37747. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37748. var faceUV = fUV || new Array(3);
  37749. var faceColors = fColors;
  37750. var colors = [];
  37751. // default face colors and UV if undefined
  37752. for (var f = 0; f < 3; f++) {
  37753. if (faceUV[f] === undefined) {
  37754. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37755. }
  37756. if (faceColors && faceColors[f] === undefined) {
  37757. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37758. }
  37759. }
  37760. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37761. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37762. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37763. var indices = polygon.getIndices();
  37764. // set face colours and textures
  37765. var idx = 0;
  37766. var face = 0;
  37767. for (var index = 0; index < normals.length; index += 3) {
  37768. //Edge Face no. 1
  37769. if (Math.abs(normals[index + 1]) < 0.001) {
  37770. face = 1;
  37771. }
  37772. //Top Face no. 0
  37773. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37774. face = 0;
  37775. }
  37776. //Bottom Face no. 2
  37777. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37778. face = 2;
  37779. }
  37780. idx = index / 3;
  37781. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37782. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37783. if (faceColors) {
  37784. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37785. }
  37786. }
  37787. // sides
  37788. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37789. // Result
  37790. var vertexData = new VertexData();
  37791. vertexData.indices = indices;
  37792. vertexData.positions = positions;
  37793. vertexData.normals = normals;
  37794. vertexData.uvs = uvs;
  37795. if (faceColors) {
  37796. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37797. vertexData.colors = totalColors;
  37798. }
  37799. return vertexData;
  37800. };
  37801. /**
  37802. * Creates the VertexData of the IcoSphere
  37803. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37804. * * radius the radius of the IcoSphere, optional default 1
  37805. * * radiusX allows stretching in the x direction, optional, default radius
  37806. * * radiusY allows stretching in the y direction, optional, default radius
  37807. * * radiusZ allows stretching in the z direction, optional, default radius
  37808. * * flat when true creates a flat shaded mesh, optional, default true
  37809. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37810. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37811. * * 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)
  37812. * * 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)
  37813. * @returns the VertexData of the IcoSphere
  37814. */
  37815. VertexData.CreateIcoSphere = function (options) {
  37816. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37817. var radius = options.radius || 1;
  37818. var flat = (options.flat === undefined) ? true : options.flat;
  37819. var subdivisions = options.subdivisions || 4;
  37820. var radiusX = options.radiusX || radius;
  37821. var radiusY = options.radiusY || radius;
  37822. var radiusZ = options.radiusZ || radius;
  37823. var t = (1 + Math.sqrt(5)) / 2;
  37824. // 12 vertex x,y,z
  37825. var ico_vertices = [
  37826. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37827. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37828. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37829. ];
  37830. // index of 3 vertex makes a face of icopshere
  37831. var ico_indices = [
  37832. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37833. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37834. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37835. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37836. ];
  37837. // vertex for uv have aliased position, not for UV
  37838. var vertices_unalias_id = [
  37839. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37840. // vertex alias
  37841. 0,
  37842. 2,
  37843. 3,
  37844. 3,
  37845. 3,
  37846. 4,
  37847. 7,
  37848. 8,
  37849. 9,
  37850. 9,
  37851. 10,
  37852. 11 // 23: B + 12
  37853. ];
  37854. // uv as integer step (not pixels !)
  37855. var ico_vertexuv = [
  37856. 5, 1, 3, 1, 6, 4, 0, 0,
  37857. 5, 3, 4, 2, 2, 2, 4, 0,
  37858. 2, 0, 1, 1, 6, 0, 6, 2,
  37859. // vertex alias (for same vertex on different faces)
  37860. 0, 4,
  37861. 3, 3,
  37862. 4, 4,
  37863. 3, 1,
  37864. 4, 2,
  37865. 4, 4,
  37866. 0, 2,
  37867. 1, 1,
  37868. 2, 2,
  37869. 3, 3,
  37870. 1, 3,
  37871. 2, 4 // 23: B + 12
  37872. ];
  37873. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37874. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37875. // First island of uv mapping
  37876. // v = 4h 3+ 2
  37877. // v = 3h 9+ 4
  37878. // v = 2h 9+ 5 B
  37879. // v = 1h 9 1 0
  37880. // v = 0h 3 8 7 A
  37881. // u = 0 1 2 3 4 5 6 *a
  37882. // Second island of uv mapping
  37883. // v = 4h 0+ B+ 4+
  37884. // v = 3h A+ 2+
  37885. // v = 2h 7+ 6 3+
  37886. // v = 1h 8+ 3+
  37887. // v = 0h
  37888. // u = 0 1 2 3 4 5 6 *a
  37889. // Face layout on texture UV mapping
  37890. // ============
  37891. // \ 4 /\ 16 / ======
  37892. // \ / \ / /\ 11 /
  37893. // \/ 7 \/ / \ /
  37894. // ======= / 10 \/
  37895. // /\ 17 /\ =======
  37896. // / \ / \ \ 15 /\
  37897. // / 8 \/ 12 \ \ / \
  37898. // ============ \/ 6 \
  37899. // \ 18 /\ ============
  37900. // \ / \ \ 5 /\ 0 /
  37901. // \/ 13 \ \ / \ /
  37902. // ======= \/ 1 \/
  37903. // =============
  37904. // /\ 19 /\ 2 /\
  37905. // / \ / \ / \
  37906. // / 14 \/ 9 \/ 3 \
  37907. // ===================
  37908. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37909. var ustep = 138 / 1024;
  37910. var vstep = 239 / 1024;
  37911. var uoffset = 60 / 1024;
  37912. var voffset = 26 / 1024;
  37913. // Second island should have margin, not to touch the first island
  37914. // avoid any borderline artefact in pixel rounding
  37915. var island_u_offset = -40 / 1024;
  37916. var island_v_offset = +20 / 1024;
  37917. // face is either island 0 or 1 :
  37918. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37919. var island = [
  37920. 0, 0, 0, 0, 1,
  37921. 0, 0, 1, 1, 0,
  37922. 0, 0, 1, 1, 0,
  37923. 0, 1, 1, 1, 0 // 15 - 19
  37924. ];
  37925. var indices = new Array();
  37926. var positions = new Array();
  37927. var normals = new Array();
  37928. var uvs = new Array();
  37929. var current_indice = 0;
  37930. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37931. var face_vertex_pos = new Array(3);
  37932. var face_vertex_uv = new Array(3);
  37933. var v012;
  37934. for (v012 = 0; v012 < 3; v012++) {
  37935. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37936. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37937. }
  37938. // create all with normals
  37939. for (var face = 0; face < 20; face++) {
  37940. // 3 vertex per face
  37941. for (v012 = 0; v012 < 3; v012++) {
  37942. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37943. var v_id = ico_indices[3 * face + v012];
  37944. // vertex have 3D position (x,y,z)
  37945. 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]);
  37946. // Normalize to get normal, then scale to radius
  37947. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37948. // uv Coordinates from vertex ID
  37949. 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);
  37950. }
  37951. // Subdivide the face (interpolate pos, norm, uv)
  37952. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37953. // - norm is linear interpolation of vertex corner normal
  37954. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37955. // - uv is linear interpolation
  37956. //
  37957. // Topology is as below for sub-divide by 2
  37958. // vertex shown as v0,v1,v2
  37959. // interp index is i1 to progress in range [v0,v1[
  37960. // interp index is i2 to progress in range [v0,v2[
  37961. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37962. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37963. //
  37964. //
  37965. // i2 v2
  37966. // ^ ^
  37967. // / / \
  37968. // / / \
  37969. // / / \
  37970. // / / (0,1) \
  37971. // / #---------\
  37972. // / / \ (0,0)'/ \
  37973. // / / \ / \
  37974. // / / \ / \
  37975. // / / (0,0) \ / (1,0) \
  37976. // / #---------#---------\
  37977. // v0 v1
  37978. //
  37979. // --------------------> i1
  37980. //
  37981. // interp of (i1,i2):
  37982. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37983. // along i1 : lerp(x0,x1, i1/(S-i2))
  37984. //
  37985. // centroid of triangle is needed to get help normal computation
  37986. // (c1,c2) are used for centroid location
  37987. var interp_vertex = function (i1, i2, c1, c2) {
  37988. // vertex is interpolated from
  37989. // - face_vertex_pos[0..2]
  37990. // - face_vertex_uv[0..2]
  37991. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37992. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37993. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37994. pos_interp.normalize();
  37995. var vertex_normal;
  37996. if (flat) {
  37997. // in flat mode, recalculate normal as face centroid normal
  37998. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37999. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38000. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38001. }
  38002. else {
  38003. // in smooth mode, recalculate normal from each single vertex position
  38004. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38005. }
  38006. // Vertex normal need correction due to X,Y,Z radius scaling
  38007. vertex_normal.x /= radiusX;
  38008. vertex_normal.y /= radiusY;
  38009. vertex_normal.z /= radiusZ;
  38010. vertex_normal.normalize();
  38011. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38012. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38013. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38014. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38015. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38016. uvs.push(uv_interp.x, uv_interp.y);
  38017. // push each vertex has member of a face
  38018. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38019. indices.push(current_indice);
  38020. current_indice++;
  38021. };
  38022. for (var i2 = 0; i2 < subdivisions; i2++) {
  38023. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38024. // face : (i1,i2) for /\ :
  38025. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38026. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38027. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38028. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38029. if (i1 + i2 + 1 < subdivisions) {
  38030. // face : (i1,i2)' for \/ :
  38031. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38032. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38033. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38034. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38035. }
  38036. }
  38037. }
  38038. }
  38039. // Sides
  38040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38041. // Result
  38042. var vertexData = new VertexData();
  38043. vertexData.indices = indices;
  38044. vertexData.positions = positions;
  38045. vertexData.normals = normals;
  38046. vertexData.uvs = uvs;
  38047. return vertexData;
  38048. };
  38049. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38050. /**
  38051. * Creates the VertexData for a Polyhedron
  38052. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38053. * * type provided types are:
  38054. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38055. * * 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)
  38056. * * size the size of the IcoSphere, optional default 1
  38057. * * sizeX allows stretching in the x direction, optional, default size
  38058. * * sizeY allows stretching in the y direction, optional, default size
  38059. * * sizeZ allows stretching in the z direction, optional, default size
  38060. * * 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
  38061. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38062. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38063. * * flat when true creates a flat shaded mesh, optional, default true
  38064. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38065. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38066. * * 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)
  38067. * * 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)
  38068. * @returns the VertexData of the Polyhedron
  38069. */
  38070. VertexData.CreatePolyhedron = function (options) {
  38071. // provided polyhedron types :
  38072. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38073. // 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)
  38074. var polyhedra = [];
  38075. 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]] };
  38076. 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]] };
  38077. polyhedra[2] = {
  38078. 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]],
  38079. 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]]
  38080. };
  38081. polyhedra[3] = {
  38082. 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]],
  38083. 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]]
  38084. };
  38085. polyhedra[4] = {
  38086. 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]],
  38087. 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]]
  38088. };
  38089. 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]] };
  38090. 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]] };
  38091. 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]] };
  38092. 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]] };
  38093. 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]] };
  38094. 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]] };
  38095. 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]] };
  38096. 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]] };
  38097. 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]] };
  38098. polyhedra[14] = {
  38099. 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]],
  38100. 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]]
  38101. };
  38102. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38103. var size = options.size;
  38104. var sizeX = options.sizeX || size || 1;
  38105. var sizeY = options.sizeY || size || 1;
  38106. var sizeZ = options.sizeZ || size || 1;
  38107. var data = options.custom || polyhedra[type];
  38108. var nbfaces = data.face.length;
  38109. var faceUV = options.faceUV || new Array(nbfaces);
  38110. var faceColors = options.faceColors;
  38111. var flat = (options.flat === undefined) ? true : options.flat;
  38112. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38113. var positions = new Array();
  38114. var indices = new Array();
  38115. var normals = new Array();
  38116. var uvs = new Array();
  38117. var colors = new Array();
  38118. var index = 0;
  38119. var faceIdx = 0; // face cursor in the array "indexes"
  38120. var indexes = new Array();
  38121. var i = 0;
  38122. var f = 0;
  38123. var u, v, ang, x, y, tmp;
  38124. // default face colors and UV if undefined
  38125. if (flat) {
  38126. for (f = 0; f < nbfaces; f++) {
  38127. if (faceColors && faceColors[f] === undefined) {
  38128. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38129. }
  38130. if (faceUV && faceUV[f] === undefined) {
  38131. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38132. }
  38133. }
  38134. }
  38135. if (!flat) {
  38136. for (i = 0; i < data.vertex.length; i++) {
  38137. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38138. uvs.push(0, 0);
  38139. }
  38140. for (f = 0; f < nbfaces; f++) {
  38141. for (i = 0; i < data.face[f].length - 2; i++) {
  38142. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38143. }
  38144. }
  38145. }
  38146. else {
  38147. for (f = 0; f < nbfaces; f++) {
  38148. var fl = data.face[f].length; // number of vertices of the current face
  38149. ang = 2 * Math.PI / fl;
  38150. x = 0.5 * Math.tan(ang / 2);
  38151. y = 0.5;
  38152. // positions, uvs, colors
  38153. for (i = 0; i < fl; i++) {
  38154. // positions
  38155. 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);
  38156. indexes.push(index);
  38157. index++;
  38158. // uvs
  38159. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38160. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38161. uvs.push(u, v);
  38162. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38163. y = x * Math.sin(ang) + y * Math.cos(ang);
  38164. x = tmp;
  38165. // colors
  38166. if (faceColors) {
  38167. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38168. }
  38169. }
  38170. // indices from indexes
  38171. for (i = 0; i < fl - 2; i++) {
  38172. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38173. }
  38174. faceIdx += fl;
  38175. }
  38176. }
  38177. VertexData.ComputeNormals(positions, indices, normals);
  38178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38179. var vertexData = new VertexData();
  38180. vertexData.positions = positions;
  38181. vertexData.indices = indices;
  38182. vertexData.normals = normals;
  38183. vertexData.uvs = uvs;
  38184. if (faceColors && flat) {
  38185. vertexData.colors = colors;
  38186. }
  38187. return vertexData;
  38188. };
  38189. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38190. /**
  38191. * Creates the VertexData for a TorusKnot
  38192. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38193. * * radius the radius of the torus knot, optional, default 2
  38194. * * tube the thickness of the tube, optional, default 0.5
  38195. * * radialSegments the number of sides on each tube segments, optional, default 32
  38196. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38197. * * p the number of windings around the z axis, optional, default 2
  38198. * * q the number of windings around the x axis, optional, default 3
  38199. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38200. * * 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)
  38201. * * 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)
  38202. * @returns the VertexData of the Torus Knot
  38203. */
  38204. VertexData.CreateTorusKnot = function (options) {
  38205. var indices = new Array();
  38206. var positions = new Array();
  38207. var normals = new Array();
  38208. var uvs = new Array();
  38209. var radius = options.radius || 2;
  38210. var tube = options.tube || 0.5;
  38211. var radialSegments = options.radialSegments || 32;
  38212. var tubularSegments = options.tubularSegments || 32;
  38213. var p = options.p || 2;
  38214. var q = options.q || 3;
  38215. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38216. // Helper
  38217. var getPos = function (angle) {
  38218. var cu = Math.cos(angle);
  38219. var su = Math.sin(angle);
  38220. var quOverP = q / p * angle;
  38221. var cs = Math.cos(quOverP);
  38222. var tx = radius * (2 + cs) * 0.5 * cu;
  38223. var ty = radius * (2 + cs) * su * 0.5;
  38224. var tz = radius * Math.sin(quOverP) * 0.5;
  38225. return new BABYLON.Vector3(tx, ty, tz);
  38226. };
  38227. // Vertices
  38228. var i;
  38229. var j;
  38230. for (i = 0; i <= radialSegments; i++) {
  38231. var modI = i % radialSegments;
  38232. var u = modI / radialSegments * 2 * p * Math.PI;
  38233. var p1 = getPos(u);
  38234. var p2 = getPos(u + 0.01);
  38235. var tang = p2.subtract(p1);
  38236. var n = p2.add(p1);
  38237. var bitan = BABYLON.Vector3.Cross(tang, n);
  38238. n = BABYLON.Vector3.Cross(bitan, tang);
  38239. bitan.normalize();
  38240. n.normalize();
  38241. for (j = 0; j < tubularSegments; j++) {
  38242. var modJ = j % tubularSegments;
  38243. var v = modJ / tubularSegments * 2 * Math.PI;
  38244. var cx = -tube * Math.cos(v);
  38245. var cy = tube * Math.sin(v);
  38246. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38247. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38248. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38249. uvs.push(i / radialSegments);
  38250. uvs.push(j / tubularSegments);
  38251. }
  38252. }
  38253. for (i = 0; i < radialSegments; i++) {
  38254. for (j = 0; j < tubularSegments; j++) {
  38255. var jNext = (j + 1) % tubularSegments;
  38256. var a = i * tubularSegments + j;
  38257. var b = (i + 1) * tubularSegments + j;
  38258. var c = (i + 1) * tubularSegments + jNext;
  38259. var d = i * tubularSegments + jNext;
  38260. indices.push(d);
  38261. indices.push(b);
  38262. indices.push(a);
  38263. indices.push(d);
  38264. indices.push(c);
  38265. indices.push(b);
  38266. }
  38267. }
  38268. // Normals
  38269. VertexData.ComputeNormals(positions, indices, normals);
  38270. // Sides
  38271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38272. // Result
  38273. var vertexData = new VertexData();
  38274. vertexData.indices = indices;
  38275. vertexData.positions = positions;
  38276. vertexData.normals = normals;
  38277. vertexData.uvs = uvs;
  38278. return vertexData;
  38279. };
  38280. // Tools
  38281. /**
  38282. * Compute normals for given positions and indices
  38283. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38284. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38285. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38286. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38287. * * facetNormals : optional array of facet normals (vector3)
  38288. * * facetPositions : optional array of facet positions (vector3)
  38289. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38290. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38291. * * bInfo : optional bounding info, required for facetPartitioning computation
  38292. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38293. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38294. * * useRightHandedSystem: optional boolean to for right handed system computation
  38295. * * depthSort : optional boolean to enable the facet depth sort computation
  38296. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38297. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38298. */
  38299. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38300. // temporary scalar variables
  38301. var index = 0; // facet index
  38302. var p1p2x = 0.0; // p1p2 vector x coordinate
  38303. var p1p2y = 0.0; // p1p2 vector y coordinate
  38304. var p1p2z = 0.0; // p1p2 vector z coordinate
  38305. var p3p2x = 0.0; // p3p2 vector x coordinate
  38306. var p3p2y = 0.0; // p3p2 vector y coordinate
  38307. var p3p2z = 0.0; // p3p2 vector z coordinate
  38308. var faceNormalx = 0.0; // facet normal x coordinate
  38309. var faceNormaly = 0.0; // facet normal y coordinate
  38310. var faceNormalz = 0.0; // facet normal z coordinate
  38311. var length = 0.0; // facet normal length before normalization
  38312. var v1x = 0; // vector1 x index in the positions array
  38313. var v1y = 0; // vector1 y index in the positions array
  38314. var v1z = 0; // vector1 z index in the positions array
  38315. var v2x = 0; // vector2 x index in the positions array
  38316. var v2y = 0; // vector2 y index in the positions array
  38317. var v2z = 0; // vector2 z index in the positions array
  38318. var v3x = 0; // vector3 x index in the positions array
  38319. var v3y = 0; // vector3 y index in the positions array
  38320. var v3z = 0; // vector3 z index in the positions array
  38321. var computeFacetNormals = false;
  38322. var computeFacetPositions = false;
  38323. var computeFacetPartitioning = false;
  38324. var computeDepthSort = false;
  38325. var faceNormalSign = 1;
  38326. var ratio = 0;
  38327. var distanceTo = null;
  38328. if (options) {
  38329. computeFacetNormals = (options.facetNormals) ? true : false;
  38330. computeFacetPositions = (options.facetPositions) ? true : false;
  38331. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38332. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38333. ratio = options.ratio || 0;
  38334. computeDepthSort = (options.depthSort) ? true : false;
  38335. distanceTo = (options.distanceTo);
  38336. if (computeDepthSort) {
  38337. if (distanceTo === undefined) {
  38338. distanceTo = BABYLON.Vector3.Zero();
  38339. }
  38340. var depthSortedFacets = options.depthSortedFacets;
  38341. }
  38342. }
  38343. // facetPartitioning reinit if needed
  38344. var xSubRatio = 0;
  38345. var ySubRatio = 0;
  38346. var zSubRatio = 0;
  38347. var subSq = 0;
  38348. if (computeFacetPartitioning && options && options.bbSize) {
  38349. var ox = 0; // X partitioning index for facet position
  38350. var oy = 0; // Y partinioning index for facet position
  38351. var oz = 0; // Z partinioning index for facet position
  38352. var b1x = 0; // X partitioning index for facet v1 vertex
  38353. var b1y = 0; // Y partitioning index for facet v1 vertex
  38354. var b1z = 0; // z partitioning index for facet v1 vertex
  38355. var b2x = 0; // X partitioning index for facet v2 vertex
  38356. var b2y = 0; // Y partitioning index for facet v2 vertex
  38357. var b2z = 0; // Z partitioning index for facet v2 vertex
  38358. var b3x = 0; // X partitioning index for facet v3 vertex
  38359. var b3y = 0; // Y partitioning index for facet v3 vertex
  38360. var b3z = 0; // Z partitioning index for facet v3 vertex
  38361. var block_idx_o = 0; // facet barycenter block index
  38362. var block_idx_v1 = 0; // v1 vertex block index
  38363. var block_idx_v2 = 0; // v2 vertex block index
  38364. var block_idx_v3 = 0; // v3 vertex block index
  38365. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38366. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38367. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38368. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38369. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38370. subSq = options.subDiv.max * options.subDiv.max;
  38371. options.facetPartitioning.length = 0;
  38372. }
  38373. // reset the normals
  38374. for (index = 0; index < positions.length; index++) {
  38375. normals[index] = 0.0;
  38376. }
  38377. // Loop : 1 indice triplet = 1 facet
  38378. var nbFaces = (indices.length / 3) | 0;
  38379. for (index = 0; index < nbFaces; index++) {
  38380. // get the indexes of the coordinates of each vertex of the facet
  38381. v1x = indices[index * 3] * 3;
  38382. v1y = v1x + 1;
  38383. v1z = v1x + 2;
  38384. v2x = indices[index * 3 + 1] * 3;
  38385. v2y = v2x + 1;
  38386. v2z = v2x + 2;
  38387. v3x = indices[index * 3 + 2] * 3;
  38388. v3y = v3x + 1;
  38389. v3z = v3x + 2;
  38390. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38391. p1p2y = positions[v1y] - positions[v2y];
  38392. p1p2z = positions[v1z] - positions[v2z];
  38393. p3p2x = positions[v3x] - positions[v2x];
  38394. p3p2y = positions[v3y] - positions[v2y];
  38395. p3p2z = positions[v3z] - positions[v2z];
  38396. // compute the face normal with the cross product
  38397. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38398. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38399. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38400. // normalize this normal and store it in the array facetData
  38401. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38402. length = (length === 0) ? 1.0 : length;
  38403. faceNormalx /= length;
  38404. faceNormaly /= length;
  38405. faceNormalz /= length;
  38406. if (computeFacetNormals && options) {
  38407. options.facetNormals[index].x = faceNormalx;
  38408. options.facetNormals[index].y = faceNormaly;
  38409. options.facetNormals[index].z = faceNormalz;
  38410. }
  38411. if (computeFacetPositions && options) {
  38412. // compute and the facet barycenter coordinates in the array facetPositions
  38413. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38414. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38415. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38416. }
  38417. if (computeFacetPartitioning && options) {
  38418. // store the facet indexes in arrays in the main facetPartitioning array :
  38419. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38420. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38421. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38422. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38423. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38424. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38425. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38426. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38427. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38428. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38429. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38430. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38431. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38432. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38433. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38434. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38435. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38436. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38437. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38438. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38439. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38440. // push each facet index in each block containing the vertex
  38441. options.facetPartitioning[block_idx_v1].push(index);
  38442. if (block_idx_v2 != block_idx_v1) {
  38443. options.facetPartitioning[block_idx_v2].push(index);
  38444. }
  38445. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38446. options.facetPartitioning[block_idx_v3].push(index);
  38447. }
  38448. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38449. options.facetPartitioning[block_idx_o].push(index);
  38450. }
  38451. }
  38452. if (computeDepthSort && options && options.facetPositions) {
  38453. var dsf = depthSortedFacets[index];
  38454. dsf.ind = index * 3;
  38455. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38456. }
  38457. // compute the normals anyway
  38458. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38459. normals[v1y] += faceNormaly;
  38460. normals[v1z] += faceNormalz;
  38461. normals[v2x] += faceNormalx;
  38462. normals[v2y] += faceNormaly;
  38463. normals[v2z] += faceNormalz;
  38464. normals[v3x] += faceNormalx;
  38465. normals[v3y] += faceNormaly;
  38466. normals[v3z] += faceNormalz;
  38467. }
  38468. // last normalization of each normal
  38469. for (index = 0; index < normals.length / 3; index++) {
  38470. faceNormalx = normals[index * 3];
  38471. faceNormaly = normals[index * 3 + 1];
  38472. faceNormalz = normals[index * 3 + 2];
  38473. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38474. length = (length === 0) ? 1.0 : length;
  38475. faceNormalx /= length;
  38476. faceNormaly /= length;
  38477. faceNormalz /= length;
  38478. normals[index * 3] = faceNormalx;
  38479. normals[index * 3 + 1] = faceNormaly;
  38480. normals[index * 3 + 2] = faceNormalz;
  38481. }
  38482. };
  38483. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38484. var li = indices.length;
  38485. var ln = normals.length;
  38486. var i;
  38487. var n;
  38488. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38489. switch (sideOrientation) {
  38490. case BABYLON.Mesh.FRONTSIDE:
  38491. // nothing changed
  38492. break;
  38493. case BABYLON.Mesh.BACKSIDE:
  38494. var tmp;
  38495. // indices
  38496. for (i = 0; i < li; i += 3) {
  38497. tmp = indices[i];
  38498. indices[i] = indices[i + 2];
  38499. indices[i + 2] = tmp;
  38500. }
  38501. // normals
  38502. for (n = 0; n < ln; n++) {
  38503. normals[n] = -normals[n];
  38504. }
  38505. break;
  38506. case BABYLON.Mesh.DOUBLESIDE:
  38507. // positions
  38508. var lp = positions.length;
  38509. var l = lp / 3;
  38510. for (var p = 0; p < lp; p++) {
  38511. positions[lp + p] = positions[p];
  38512. }
  38513. // indices
  38514. for (i = 0; i < li; i += 3) {
  38515. indices[i + li] = indices[i + 2] + l;
  38516. indices[i + 1 + li] = indices[i + 1] + l;
  38517. indices[i + 2 + li] = indices[i] + l;
  38518. }
  38519. // normals
  38520. for (n = 0; n < ln; n++) {
  38521. normals[ln + n] = -normals[n];
  38522. }
  38523. // uvs
  38524. var lu = uvs.length;
  38525. var u = 0;
  38526. for (u = 0; u < lu; u++) {
  38527. uvs[u + lu] = uvs[u];
  38528. }
  38529. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38530. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38531. u = 0;
  38532. for (i = 0; i < lu / 2; i++) {
  38533. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38534. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38535. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38536. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38537. u += 2;
  38538. }
  38539. break;
  38540. }
  38541. };
  38542. /**
  38543. * Applies VertexData created from the imported parameters to the geometry
  38544. * @param parsedVertexData the parsed data from an imported file
  38545. * @param geometry the geometry to apply the VertexData to
  38546. */
  38547. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38548. var vertexData = new VertexData();
  38549. // positions
  38550. var positions = parsedVertexData.positions;
  38551. if (positions) {
  38552. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38553. }
  38554. // normals
  38555. var normals = parsedVertexData.normals;
  38556. if (normals) {
  38557. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38558. }
  38559. // tangents
  38560. var tangents = parsedVertexData.tangents;
  38561. if (tangents) {
  38562. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38563. }
  38564. // uvs
  38565. var uvs = parsedVertexData.uvs;
  38566. if (uvs) {
  38567. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38568. }
  38569. // uv2s
  38570. var uv2s = parsedVertexData.uv2s;
  38571. if (uv2s) {
  38572. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38573. }
  38574. // uv3s
  38575. var uv3s = parsedVertexData.uv3s;
  38576. if (uv3s) {
  38577. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38578. }
  38579. // uv4s
  38580. var uv4s = parsedVertexData.uv4s;
  38581. if (uv4s) {
  38582. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38583. }
  38584. // uv5s
  38585. var uv5s = parsedVertexData.uv5s;
  38586. if (uv5s) {
  38587. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38588. }
  38589. // uv6s
  38590. var uv6s = parsedVertexData.uv6s;
  38591. if (uv6s) {
  38592. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38593. }
  38594. // colors
  38595. var colors = parsedVertexData.colors;
  38596. if (colors) {
  38597. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38598. }
  38599. // matricesIndices
  38600. var matricesIndices = parsedVertexData.matricesIndices;
  38601. if (matricesIndices) {
  38602. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38603. }
  38604. // matricesWeights
  38605. var matricesWeights = parsedVertexData.matricesWeights;
  38606. if (matricesWeights) {
  38607. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38608. }
  38609. // indices
  38610. var indices = parsedVertexData.indices;
  38611. if (indices) {
  38612. vertexData.indices = indices;
  38613. }
  38614. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38615. };
  38616. return VertexData;
  38617. }());
  38618. BABYLON.VertexData = VertexData;
  38619. })(BABYLON || (BABYLON = {}));
  38620. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38621. var BABYLON;
  38622. (function (BABYLON) {
  38623. /**
  38624. * Class used to store geometry data (vertex buffers + index buffer)
  38625. */
  38626. var Geometry = /** @class */ (function () {
  38627. /**
  38628. * Creates a new geometry
  38629. * @param id defines the unique ID
  38630. * @param scene defines the hosting scene
  38631. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38632. * @param updatable defines if geometry must be updatable (false by default)
  38633. * @param mesh defines the mesh that will be associated with the geometry
  38634. */
  38635. function Geometry(id, scene, vertexData, updatable, mesh) {
  38636. if (updatable === void 0) { updatable = false; }
  38637. if (mesh === void 0) { mesh = null; }
  38638. /**
  38639. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38640. */
  38641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38642. this._totalVertices = 0;
  38643. this._isDisposed = false;
  38644. this._indexBufferIsUpdatable = false;
  38645. this.id = id;
  38646. this._engine = scene.getEngine();
  38647. this._meshes = [];
  38648. this._scene = scene;
  38649. //Init vertex buffer cache
  38650. this._vertexBuffers = {};
  38651. this._indices = [];
  38652. this._updatable = updatable;
  38653. // vertexData
  38654. if (vertexData) {
  38655. this.setAllVerticesData(vertexData, updatable);
  38656. }
  38657. else {
  38658. this._totalVertices = 0;
  38659. this._indices = [];
  38660. }
  38661. if (this._engine.getCaps().vertexArrayObject) {
  38662. this._vertexArrayObjects = {};
  38663. }
  38664. // applyToMesh
  38665. if (mesh) {
  38666. if (mesh.getClassName() === "LinesMesh") {
  38667. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38668. this._updateExtend();
  38669. }
  38670. this.applyToMesh(mesh);
  38671. mesh.computeWorldMatrix(true);
  38672. }
  38673. }
  38674. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38675. /**
  38676. * 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
  38677. */
  38678. get: function () {
  38679. return this._boundingBias;
  38680. },
  38681. /**
  38682. * 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
  38683. */
  38684. set: function (value) {
  38685. if (this._boundingBias && this._boundingBias.equals(value)) {
  38686. return;
  38687. }
  38688. this._boundingBias = value.clone();
  38689. this._updateBoundingInfo(true, null);
  38690. },
  38691. enumerable: true,
  38692. configurable: true
  38693. });
  38694. /**
  38695. * Static function used to attach a new empty geometry to a mesh
  38696. * @param mesh defines the mesh to attach the geometry to
  38697. * @returns the new {BABYLON.Geometry}
  38698. */
  38699. Geometry.CreateGeometryForMesh = function (mesh) {
  38700. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38701. geometry.applyToMesh(mesh);
  38702. return geometry;
  38703. };
  38704. Object.defineProperty(Geometry.prototype, "extend", {
  38705. /**
  38706. * Gets the current extend of the geometry
  38707. */
  38708. get: function () {
  38709. return this._extend;
  38710. },
  38711. enumerable: true,
  38712. configurable: true
  38713. });
  38714. /**
  38715. * Gets the hosting scene
  38716. * @returns the hosting {BABYLON.Scene}
  38717. */
  38718. Geometry.prototype.getScene = function () {
  38719. return this._scene;
  38720. };
  38721. /**
  38722. * Gets the hosting engine
  38723. * @returns the hosting {BABYLON.Engine}
  38724. */
  38725. Geometry.prototype.getEngine = function () {
  38726. return this._engine;
  38727. };
  38728. /**
  38729. * Defines if the geometry is ready to use
  38730. * @returns true if the geometry is ready to be used
  38731. */
  38732. Geometry.prototype.isReady = function () {
  38733. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38734. };
  38735. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38736. /**
  38737. * Gets a value indicating that the geometry should not be serialized
  38738. */
  38739. get: function () {
  38740. for (var index = 0; index < this._meshes.length; index++) {
  38741. if (!this._meshes[index].doNotSerialize) {
  38742. return false;
  38743. }
  38744. }
  38745. return true;
  38746. },
  38747. enumerable: true,
  38748. configurable: true
  38749. });
  38750. /** @hidden */
  38751. Geometry.prototype._rebuild = function () {
  38752. if (this._vertexArrayObjects) {
  38753. this._vertexArrayObjects = {};
  38754. }
  38755. // Index buffer
  38756. if (this._meshes.length !== 0 && this._indices) {
  38757. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38758. }
  38759. // Vertex buffers
  38760. for (var key in this._vertexBuffers) {
  38761. var vertexBuffer = this._vertexBuffers[key];
  38762. vertexBuffer._rebuild();
  38763. }
  38764. };
  38765. /**
  38766. * Affects all geometry data in one call
  38767. * @param vertexData defines the geometry data
  38768. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38769. */
  38770. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38771. vertexData.applyToGeometry(this, updatable);
  38772. this.notifyUpdate();
  38773. };
  38774. /**
  38775. * Set specific vertex data
  38776. * @param kind defines the data kind (Position, normal, etc...)
  38777. * @param data defines the vertex data to use
  38778. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38779. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38780. */
  38781. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38782. if (updatable === void 0) { updatable = false; }
  38783. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38784. this.setVerticesBuffer(buffer);
  38785. };
  38786. /**
  38787. * Removes a specific vertex data
  38788. * @param kind defines the data kind (Position, normal, etc...)
  38789. */
  38790. Geometry.prototype.removeVerticesData = function (kind) {
  38791. if (this._vertexBuffers[kind]) {
  38792. this._vertexBuffers[kind].dispose();
  38793. delete this._vertexBuffers[kind];
  38794. }
  38795. };
  38796. /**
  38797. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38798. * @param buffer defines the vertex buffer to use
  38799. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38800. */
  38801. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38802. if (totalVertices === void 0) { totalVertices = null; }
  38803. var kind = buffer.getKind();
  38804. if (this._vertexBuffers[kind]) {
  38805. this._vertexBuffers[kind].dispose();
  38806. }
  38807. this._vertexBuffers[kind] = buffer;
  38808. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38809. var data = buffer.getData();
  38810. if (totalVertices != null) {
  38811. this._totalVertices = totalVertices;
  38812. }
  38813. else {
  38814. if (data != null) {
  38815. this._totalVertices = data.length / (buffer.byteStride / 4);
  38816. }
  38817. }
  38818. this._updateExtend(data);
  38819. this._resetPointsArrayCache();
  38820. var meshes = this._meshes;
  38821. var numOfMeshes = meshes.length;
  38822. for (var index = 0; index < numOfMeshes; index++) {
  38823. var mesh = meshes[index];
  38824. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38825. mesh._createGlobalSubMesh(false);
  38826. mesh.computeWorldMatrix(true);
  38827. }
  38828. }
  38829. this.notifyUpdate(kind);
  38830. if (this._vertexArrayObjects) {
  38831. this._disposeVertexArrayObjects();
  38832. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38833. }
  38834. };
  38835. /**
  38836. * Update a specific vertex buffer
  38837. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38838. * It will do nothing if the buffer is not updatable
  38839. * @param kind defines the data kind (Position, normal, etc...)
  38840. * @param data defines the data to use
  38841. * @param offset defines the offset in the target buffer where to store the data
  38842. * @param useBytes set to true if the offset is in bytes
  38843. */
  38844. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38845. if (useBytes === void 0) { useBytes = false; }
  38846. var vertexBuffer = this.getVertexBuffer(kind);
  38847. if (!vertexBuffer) {
  38848. return;
  38849. }
  38850. vertexBuffer.updateDirectly(data, offset, useBytes);
  38851. this.notifyUpdate(kind);
  38852. };
  38853. /**
  38854. * Update a specific vertex buffer
  38855. * This function will create a new buffer if the current one is not updatable
  38856. * @param kind defines the data kind (Position, normal, etc...)
  38857. * @param data defines the data to use
  38858. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38859. */
  38860. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38861. if (updateExtends === void 0) { updateExtends = false; }
  38862. var vertexBuffer = this.getVertexBuffer(kind);
  38863. if (!vertexBuffer) {
  38864. return;
  38865. }
  38866. vertexBuffer.update(data);
  38867. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38868. this._updateBoundingInfo(updateExtends, data);
  38869. }
  38870. this.notifyUpdate(kind);
  38871. };
  38872. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38873. if (updateExtends) {
  38874. this._updateExtend(data);
  38875. }
  38876. var meshes = this._meshes;
  38877. var numOfMeshes = meshes.length;
  38878. this._resetPointsArrayCache();
  38879. for (var index = 0; index < numOfMeshes; index++) {
  38880. var mesh = meshes[index];
  38881. if (updateExtends) {
  38882. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38883. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38884. var subMesh = mesh.subMeshes[subIndex];
  38885. subMesh.refreshBoundingInfo();
  38886. }
  38887. }
  38888. }
  38889. };
  38890. /** @hidden */
  38891. Geometry.prototype._bind = function (effect, indexToBind) {
  38892. if (!effect) {
  38893. return;
  38894. }
  38895. if (indexToBind === undefined) {
  38896. indexToBind = this._indexBuffer;
  38897. }
  38898. var vbs = this.getVertexBuffers();
  38899. if (!vbs) {
  38900. return;
  38901. }
  38902. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38903. this._engine.bindBuffers(vbs, indexToBind, effect);
  38904. return;
  38905. }
  38906. // Using VAO
  38907. if (!this._vertexArrayObjects[effect.key]) {
  38908. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38909. }
  38910. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38911. };
  38912. /**
  38913. * Gets total number of vertices
  38914. * @returns the total number of vertices
  38915. */
  38916. Geometry.prototype.getTotalVertices = function () {
  38917. if (!this.isReady()) {
  38918. return 0;
  38919. }
  38920. return this._totalVertices;
  38921. };
  38922. /**
  38923. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38924. * @param kind defines the data kind (Position, normal, etc...)
  38925. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38926. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38927. * @returns a float array containing vertex data
  38928. */
  38929. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38930. var vertexBuffer = this.getVertexBuffer(kind);
  38931. if (!vertexBuffer) {
  38932. return null;
  38933. }
  38934. var data = vertexBuffer.getData();
  38935. if (!data) {
  38936. return null;
  38937. }
  38938. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38939. var count = this._totalVertices * vertexBuffer.getSize();
  38940. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38941. var copy_1 = new Array(count);
  38942. vertexBuffer.forEach(count, function (value, index) {
  38943. copy_1[index] = value;
  38944. });
  38945. return copy_1;
  38946. }
  38947. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38948. if (data instanceof Array) {
  38949. var offset = vertexBuffer.byteOffset / 4;
  38950. return BABYLON.Tools.Slice(data, offset, offset + count);
  38951. }
  38952. else if (data instanceof ArrayBuffer) {
  38953. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38954. }
  38955. else {
  38956. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38957. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38958. var result = new Float32Array(count);
  38959. var source = new Float32Array(data.buffer, offset, count);
  38960. result.set(source);
  38961. return result;
  38962. }
  38963. return new Float32Array(data.buffer, offset, count);
  38964. }
  38965. }
  38966. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38967. return BABYLON.Tools.Slice(data);
  38968. }
  38969. return data;
  38970. };
  38971. /**
  38972. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38973. * @param kind defines the data kind (Position, normal, etc...)
  38974. * @returns true if the vertex buffer with the specified kind is updatable
  38975. */
  38976. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38977. var vb = this._vertexBuffers[kind];
  38978. if (!vb) {
  38979. return false;
  38980. }
  38981. return vb.isUpdatable();
  38982. };
  38983. /**
  38984. * Gets a specific vertex buffer
  38985. * @param kind defines the data kind (Position, normal, etc...)
  38986. * @returns a {BABYLON.VertexBuffer}
  38987. */
  38988. Geometry.prototype.getVertexBuffer = function (kind) {
  38989. if (!this.isReady()) {
  38990. return null;
  38991. }
  38992. return this._vertexBuffers[kind];
  38993. };
  38994. /**
  38995. * Returns all vertex buffers
  38996. * @return an object holding all vertex buffers indexed by kind
  38997. */
  38998. Geometry.prototype.getVertexBuffers = function () {
  38999. if (!this.isReady()) {
  39000. return null;
  39001. }
  39002. return this._vertexBuffers;
  39003. };
  39004. /**
  39005. * Gets a boolean indicating if specific vertex buffer is present
  39006. * @param kind defines the data kind (Position, normal, etc...)
  39007. * @returns true if data is present
  39008. */
  39009. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39010. if (!this._vertexBuffers) {
  39011. if (this._delayInfo) {
  39012. return this._delayInfo.indexOf(kind) !== -1;
  39013. }
  39014. return false;
  39015. }
  39016. return this._vertexBuffers[kind] !== undefined;
  39017. };
  39018. /**
  39019. * Gets a list of all attached data kinds (Position, normal, etc...)
  39020. * @returns a list of string containing all kinds
  39021. */
  39022. Geometry.prototype.getVerticesDataKinds = function () {
  39023. var result = [];
  39024. var kind;
  39025. if (!this._vertexBuffers && this._delayInfo) {
  39026. for (kind in this._delayInfo) {
  39027. result.push(kind);
  39028. }
  39029. }
  39030. else {
  39031. for (kind in this._vertexBuffers) {
  39032. result.push(kind);
  39033. }
  39034. }
  39035. return result;
  39036. };
  39037. /**
  39038. * Update index buffer
  39039. * @param indices defines the indices to store in the index buffer
  39040. * @param offset defines the offset in the target buffer where to store the data
  39041. */
  39042. Geometry.prototype.updateIndices = function (indices, offset) {
  39043. if (!this._indexBuffer) {
  39044. return;
  39045. }
  39046. if (!this._indexBufferIsUpdatable) {
  39047. this.setIndices(indices, null, true);
  39048. }
  39049. else {
  39050. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39051. }
  39052. };
  39053. /**
  39054. * Creates a new index buffer
  39055. * @param indices defines the indices to store in the index buffer
  39056. * @param totalVertices defines the total number of vertices (could be null)
  39057. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39058. */
  39059. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39060. if (totalVertices === void 0) { totalVertices = null; }
  39061. if (updatable === void 0) { updatable = false; }
  39062. if (this._indexBuffer) {
  39063. this._engine._releaseBuffer(this._indexBuffer);
  39064. }
  39065. this._disposeVertexArrayObjects();
  39066. this._indices = indices;
  39067. this._indexBufferIsUpdatable = updatable;
  39068. if (this._meshes.length !== 0 && this._indices) {
  39069. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39070. }
  39071. if (totalVertices != undefined) { // including null and undefined
  39072. this._totalVertices = totalVertices;
  39073. }
  39074. var meshes = this._meshes;
  39075. var numOfMeshes = meshes.length;
  39076. for (var index = 0; index < numOfMeshes; index++) {
  39077. meshes[index]._createGlobalSubMesh(true);
  39078. }
  39079. this.notifyUpdate();
  39080. };
  39081. /**
  39082. * Return the total number of indices
  39083. * @returns the total number of indices
  39084. */
  39085. Geometry.prototype.getTotalIndices = function () {
  39086. if (!this.isReady()) {
  39087. return 0;
  39088. }
  39089. return this._indices.length;
  39090. };
  39091. /**
  39092. * Gets the index buffer array
  39093. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39094. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39095. * @returns the index buffer array
  39096. */
  39097. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39098. if (!this.isReady()) {
  39099. return null;
  39100. }
  39101. var orig = this._indices;
  39102. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39103. return orig;
  39104. }
  39105. else {
  39106. var len = orig.length;
  39107. var copy = [];
  39108. for (var i = 0; i < len; i++) {
  39109. copy.push(orig[i]);
  39110. }
  39111. return copy;
  39112. }
  39113. };
  39114. /**
  39115. * Gets the index buffer
  39116. * @return the index buffer
  39117. */
  39118. Geometry.prototype.getIndexBuffer = function () {
  39119. if (!this.isReady()) {
  39120. return null;
  39121. }
  39122. return this._indexBuffer;
  39123. };
  39124. /** @hidden */
  39125. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39126. if (effect === void 0) { effect = null; }
  39127. if (!effect || !this._vertexArrayObjects) {
  39128. return;
  39129. }
  39130. if (this._vertexArrayObjects[effect.key]) {
  39131. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39132. delete this._vertexArrayObjects[effect.key];
  39133. }
  39134. };
  39135. /**
  39136. * Release the associated resources for a specific mesh
  39137. * @param mesh defines the source mesh
  39138. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39139. */
  39140. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39141. var meshes = this._meshes;
  39142. var index = meshes.indexOf(mesh);
  39143. if (index === -1) {
  39144. return;
  39145. }
  39146. meshes.splice(index, 1);
  39147. mesh._geometry = null;
  39148. if (meshes.length === 0 && shouldDispose) {
  39149. this.dispose();
  39150. }
  39151. };
  39152. /**
  39153. * Apply current geometry to a given mesh
  39154. * @param mesh defines the mesh to apply geometry to
  39155. */
  39156. Geometry.prototype.applyToMesh = function (mesh) {
  39157. if (mesh._geometry === this) {
  39158. return;
  39159. }
  39160. var previousGeometry = mesh._geometry;
  39161. if (previousGeometry) {
  39162. previousGeometry.releaseForMesh(mesh);
  39163. }
  39164. var meshes = this._meshes;
  39165. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39166. mesh._geometry = this;
  39167. this._scene.pushGeometry(this);
  39168. meshes.push(mesh);
  39169. if (this.isReady()) {
  39170. this._applyToMesh(mesh);
  39171. }
  39172. else {
  39173. mesh._boundingInfo = this._boundingInfo;
  39174. }
  39175. };
  39176. Geometry.prototype._updateExtend = function (data) {
  39177. if (data === void 0) { data = null; }
  39178. if (!data) {
  39179. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39180. }
  39181. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39182. };
  39183. Geometry.prototype._applyToMesh = function (mesh) {
  39184. var numOfMeshes = this._meshes.length;
  39185. // vertexBuffers
  39186. for (var kind in this._vertexBuffers) {
  39187. if (numOfMeshes === 1) {
  39188. this._vertexBuffers[kind].create();
  39189. }
  39190. var buffer = this._vertexBuffers[kind].getBuffer();
  39191. if (buffer)
  39192. buffer.references = numOfMeshes;
  39193. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39194. if (!this._extend) {
  39195. this._updateExtend();
  39196. }
  39197. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39198. mesh._createGlobalSubMesh(false);
  39199. //bounding info was just created again, world matrix should be applied again.
  39200. mesh._updateBoundingInfo();
  39201. }
  39202. }
  39203. // indexBuffer
  39204. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39205. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39206. }
  39207. if (this._indexBuffer) {
  39208. this._indexBuffer.references = numOfMeshes;
  39209. }
  39210. };
  39211. Geometry.prototype.notifyUpdate = function (kind) {
  39212. if (this.onGeometryUpdated) {
  39213. this.onGeometryUpdated(this, kind);
  39214. }
  39215. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39216. var mesh = _a[_i];
  39217. mesh._markSubMeshesAsAttributesDirty();
  39218. }
  39219. };
  39220. /**
  39221. * Load the geometry if it was flagged as delay loaded
  39222. * @param scene defines the hosting scene
  39223. * @param onLoaded defines a callback called when the geometry is loaded
  39224. */
  39225. Geometry.prototype.load = function (scene, onLoaded) {
  39226. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39227. return;
  39228. }
  39229. if (this.isReady()) {
  39230. if (onLoaded) {
  39231. onLoaded();
  39232. }
  39233. return;
  39234. }
  39235. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39236. this._queueLoad(scene, onLoaded);
  39237. };
  39238. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39239. var _this = this;
  39240. if (!this.delayLoadingFile) {
  39241. return;
  39242. }
  39243. scene._addPendingData(this);
  39244. scene._loadFile(this.delayLoadingFile, function (data) {
  39245. if (!_this._delayLoadingFunction) {
  39246. return;
  39247. }
  39248. _this._delayLoadingFunction(JSON.parse(data), _this);
  39249. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39250. _this._delayInfo = [];
  39251. scene._removePendingData(_this);
  39252. var meshes = _this._meshes;
  39253. var numOfMeshes = meshes.length;
  39254. for (var index = 0; index < numOfMeshes; index++) {
  39255. _this._applyToMesh(meshes[index]);
  39256. }
  39257. if (onLoaded) {
  39258. onLoaded();
  39259. }
  39260. }, undefined, true);
  39261. };
  39262. /**
  39263. * Invert the geometry to move from a right handed system to a left handed one.
  39264. */
  39265. Geometry.prototype.toLeftHanded = function () {
  39266. // Flip faces
  39267. var tIndices = this.getIndices(false);
  39268. if (tIndices != null && tIndices.length > 0) {
  39269. for (var i = 0; i < tIndices.length; i += 3) {
  39270. var tTemp = tIndices[i + 0];
  39271. tIndices[i + 0] = tIndices[i + 2];
  39272. tIndices[i + 2] = tTemp;
  39273. }
  39274. this.setIndices(tIndices);
  39275. }
  39276. // Negate position.z
  39277. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39278. if (tPositions != null && tPositions.length > 0) {
  39279. for (var i = 0; i < tPositions.length; i += 3) {
  39280. tPositions[i + 2] = -tPositions[i + 2];
  39281. }
  39282. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39283. }
  39284. // Negate normal.z
  39285. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39286. if (tNormals != null && tNormals.length > 0) {
  39287. for (var i = 0; i < tNormals.length; i += 3) {
  39288. tNormals[i + 2] = -tNormals[i + 2];
  39289. }
  39290. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39291. }
  39292. };
  39293. // Cache
  39294. /** @hidden */
  39295. Geometry.prototype._resetPointsArrayCache = function () {
  39296. this._positions = null;
  39297. };
  39298. /** @hidden */
  39299. Geometry.prototype._generatePointsArray = function () {
  39300. if (this._positions)
  39301. return true;
  39302. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39303. if (!data || data.length === 0) {
  39304. return false;
  39305. }
  39306. this._positions = [];
  39307. for (var index = 0; index < data.length; index += 3) {
  39308. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39309. }
  39310. return true;
  39311. };
  39312. /**
  39313. * Gets a value indicating if the geometry is disposed
  39314. * @returns true if the geometry was disposed
  39315. */
  39316. Geometry.prototype.isDisposed = function () {
  39317. return this._isDisposed;
  39318. };
  39319. Geometry.prototype._disposeVertexArrayObjects = function () {
  39320. if (this._vertexArrayObjects) {
  39321. for (var kind in this._vertexArrayObjects) {
  39322. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39323. }
  39324. this._vertexArrayObjects = {};
  39325. }
  39326. };
  39327. /**
  39328. * Free all associated resources
  39329. */
  39330. Geometry.prototype.dispose = function () {
  39331. var meshes = this._meshes;
  39332. var numOfMeshes = meshes.length;
  39333. var index;
  39334. for (index = 0; index < numOfMeshes; index++) {
  39335. this.releaseForMesh(meshes[index]);
  39336. }
  39337. this._meshes = [];
  39338. this._disposeVertexArrayObjects();
  39339. for (var kind in this._vertexBuffers) {
  39340. this._vertexBuffers[kind].dispose();
  39341. }
  39342. this._vertexBuffers = {};
  39343. this._totalVertices = 0;
  39344. if (this._indexBuffer) {
  39345. this._engine._releaseBuffer(this._indexBuffer);
  39346. }
  39347. this._indexBuffer = null;
  39348. this._indices = [];
  39349. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39350. this.delayLoadingFile = null;
  39351. this._delayLoadingFunction = null;
  39352. this._delayInfo = [];
  39353. this._boundingInfo = null;
  39354. this._scene.removeGeometry(this);
  39355. this._isDisposed = true;
  39356. };
  39357. /**
  39358. * Clone the current geometry into a new geometry
  39359. * @param id defines the unique ID of the new geometry
  39360. * @returns a new geometry object
  39361. */
  39362. Geometry.prototype.copy = function (id) {
  39363. var vertexData = new BABYLON.VertexData();
  39364. vertexData.indices = [];
  39365. var indices = this.getIndices();
  39366. if (indices) {
  39367. for (var index = 0; index < indices.length; index++) {
  39368. vertexData.indices.push(indices[index]);
  39369. }
  39370. }
  39371. var updatable = false;
  39372. var stopChecking = false;
  39373. var kind;
  39374. for (kind in this._vertexBuffers) {
  39375. // using slice() to make a copy of the array and not just reference it
  39376. var data = this.getVerticesData(kind);
  39377. if (data instanceof Float32Array) {
  39378. vertexData.set(new Float32Array(data), kind);
  39379. }
  39380. else {
  39381. vertexData.set(data.slice(0), kind);
  39382. }
  39383. if (!stopChecking) {
  39384. var vb = this.getVertexBuffer(kind);
  39385. if (vb) {
  39386. updatable = vb.isUpdatable();
  39387. stopChecking = !updatable;
  39388. }
  39389. }
  39390. }
  39391. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39392. geometry.delayLoadState = this.delayLoadState;
  39393. geometry.delayLoadingFile = this.delayLoadingFile;
  39394. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39395. for (kind in this._delayInfo) {
  39396. geometry._delayInfo = geometry._delayInfo || [];
  39397. geometry._delayInfo.push(kind);
  39398. }
  39399. // Bounding info
  39400. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39401. return geometry;
  39402. };
  39403. /**
  39404. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39405. * @return a JSON representation of the current geometry data (without the vertices data)
  39406. */
  39407. Geometry.prototype.serialize = function () {
  39408. var serializationObject = {};
  39409. serializationObject.id = this.id;
  39410. serializationObject.updatable = this._updatable;
  39411. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39412. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39413. }
  39414. return serializationObject;
  39415. };
  39416. Geometry.prototype.toNumberArray = function (origin) {
  39417. if (Array.isArray(origin)) {
  39418. return origin;
  39419. }
  39420. else {
  39421. return Array.prototype.slice.call(origin);
  39422. }
  39423. };
  39424. /**
  39425. * Serialize all vertices data into a JSON oject
  39426. * @returns a JSON representation of the current geometry data
  39427. */
  39428. Geometry.prototype.serializeVerticeData = function () {
  39429. var serializationObject = this.serialize();
  39430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39431. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39433. serializationObject.positions._updatable = true;
  39434. }
  39435. }
  39436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39437. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39438. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39439. serializationObject.normals._updatable = true;
  39440. }
  39441. }
  39442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39443. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39444. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39445. serializationObject.tangets._updatable = true;
  39446. }
  39447. }
  39448. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39449. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39450. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39451. serializationObject.uvs._updatable = true;
  39452. }
  39453. }
  39454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39455. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39456. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39457. serializationObject.uv2s._updatable = true;
  39458. }
  39459. }
  39460. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39461. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39462. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39463. serializationObject.uv3s._updatable = true;
  39464. }
  39465. }
  39466. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39467. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39468. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39469. serializationObject.uv4s._updatable = true;
  39470. }
  39471. }
  39472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39473. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39474. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39475. serializationObject.uv5s._updatable = true;
  39476. }
  39477. }
  39478. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39479. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39480. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39481. serializationObject.uv6s._updatable = true;
  39482. }
  39483. }
  39484. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39485. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39486. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39487. serializationObject.colors._updatable = true;
  39488. }
  39489. }
  39490. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39491. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39492. serializationObject.matricesIndices._isExpanded = true;
  39493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39494. serializationObject.matricesIndices._updatable = true;
  39495. }
  39496. }
  39497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39498. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39499. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39500. serializationObject.matricesWeights._updatable = true;
  39501. }
  39502. }
  39503. serializationObject.indices = this.toNumberArray(this.getIndices());
  39504. return serializationObject;
  39505. };
  39506. // Statics
  39507. /**
  39508. * Extracts a clone of a mesh geometry
  39509. * @param mesh defines the source mesh
  39510. * @param id defines the unique ID of the new geometry object
  39511. * @returns the new geometry object
  39512. */
  39513. Geometry.ExtractFromMesh = function (mesh, id) {
  39514. var geometry = mesh._geometry;
  39515. if (!geometry) {
  39516. return null;
  39517. }
  39518. return geometry.copy(id);
  39519. };
  39520. /**
  39521. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39522. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39523. * Be aware Math.random() could cause collisions, but:
  39524. * "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"
  39525. * @returns a string containing a new GUID
  39526. */
  39527. Geometry.RandomId = function () {
  39528. return BABYLON.Tools.RandomId();
  39529. };
  39530. /** @hidden */
  39531. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39532. var scene = mesh.getScene();
  39533. // Geometry
  39534. var geometryId = parsedGeometry.geometryId;
  39535. if (geometryId) {
  39536. var geometry = scene.getGeometryByID(geometryId);
  39537. if (geometry) {
  39538. geometry.applyToMesh(mesh);
  39539. }
  39540. }
  39541. else if (parsedGeometry instanceof ArrayBuffer) {
  39542. var binaryInfo = mesh._binaryInfo;
  39543. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39544. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39545. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39546. }
  39547. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39548. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39550. }
  39551. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39552. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39554. }
  39555. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39556. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39558. }
  39559. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39560. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39562. }
  39563. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39564. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39566. }
  39567. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39568. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39569. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39570. }
  39571. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39572. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39574. }
  39575. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39576. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39578. }
  39579. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39580. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39582. }
  39583. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39584. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39585. var floatIndices = [];
  39586. for (var i = 0; i < matricesIndicesData.length; i++) {
  39587. var index = matricesIndicesData[i];
  39588. floatIndices.push(index & 0x000000FF);
  39589. floatIndices.push((index & 0x0000FF00) >> 8);
  39590. floatIndices.push((index & 0x00FF0000) >> 16);
  39591. floatIndices.push(index >> 24);
  39592. }
  39593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39594. }
  39595. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39596. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39598. }
  39599. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39600. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39601. mesh.setIndices(indicesData, null);
  39602. }
  39603. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39604. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39605. mesh.subMeshes = [];
  39606. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39607. var materialIndex = subMeshesData[(i * 5) + 0];
  39608. var verticesStart = subMeshesData[(i * 5) + 1];
  39609. var verticesCount = subMeshesData[(i * 5) + 2];
  39610. var indexStart = subMeshesData[(i * 5) + 3];
  39611. var indexCount = subMeshesData[(i * 5) + 4];
  39612. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39613. }
  39614. }
  39615. }
  39616. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39617. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39618. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39619. if (parsedGeometry.tangents) {
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39621. }
  39622. if (parsedGeometry.uvs) {
  39623. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39624. }
  39625. if (parsedGeometry.uvs2) {
  39626. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39627. }
  39628. if (parsedGeometry.uvs3) {
  39629. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39630. }
  39631. if (parsedGeometry.uvs4) {
  39632. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39633. }
  39634. if (parsedGeometry.uvs5) {
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39636. }
  39637. if (parsedGeometry.uvs6) {
  39638. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39639. }
  39640. if (parsedGeometry.colors) {
  39641. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39642. }
  39643. if (parsedGeometry.matricesIndices) {
  39644. if (!parsedGeometry.matricesIndices._isExpanded) {
  39645. var floatIndices = [];
  39646. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39647. var matricesIndex = parsedGeometry.matricesIndices[i];
  39648. floatIndices.push(matricesIndex & 0x000000FF);
  39649. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39650. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39651. floatIndices.push(matricesIndex >> 24);
  39652. }
  39653. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39654. }
  39655. else {
  39656. delete parsedGeometry.matricesIndices._isExpanded;
  39657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39658. }
  39659. }
  39660. if (parsedGeometry.matricesIndicesExtra) {
  39661. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39662. var floatIndices = [];
  39663. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39664. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39665. floatIndices.push(matricesIndex & 0x000000FF);
  39666. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39667. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39668. floatIndices.push(matricesIndex >> 24);
  39669. }
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39671. }
  39672. else {
  39673. delete parsedGeometry.matricesIndices._isExpanded;
  39674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39675. }
  39676. }
  39677. if (parsedGeometry.matricesWeights) {
  39678. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39680. }
  39681. if (parsedGeometry.matricesWeightsExtra) {
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39683. }
  39684. mesh.setIndices(parsedGeometry.indices, null);
  39685. }
  39686. // SubMeshes
  39687. if (parsedGeometry.subMeshes) {
  39688. mesh.subMeshes = [];
  39689. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39690. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39691. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39692. }
  39693. }
  39694. // Flat shading
  39695. if (mesh._shouldGenerateFlatShading) {
  39696. mesh.convertToFlatShadedMesh();
  39697. delete mesh._shouldGenerateFlatShading;
  39698. }
  39699. // Update
  39700. mesh.computeWorldMatrix(true);
  39701. scene.onMeshImportedObservable.notifyObservers(mesh);
  39702. };
  39703. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39704. var epsilon = 1e-3;
  39705. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39706. return;
  39707. }
  39708. var noInfluenceBoneIndex = 0.0;
  39709. if (parsedGeometry.skeletonId > -1) {
  39710. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39711. if (!skeleton) {
  39712. return;
  39713. }
  39714. noInfluenceBoneIndex = skeleton.bones.length;
  39715. }
  39716. else {
  39717. return;
  39718. }
  39719. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39720. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39721. var matricesWeights = parsedGeometry.matricesWeights;
  39722. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39723. var influencers = parsedGeometry.numBoneInfluencer;
  39724. var size = matricesWeights.length;
  39725. for (var i = 0; i < size; i += 4) {
  39726. var weight = 0.0;
  39727. var firstZeroWeight = -1;
  39728. for (var j = 0; j < 4; j++) {
  39729. var w = matricesWeights[i + j];
  39730. weight += w;
  39731. if (w < epsilon && firstZeroWeight < 0) {
  39732. firstZeroWeight = j;
  39733. }
  39734. }
  39735. if (matricesWeightsExtra) {
  39736. for (var j = 0; j < 4; j++) {
  39737. var w = matricesWeightsExtra[i + j];
  39738. weight += w;
  39739. if (w < epsilon && firstZeroWeight < 0) {
  39740. firstZeroWeight = j + 4;
  39741. }
  39742. }
  39743. }
  39744. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39745. firstZeroWeight = influencers - 1;
  39746. }
  39747. if (weight > epsilon) {
  39748. var mweight = 1.0 / weight;
  39749. for (var j = 0; j < 4; j++) {
  39750. matricesWeights[i + j] *= mweight;
  39751. }
  39752. if (matricesWeightsExtra) {
  39753. for (var j = 0; j < 4; j++) {
  39754. matricesWeightsExtra[i + j] *= mweight;
  39755. }
  39756. }
  39757. }
  39758. else {
  39759. if (firstZeroWeight >= 4) {
  39760. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39761. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39762. }
  39763. else {
  39764. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39765. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39766. }
  39767. }
  39768. }
  39769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39770. if (parsedGeometry.matricesWeightsExtra) {
  39771. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39772. }
  39773. };
  39774. /**
  39775. * Create a new geometry from persisted data (Using .babylon file format)
  39776. * @param parsedVertexData defines the persisted data
  39777. * @param scene defines the hosting scene
  39778. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39779. * @returns the new geometry object
  39780. */
  39781. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39782. if (scene.getGeometryByID(parsedVertexData.id)) {
  39783. return null; // null since geometry could be something else than a box...
  39784. }
  39785. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39786. if (BABYLON.Tags) {
  39787. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39788. }
  39789. if (parsedVertexData.delayLoadingFile) {
  39790. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39791. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39792. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39793. geometry._delayInfo = [];
  39794. if (parsedVertexData.hasUVs) {
  39795. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39796. }
  39797. if (parsedVertexData.hasUVs2) {
  39798. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39799. }
  39800. if (parsedVertexData.hasUVs3) {
  39801. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39802. }
  39803. if (parsedVertexData.hasUVs4) {
  39804. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39805. }
  39806. if (parsedVertexData.hasUVs5) {
  39807. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39808. }
  39809. if (parsedVertexData.hasUVs6) {
  39810. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39811. }
  39812. if (parsedVertexData.hasColors) {
  39813. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39814. }
  39815. if (parsedVertexData.hasMatricesIndices) {
  39816. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39817. }
  39818. if (parsedVertexData.hasMatricesWeights) {
  39819. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39820. }
  39821. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39822. }
  39823. else {
  39824. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39825. }
  39826. scene.pushGeometry(geometry, true);
  39827. return geometry;
  39828. };
  39829. return Geometry;
  39830. }());
  39831. BABYLON.Geometry = Geometry;
  39832. // Primitives
  39833. /// Abstract class
  39834. /**
  39835. * Abstract class used to provide common services for all typed geometries
  39836. * @hidden
  39837. */
  39838. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39839. __extends(_PrimitiveGeometry, _super);
  39840. /**
  39841. * Creates a new typed geometry
  39842. * @param id defines the unique ID of the geometry
  39843. * @param scene defines the hosting scene
  39844. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39845. * @param mesh defines the hosting mesh (can be null)
  39846. */
  39847. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39848. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39849. if (mesh === void 0) { mesh = null; }
  39850. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39851. _this._canBeRegenerated = _canBeRegenerated;
  39852. _this._beingRegenerated = true;
  39853. _this.regenerate();
  39854. _this._beingRegenerated = false;
  39855. return _this;
  39856. }
  39857. /**
  39858. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39859. * @returns true if the geometry can be regenerated
  39860. */
  39861. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39862. return this._canBeRegenerated;
  39863. };
  39864. /**
  39865. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39866. */
  39867. _PrimitiveGeometry.prototype.regenerate = function () {
  39868. if (!this._canBeRegenerated) {
  39869. return;
  39870. }
  39871. this._beingRegenerated = true;
  39872. this.setAllVerticesData(this._regenerateVertexData(), false);
  39873. this._beingRegenerated = false;
  39874. };
  39875. /**
  39876. * Clone the geometry
  39877. * @param id defines the unique ID of the new geometry
  39878. * @returns the new geometry
  39879. */
  39880. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39881. return _super.prototype.copy.call(this, id);
  39882. };
  39883. // overrides
  39884. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39885. if (!this._beingRegenerated) {
  39886. return;
  39887. }
  39888. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39889. };
  39890. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39891. if (!this._beingRegenerated) {
  39892. return;
  39893. }
  39894. _super.prototype.setVerticesData.call(this, kind, data, false);
  39895. };
  39896. // to override
  39897. /** @hidden */
  39898. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39899. throw new Error("Abstract method");
  39900. };
  39901. _PrimitiveGeometry.prototype.copy = function (id) {
  39902. throw new Error("Must be overriden in sub-classes.");
  39903. };
  39904. _PrimitiveGeometry.prototype.serialize = function () {
  39905. var serializationObject = _super.prototype.serialize.call(this);
  39906. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39907. return serializationObject;
  39908. };
  39909. return _PrimitiveGeometry;
  39910. }(Geometry));
  39911. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39912. /**
  39913. * Creates a ribbon geometry
  39914. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39915. */
  39916. var RibbonGeometry = /** @class */ (function (_super) {
  39917. __extends(RibbonGeometry, _super);
  39918. /**
  39919. * Creates a ribbon geometry
  39920. * @param id defines the unique ID of the geometry
  39921. * @param scene defines the hosting scene
  39922. * @param pathArray defines the array of paths to use
  39923. * @param closeArray defines if the last path and the first path must be joined
  39924. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39925. * @param offset defines the offset between points
  39926. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39927. * @param mesh defines the hosting mesh (can be null)
  39928. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39929. */
  39930. function RibbonGeometry(id, scene,
  39931. /**
  39932. * Defines the array of paths to use
  39933. */
  39934. pathArray,
  39935. /**
  39936. * Defines if the last and first points of each path in your pathArray must be joined
  39937. */
  39938. closeArray,
  39939. /**
  39940. * Defines if the last and first points of each path in your pathArray must be joined
  39941. */
  39942. closePath,
  39943. /**
  39944. * Defines the offset between points
  39945. */
  39946. offset, canBeRegenerated, mesh,
  39947. /**
  39948. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39949. */
  39950. side) {
  39951. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39952. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39953. _this.pathArray = pathArray;
  39954. _this.closeArray = closeArray;
  39955. _this.closePath = closePath;
  39956. _this.offset = offset;
  39957. _this.side = side;
  39958. return _this;
  39959. }
  39960. /** @hidden */
  39961. RibbonGeometry.prototype._regenerateVertexData = function () {
  39962. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39963. };
  39964. RibbonGeometry.prototype.copy = function (id) {
  39965. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39966. };
  39967. return RibbonGeometry;
  39968. }(_PrimitiveGeometry));
  39969. BABYLON.RibbonGeometry = RibbonGeometry;
  39970. /**
  39971. * Creates a box geometry
  39972. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39973. */
  39974. var BoxGeometry = /** @class */ (function (_super) {
  39975. __extends(BoxGeometry, _super);
  39976. /**
  39977. * Creates a box geometry
  39978. * @param id defines the unique ID of the geometry
  39979. * @param scene defines the hosting scene
  39980. * @param size defines the zise of the box (width, height and depth are the same)
  39981. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39982. * @param mesh defines the hosting mesh (can be null)
  39983. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39984. */
  39985. function BoxGeometry(id, scene,
  39986. /**
  39987. * Defines the zise of the box (width, height and depth are the same)
  39988. */
  39989. size, canBeRegenerated, mesh,
  39990. /**
  39991. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39992. */
  39993. side) {
  39994. if (mesh === void 0) { mesh = null; }
  39995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39996. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39997. _this.size = size;
  39998. _this.side = side;
  39999. return _this;
  40000. }
  40001. /** @hidden */
  40002. BoxGeometry.prototype._regenerateVertexData = function () {
  40003. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40004. };
  40005. BoxGeometry.prototype.copy = function (id) {
  40006. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40007. };
  40008. BoxGeometry.prototype.serialize = function () {
  40009. var serializationObject = _super.prototype.serialize.call(this);
  40010. serializationObject.size = this.size;
  40011. return serializationObject;
  40012. };
  40013. BoxGeometry.Parse = function (parsedBox, scene) {
  40014. if (scene.getGeometryByID(parsedBox.id)) {
  40015. return null; // null since geometry could be something else than a box...
  40016. }
  40017. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40018. if (BABYLON.Tags) {
  40019. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40020. }
  40021. scene.pushGeometry(box, true);
  40022. return box;
  40023. };
  40024. return BoxGeometry;
  40025. }(_PrimitiveGeometry));
  40026. BABYLON.BoxGeometry = BoxGeometry;
  40027. /**
  40028. * Creates a sphere geometry
  40029. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40030. */
  40031. var SphereGeometry = /** @class */ (function (_super) {
  40032. __extends(SphereGeometry, _super);
  40033. /**
  40034. * Create a new sphere geometry
  40035. * @param id defines the unique ID of the geometry
  40036. * @param scene defines the hosting scene
  40037. * @param segments defines the number of segments to use to create the sphere
  40038. * @param diameter defines the diameter of the sphere
  40039. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40040. * @param mesh defines the hosting mesh (can be null)
  40041. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40042. */
  40043. function SphereGeometry(id, scene,
  40044. /**
  40045. * Defines the number of segments to use to create the sphere
  40046. */
  40047. segments,
  40048. /**
  40049. * Defines the diameter of the sphere
  40050. */
  40051. diameter, canBeRegenerated, mesh,
  40052. /**
  40053. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40054. */
  40055. side) {
  40056. if (mesh === void 0) { mesh = null; }
  40057. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40058. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40059. _this.segments = segments;
  40060. _this.diameter = diameter;
  40061. _this.side = side;
  40062. return _this;
  40063. }
  40064. /** @hidden */
  40065. SphereGeometry.prototype._regenerateVertexData = function () {
  40066. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40067. };
  40068. SphereGeometry.prototype.copy = function (id) {
  40069. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40070. };
  40071. SphereGeometry.prototype.serialize = function () {
  40072. var serializationObject = _super.prototype.serialize.call(this);
  40073. serializationObject.segments = this.segments;
  40074. serializationObject.diameter = this.diameter;
  40075. return serializationObject;
  40076. };
  40077. SphereGeometry.Parse = function (parsedSphere, scene) {
  40078. if (scene.getGeometryByID(parsedSphere.id)) {
  40079. return null; // null since geometry could be something else than a sphere...
  40080. }
  40081. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40082. if (BABYLON.Tags) {
  40083. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40084. }
  40085. scene.pushGeometry(sphere, true);
  40086. return sphere;
  40087. };
  40088. return SphereGeometry;
  40089. }(_PrimitiveGeometry));
  40090. BABYLON.SphereGeometry = SphereGeometry;
  40091. /**
  40092. * Creates a disc geometry
  40093. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40094. */
  40095. var DiscGeometry = /** @class */ (function (_super) {
  40096. __extends(DiscGeometry, _super);
  40097. /**
  40098. * Creates a new disc geometry
  40099. * @param id defines the unique ID of the geometry
  40100. * @param scene defines the hosting scene
  40101. * @param radius defines the radius of the disc
  40102. * @param tessellation defines the tesselation factor to apply to the disc
  40103. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40104. * @param mesh defines the hosting mesh (can be null)
  40105. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40106. */
  40107. function DiscGeometry(id, scene,
  40108. /**
  40109. * Defines the radius of the disc
  40110. */
  40111. radius,
  40112. /**
  40113. * Defines the tesselation factor to apply to the disc
  40114. */
  40115. tessellation, canBeRegenerated, mesh,
  40116. /**
  40117. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40118. */
  40119. side) {
  40120. if (mesh === void 0) { mesh = null; }
  40121. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40122. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40123. _this.radius = radius;
  40124. _this.tessellation = tessellation;
  40125. _this.side = side;
  40126. return _this;
  40127. }
  40128. /** @hidden */
  40129. DiscGeometry.prototype._regenerateVertexData = function () {
  40130. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40131. };
  40132. DiscGeometry.prototype.copy = function (id) {
  40133. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40134. };
  40135. return DiscGeometry;
  40136. }(_PrimitiveGeometry));
  40137. BABYLON.DiscGeometry = DiscGeometry;
  40138. /**
  40139. * Creates a new cylinder geometry
  40140. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40141. */
  40142. var CylinderGeometry = /** @class */ (function (_super) {
  40143. __extends(CylinderGeometry, _super);
  40144. /**
  40145. * Creates a new cylinder geometry
  40146. * @param id defines the unique ID of the geometry
  40147. * @param scene defines the hosting scene
  40148. * @param height defines the height of the cylinder
  40149. * @param diameterTop defines the diameter of the cylinder's top cap
  40150. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40151. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40152. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40153. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40154. * @param mesh defines the hosting mesh (can be null)
  40155. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40156. */
  40157. function CylinderGeometry(id, scene,
  40158. /**
  40159. * Defines the height of the cylinder
  40160. */
  40161. height,
  40162. /**
  40163. * Defines the diameter of the cylinder's top cap
  40164. */
  40165. diameterTop,
  40166. /**
  40167. * Defines the diameter of the cylinder's bottom cap
  40168. */
  40169. diameterBottom,
  40170. /**
  40171. * Defines the tessellation factor to apply to the cylinder
  40172. */
  40173. tessellation,
  40174. /**
  40175. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40176. */
  40177. subdivisions, canBeRegenerated, mesh,
  40178. /**
  40179. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40180. */
  40181. side) {
  40182. if (subdivisions === void 0) { subdivisions = 1; }
  40183. if (mesh === void 0) { mesh = null; }
  40184. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40185. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40186. _this.height = height;
  40187. _this.diameterTop = diameterTop;
  40188. _this.diameterBottom = diameterBottom;
  40189. _this.tessellation = tessellation;
  40190. _this.subdivisions = subdivisions;
  40191. _this.side = side;
  40192. return _this;
  40193. }
  40194. /** @hidden */
  40195. CylinderGeometry.prototype._regenerateVertexData = function () {
  40196. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40197. };
  40198. CylinderGeometry.prototype.copy = function (id) {
  40199. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40200. };
  40201. CylinderGeometry.prototype.serialize = function () {
  40202. var serializationObject = _super.prototype.serialize.call(this);
  40203. serializationObject.height = this.height;
  40204. serializationObject.diameterTop = this.diameterTop;
  40205. serializationObject.diameterBottom = this.diameterBottom;
  40206. serializationObject.tessellation = this.tessellation;
  40207. return serializationObject;
  40208. };
  40209. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40210. if (scene.getGeometryByID(parsedCylinder.id)) {
  40211. return null; // null since geometry could be something else than a cylinder...
  40212. }
  40213. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40214. if (BABYLON.Tags) {
  40215. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40216. }
  40217. scene.pushGeometry(cylinder, true);
  40218. return cylinder;
  40219. };
  40220. return CylinderGeometry;
  40221. }(_PrimitiveGeometry));
  40222. BABYLON.CylinderGeometry = CylinderGeometry;
  40223. /**
  40224. * Creates a new torus geometry
  40225. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40226. */
  40227. var TorusGeometry = /** @class */ (function (_super) {
  40228. __extends(TorusGeometry, _super);
  40229. /**
  40230. * Creates a new torus geometry
  40231. * @param id defines the unique ID of the geometry
  40232. * @param scene defines the hosting scene
  40233. * @param diameter defines the diameter of the torus
  40234. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40235. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40236. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40237. * @param mesh defines the hosting mesh (can be null)
  40238. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40239. */
  40240. function TorusGeometry(id, scene,
  40241. /**
  40242. * Defines the diameter of the torus
  40243. */
  40244. diameter,
  40245. /**
  40246. * Defines the thickness of the torus (ie. internal diameter)
  40247. */
  40248. thickness,
  40249. /**
  40250. * Defines the tesselation factor to apply to the torus
  40251. */
  40252. tessellation, canBeRegenerated, mesh,
  40253. /**
  40254. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40255. */
  40256. side) {
  40257. if (mesh === void 0) { mesh = null; }
  40258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40260. _this.diameter = diameter;
  40261. _this.thickness = thickness;
  40262. _this.tessellation = tessellation;
  40263. _this.side = side;
  40264. return _this;
  40265. }
  40266. /** @hidden */
  40267. TorusGeometry.prototype._regenerateVertexData = function () {
  40268. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40269. };
  40270. TorusGeometry.prototype.copy = function (id) {
  40271. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40272. };
  40273. TorusGeometry.prototype.serialize = function () {
  40274. var serializationObject = _super.prototype.serialize.call(this);
  40275. serializationObject.diameter = this.diameter;
  40276. serializationObject.thickness = this.thickness;
  40277. serializationObject.tessellation = this.tessellation;
  40278. return serializationObject;
  40279. };
  40280. TorusGeometry.Parse = function (parsedTorus, scene) {
  40281. if (scene.getGeometryByID(parsedTorus.id)) {
  40282. return null; // null since geometry could be something else than a torus...
  40283. }
  40284. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40285. if (BABYLON.Tags) {
  40286. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40287. }
  40288. scene.pushGeometry(torus, true);
  40289. return torus;
  40290. };
  40291. return TorusGeometry;
  40292. }(_PrimitiveGeometry));
  40293. BABYLON.TorusGeometry = TorusGeometry;
  40294. /**
  40295. * Creates a new ground geometry
  40296. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40297. */
  40298. var GroundGeometry = /** @class */ (function (_super) {
  40299. __extends(GroundGeometry, _super);
  40300. /**
  40301. * Creates a new ground geometry
  40302. * @param id defines the unique ID of the geometry
  40303. * @param scene defines the hosting scene
  40304. * @param width defines the width of the ground
  40305. * @param height defines the height of the ground
  40306. * @param subdivisions defines the subdivisions to apply to the ground
  40307. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40308. * @param mesh defines the hosting mesh (can be null)
  40309. */
  40310. function GroundGeometry(id, scene,
  40311. /**
  40312. * Defines the width of the ground
  40313. */
  40314. width,
  40315. /**
  40316. * Defines the height of the ground
  40317. */
  40318. height,
  40319. /**
  40320. * Defines the subdivisions to apply to the ground
  40321. */
  40322. subdivisions, canBeRegenerated, mesh) {
  40323. if (mesh === void 0) { mesh = null; }
  40324. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40325. _this.width = width;
  40326. _this.height = height;
  40327. _this.subdivisions = subdivisions;
  40328. return _this;
  40329. }
  40330. /** @hidden */
  40331. GroundGeometry.prototype._regenerateVertexData = function () {
  40332. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40333. };
  40334. GroundGeometry.prototype.copy = function (id) {
  40335. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40336. };
  40337. GroundGeometry.prototype.serialize = function () {
  40338. var serializationObject = _super.prototype.serialize.call(this);
  40339. serializationObject.width = this.width;
  40340. serializationObject.height = this.height;
  40341. serializationObject.subdivisions = this.subdivisions;
  40342. return serializationObject;
  40343. };
  40344. GroundGeometry.Parse = function (parsedGround, scene) {
  40345. if (scene.getGeometryByID(parsedGround.id)) {
  40346. return null; // null since geometry could be something else than a ground...
  40347. }
  40348. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40349. if (BABYLON.Tags) {
  40350. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40351. }
  40352. scene.pushGeometry(ground, true);
  40353. return ground;
  40354. };
  40355. return GroundGeometry;
  40356. }(_PrimitiveGeometry));
  40357. BABYLON.GroundGeometry = GroundGeometry;
  40358. /**
  40359. * Creates a tiled ground geometry
  40360. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40361. */
  40362. var TiledGroundGeometry = /** @class */ (function (_super) {
  40363. __extends(TiledGroundGeometry, _super);
  40364. /**
  40365. * Creates a tiled ground geometry
  40366. * @param id defines the unique ID of the geometry
  40367. * @param scene defines the hosting scene
  40368. * @param xmin defines the minimum value on X axis
  40369. * @param zmin defines the minimum value on Z axis
  40370. * @param xmax defines the maximum value on X axis
  40371. * @param zmax defines the maximum value on Z axis
  40372. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40373. * @param precision defines the precision to use when computing the tiles
  40374. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40375. * @param mesh defines the hosting mesh (can be null)
  40376. */
  40377. function TiledGroundGeometry(id, scene,
  40378. /**
  40379. * Defines the minimum value on X axis
  40380. */
  40381. xmin,
  40382. /**
  40383. * Defines the minimum value on Z axis
  40384. */
  40385. zmin,
  40386. /**
  40387. * Defines the maximum value on X axis
  40388. */
  40389. xmax,
  40390. /**
  40391. * Defines the maximum value on Z axis
  40392. */
  40393. zmax,
  40394. /**
  40395. * Defines the subdivisions to apply to the ground
  40396. */
  40397. subdivisions,
  40398. /**
  40399. * Defines the precision to use when computing the tiles
  40400. */
  40401. precision, canBeRegenerated, mesh) {
  40402. if (mesh === void 0) { mesh = null; }
  40403. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40404. _this.xmin = xmin;
  40405. _this.zmin = zmin;
  40406. _this.xmax = xmax;
  40407. _this.zmax = zmax;
  40408. _this.subdivisions = subdivisions;
  40409. _this.precision = precision;
  40410. return _this;
  40411. }
  40412. /** @hidden */
  40413. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40414. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40415. };
  40416. TiledGroundGeometry.prototype.copy = function (id) {
  40417. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40418. };
  40419. return TiledGroundGeometry;
  40420. }(_PrimitiveGeometry));
  40421. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40422. /**
  40423. * Creates a plane geometry
  40424. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40425. */
  40426. var PlaneGeometry = /** @class */ (function (_super) {
  40427. __extends(PlaneGeometry, _super);
  40428. /**
  40429. * Creates a plane geometry
  40430. * @param id defines the unique ID of the geometry
  40431. * @param scene defines the hosting scene
  40432. * @param size defines the size of the plane (width === height)
  40433. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40434. * @param mesh defines the hosting mesh (can be null)
  40435. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40436. */
  40437. function PlaneGeometry(id, scene,
  40438. /**
  40439. * Defines the size of the plane (width === height)
  40440. */
  40441. size, canBeRegenerated, mesh,
  40442. /**
  40443. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40444. */
  40445. side) {
  40446. if (mesh === void 0) { mesh = null; }
  40447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40449. _this.size = size;
  40450. _this.side = side;
  40451. return _this;
  40452. }
  40453. /** @hidden */
  40454. PlaneGeometry.prototype._regenerateVertexData = function () {
  40455. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40456. };
  40457. PlaneGeometry.prototype.copy = function (id) {
  40458. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40459. };
  40460. PlaneGeometry.prototype.serialize = function () {
  40461. var serializationObject = _super.prototype.serialize.call(this);
  40462. serializationObject.size = this.size;
  40463. return serializationObject;
  40464. };
  40465. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40466. if (scene.getGeometryByID(parsedPlane.id)) {
  40467. return null; // null since geometry could be something else than a ground...
  40468. }
  40469. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40470. if (BABYLON.Tags) {
  40471. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40472. }
  40473. scene.pushGeometry(plane, true);
  40474. return plane;
  40475. };
  40476. return PlaneGeometry;
  40477. }(_PrimitiveGeometry));
  40478. BABYLON.PlaneGeometry = PlaneGeometry;
  40479. /**
  40480. * Creates a torus knot geometry
  40481. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40482. */
  40483. var TorusKnotGeometry = /** @class */ (function (_super) {
  40484. __extends(TorusKnotGeometry, _super);
  40485. /**
  40486. * Creates a torus knot geometry
  40487. * @param id defines the unique ID of the geometry
  40488. * @param scene defines the hosting scene
  40489. * @param radius defines the radius of the torus knot
  40490. * @param tube defines the thickness of the torus knot tube
  40491. * @param radialSegments defines the number of radial segments
  40492. * @param tubularSegments defines the number of tubular segments
  40493. * @param p defines the first number of windings
  40494. * @param q defines the second number of windings
  40495. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40496. * @param mesh defines the hosting mesh (can be null)
  40497. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40498. */
  40499. function TorusKnotGeometry(id, scene,
  40500. /**
  40501. * Defines the radius of the torus knot
  40502. */
  40503. radius,
  40504. /**
  40505. * Defines the thickness of the torus knot tube
  40506. */
  40507. tube,
  40508. /**
  40509. * Defines the number of radial segments
  40510. */
  40511. radialSegments,
  40512. /**
  40513. * Defines the number of tubular segments
  40514. */
  40515. tubularSegments,
  40516. /**
  40517. * Defines the first number of windings
  40518. */
  40519. p,
  40520. /**
  40521. * Defines the second number of windings
  40522. */
  40523. q, canBeRegenerated, mesh,
  40524. /**
  40525. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. side) {
  40528. if (mesh === void 0) { mesh = null; }
  40529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.radius = radius;
  40532. _this.tube = tube;
  40533. _this.radialSegments = radialSegments;
  40534. _this.tubularSegments = tubularSegments;
  40535. _this.p = p;
  40536. _this.q = q;
  40537. _this.side = side;
  40538. return _this;
  40539. }
  40540. /** @hidden */
  40541. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40542. 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 });
  40543. };
  40544. TorusKnotGeometry.prototype.copy = function (id) {
  40545. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40546. };
  40547. TorusKnotGeometry.prototype.serialize = function () {
  40548. var serializationObject = _super.prototype.serialize.call(this);
  40549. serializationObject.radius = this.radius;
  40550. serializationObject.tube = this.tube;
  40551. serializationObject.radialSegments = this.radialSegments;
  40552. serializationObject.tubularSegments = this.tubularSegments;
  40553. serializationObject.p = this.p;
  40554. serializationObject.q = this.q;
  40555. return serializationObject;
  40556. };
  40557. ;
  40558. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40559. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40560. return null; // null since geometry could be something else than a ground...
  40561. }
  40562. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40563. if (BABYLON.Tags) {
  40564. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40565. }
  40566. scene.pushGeometry(torusKnot, true);
  40567. return torusKnot;
  40568. };
  40569. return TorusKnotGeometry;
  40570. }(_PrimitiveGeometry));
  40571. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40572. //}
  40573. })(BABYLON || (BABYLON = {}));
  40574. //# sourceMappingURL=babylon.geometry.js.map
  40575. var BABYLON;
  40576. (function (BABYLON) {
  40577. /**
  40578. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40579. */
  40580. var PerformanceMonitor = /** @class */ (function () {
  40581. /**
  40582. * constructor
  40583. * @param frameSampleSize The number of samples required to saturate the sliding window
  40584. */
  40585. function PerformanceMonitor(frameSampleSize) {
  40586. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40587. this._enabled = true;
  40588. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40589. }
  40590. /**
  40591. * Samples current frame
  40592. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40593. */
  40594. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40595. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40596. if (!this._enabled)
  40597. return;
  40598. if (this._lastFrameTimeMs != null) {
  40599. var dt = timeMs - this._lastFrameTimeMs;
  40600. this._rollingFrameTime.add(dt);
  40601. }
  40602. this._lastFrameTimeMs = timeMs;
  40603. };
  40604. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40605. /**
  40606. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40607. * @return Average frame time in milliseconds
  40608. */
  40609. get: function () {
  40610. return this._rollingFrameTime.average;
  40611. },
  40612. enumerable: true,
  40613. configurable: true
  40614. });
  40615. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40616. /**
  40617. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40618. * @return Frame time variance in milliseconds squared
  40619. */
  40620. get: function () {
  40621. return this._rollingFrameTime.variance;
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40627. /**
  40628. * Returns the frame time of the most recent frame
  40629. * @return Frame time in milliseconds
  40630. */
  40631. get: function () {
  40632. return this._rollingFrameTime.history(0);
  40633. },
  40634. enumerable: true,
  40635. configurable: true
  40636. });
  40637. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40638. /**
  40639. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40640. * @return Framerate in frames per second
  40641. */
  40642. get: function () {
  40643. return 1000.0 / this._rollingFrameTime.average;
  40644. },
  40645. enumerable: true,
  40646. configurable: true
  40647. });
  40648. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40649. /**
  40650. * Returns the average framerate in frames per second using the most recent frame time
  40651. * @return Framerate in frames per second
  40652. */
  40653. get: function () {
  40654. var history = this._rollingFrameTime.history(0);
  40655. if (history === 0) {
  40656. return 0;
  40657. }
  40658. return 1000.0 / history;
  40659. },
  40660. enumerable: true,
  40661. configurable: true
  40662. });
  40663. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40664. /**
  40665. * Returns true if enough samples have been taken to completely fill the sliding window
  40666. * @return true if saturated
  40667. */
  40668. get: function () {
  40669. return this._rollingFrameTime.isSaturated();
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. /**
  40675. * Enables contributions to the sliding window sample set
  40676. */
  40677. PerformanceMonitor.prototype.enable = function () {
  40678. this._enabled = true;
  40679. };
  40680. /**
  40681. * Disables contributions to the sliding window sample set
  40682. * Samples will not be interpolated over the disabled period
  40683. */
  40684. PerformanceMonitor.prototype.disable = function () {
  40685. this._enabled = false;
  40686. //clear last sample to avoid interpolating over the disabled period when next enabled
  40687. this._lastFrameTimeMs = null;
  40688. };
  40689. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40690. /**
  40691. * Returns true if sampling is enabled
  40692. * @return true if enabled
  40693. */
  40694. get: function () {
  40695. return this._enabled;
  40696. },
  40697. enumerable: true,
  40698. configurable: true
  40699. });
  40700. /**
  40701. * Resets performance monitor
  40702. */
  40703. PerformanceMonitor.prototype.reset = function () {
  40704. //clear last sample to avoid interpolating over the disabled period when next enabled
  40705. this._lastFrameTimeMs = null;
  40706. //wipe record
  40707. this._rollingFrameTime.reset();
  40708. };
  40709. return PerformanceMonitor;
  40710. }());
  40711. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40712. /**
  40713. * RollingAverage
  40714. *
  40715. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40716. */
  40717. var RollingAverage = /** @class */ (function () {
  40718. /**
  40719. * constructor
  40720. * @param length The number of samples required to saturate the sliding window
  40721. */
  40722. function RollingAverage(length) {
  40723. this._samples = new Array(length);
  40724. this.reset();
  40725. }
  40726. /**
  40727. * Adds a sample to the sample set
  40728. * @param v The sample value
  40729. */
  40730. RollingAverage.prototype.add = function (v) {
  40731. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40732. var delta;
  40733. //we need to check if we've already wrapped round
  40734. if (this.isSaturated()) {
  40735. //remove bottom of stack from mean
  40736. var bottomValue = this._samples[this._pos];
  40737. delta = bottomValue - this.average;
  40738. this.average -= delta / (this._sampleCount - 1);
  40739. this._m2 -= delta * (bottomValue - this.average);
  40740. }
  40741. else {
  40742. this._sampleCount++;
  40743. }
  40744. //add new value to mean
  40745. delta = v - this.average;
  40746. this.average += delta / (this._sampleCount);
  40747. this._m2 += delta * (v - this.average);
  40748. //set the new variance
  40749. this.variance = this._m2 / (this._sampleCount - 1);
  40750. this._samples[this._pos] = v;
  40751. this._pos++;
  40752. this._pos %= this._samples.length; //positive wrap around
  40753. };
  40754. /**
  40755. * Returns previously added values or null if outside of history or outside the sliding window domain
  40756. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40757. * @return Value previously recorded with add() or null if outside of range
  40758. */
  40759. RollingAverage.prototype.history = function (i) {
  40760. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40761. return 0;
  40762. }
  40763. var i0 = this._wrapPosition(this._pos - 1.0);
  40764. return this._samples[this._wrapPosition(i0 - i)];
  40765. };
  40766. /**
  40767. * Returns true if enough samples have been taken to completely fill the sliding window
  40768. * @return true if sample-set saturated
  40769. */
  40770. RollingAverage.prototype.isSaturated = function () {
  40771. return this._sampleCount >= this._samples.length;
  40772. };
  40773. /**
  40774. * Resets the rolling average (equivalent to 0 samples taken so far)
  40775. */
  40776. RollingAverage.prototype.reset = function () {
  40777. this.average = 0;
  40778. this.variance = 0;
  40779. this._sampleCount = 0;
  40780. this._pos = 0;
  40781. this._m2 = 0;
  40782. };
  40783. /**
  40784. * Wraps a value around the sample range boundaries
  40785. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40786. * @return Wrapped position in sample range
  40787. */
  40788. RollingAverage.prototype._wrapPosition = function (i) {
  40789. var max = this._samples.length;
  40790. return ((i % max) + max) % max;
  40791. };
  40792. return RollingAverage;
  40793. }());
  40794. BABYLON.RollingAverage = RollingAverage;
  40795. })(BABYLON || (BABYLON = {}));
  40796. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40797. var BABYLON;
  40798. (function (BABYLON) {
  40799. /**
  40800. * "Static Class" containing the most commonly used helper while dealing with material for
  40801. * rendering purpose.
  40802. *
  40803. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40804. *
  40805. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40806. */
  40807. var MaterialHelper = /** @class */ (function () {
  40808. function MaterialHelper() {
  40809. }
  40810. /**
  40811. * Bind the current view position to an effect.
  40812. * @param effect The effect to be bound
  40813. * @param scene The scene the eyes position is used from
  40814. */
  40815. MaterialHelper.BindEyePosition = function (effect, scene) {
  40816. if (scene._forcedViewPosition) {
  40817. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40818. return;
  40819. }
  40820. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40821. };
  40822. /**
  40823. * Helps preparing the defines values about the UVs in used in the effect.
  40824. * UVs are shared as much as we can accross chanels in the shaders.
  40825. * @param texture The texture we are preparing the UVs for
  40826. * @param defines The defines to update
  40827. * @param key The chanel key "diffuse", "specular"... used in the shader
  40828. */
  40829. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40830. defines._needUVs = true;
  40831. defines[key] = true;
  40832. if (texture.getTextureMatrix().isIdentity(true)) {
  40833. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40834. if (texture.coordinatesIndex === 0) {
  40835. defines["MAINUV1"] = true;
  40836. }
  40837. else {
  40838. defines["MAINUV2"] = true;
  40839. }
  40840. }
  40841. else {
  40842. defines[key + "DIRECTUV"] = 0;
  40843. }
  40844. };
  40845. /**
  40846. * Binds a texture matrix value to its corrsponding uniform
  40847. * @param texture The texture to bind the matrix for
  40848. * @param uniformBuffer The uniform buffer receivin the data
  40849. * @param key The chanel key "diffuse", "specular"... used in the shader
  40850. */
  40851. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40852. var matrix = texture.getTextureMatrix();
  40853. if (!matrix.isIdentity(true)) {
  40854. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40855. }
  40856. };
  40857. /**
  40858. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40859. * @param mesh defines the current mesh
  40860. * @param scene defines the current scene
  40861. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40862. * @param pointsCloud defines if point cloud rendering has to be turned on
  40863. * @param fogEnabled defines if fog has to be turned on
  40864. * @param alphaTest defines if alpha testing has to be turned on
  40865. * @param defines defines the current list of defines
  40866. */
  40867. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40868. if (defines._areMiscDirty) {
  40869. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40870. defines["POINTSIZE"] = pointsCloud;
  40871. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40872. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40873. defines["ALPHATEST"] = alphaTest;
  40874. }
  40875. };
  40876. /**
  40877. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40878. * @param scene defines the current scene
  40879. * @param engine defines the current engine
  40880. * @param defines specifies the list of active defines
  40881. * @param useInstances defines if instances have to be turned on
  40882. * @param useClipPlane defines if clip plane have to be turned on
  40883. */
  40884. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40885. if (useClipPlane === void 0) { useClipPlane = null; }
  40886. var changed = false;
  40887. var useClipPlane1 = false;
  40888. var useClipPlane2 = false;
  40889. var useClipPlane3 = false;
  40890. var useClipPlane4 = false;
  40891. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40892. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40893. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40894. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40895. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40896. defines["CLIPPLANE"] = useClipPlane1;
  40897. changed = true;
  40898. }
  40899. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40900. defines["CLIPPLANE2"] = useClipPlane2;
  40901. changed = true;
  40902. }
  40903. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40904. defines["CLIPPLANE3"] = useClipPlane3;
  40905. changed = true;
  40906. }
  40907. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40908. defines["CLIPPLANE4"] = useClipPlane4;
  40909. changed = true;
  40910. }
  40911. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40912. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40913. changed = true;
  40914. }
  40915. if (defines["INSTANCES"] !== useInstances) {
  40916. defines["INSTANCES"] = useInstances;
  40917. changed = true;
  40918. }
  40919. if (changed) {
  40920. defines.markAsUnprocessed();
  40921. }
  40922. };
  40923. /**
  40924. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40925. * @param mesh The mesh containing the geometry data we will draw
  40926. * @param defines The defines to update
  40927. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40928. * @param useBones Precise whether bones should be used or not (override mesh info)
  40929. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40930. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40931. * @returns false if defines are considered not dirty and have not been checked
  40932. */
  40933. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40934. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40935. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40936. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40937. return false;
  40938. }
  40939. defines._normals = defines._needNormals;
  40940. defines._uvs = defines._needUVs;
  40941. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40942. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40943. defines["TANGENT"] = true;
  40944. }
  40945. if (defines._needUVs) {
  40946. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40947. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40948. }
  40949. else {
  40950. defines["UV1"] = false;
  40951. defines["UV2"] = false;
  40952. }
  40953. if (useVertexColor) {
  40954. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40955. defines["VERTEXCOLOR"] = hasVertexColors;
  40956. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40957. }
  40958. if (useBones) {
  40959. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40960. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40961. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40962. }
  40963. else {
  40964. defines["NUM_BONE_INFLUENCERS"] = 0;
  40965. defines["BonesPerMesh"] = 0;
  40966. }
  40967. }
  40968. if (useMorphTargets) {
  40969. var manager = mesh.morphTargetManager;
  40970. if (manager) {
  40971. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40972. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40973. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40974. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40975. }
  40976. else {
  40977. defines["MORPHTARGETS_TANGENT"] = false;
  40978. defines["MORPHTARGETS_NORMAL"] = false;
  40979. defines["MORPHTARGETS"] = false;
  40980. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40981. }
  40982. }
  40983. return true;
  40984. };
  40985. /**
  40986. * Prepares the defines related to the light information passed in parameter
  40987. * @param scene The scene we are intending to draw
  40988. * @param mesh The mesh the effect is compiling for
  40989. * @param defines The defines to update
  40990. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40991. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40992. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40993. * @returns true if normals will be required for the rest of the effect
  40994. */
  40995. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40996. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40997. if (disableLighting === void 0) { disableLighting = false; }
  40998. if (!defines._areLightsDirty) {
  40999. return defines._needNormals;
  41000. }
  41001. var lightIndex = 0;
  41002. var needNormals = false;
  41003. var needRebuild = false;
  41004. var lightmapMode = false;
  41005. var shadowEnabled = false;
  41006. var specularEnabled = false;
  41007. if (scene.lightsEnabled && !disableLighting) {
  41008. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41009. var light = _a[_i];
  41010. needNormals = true;
  41011. if (defines["LIGHT" + lightIndex] === undefined) {
  41012. needRebuild = true;
  41013. }
  41014. defines["LIGHT" + lightIndex] = true;
  41015. defines["SPOTLIGHT" + lightIndex] = false;
  41016. defines["HEMILIGHT" + lightIndex] = false;
  41017. defines["POINTLIGHT" + lightIndex] = false;
  41018. defines["DIRLIGHT" + lightIndex] = false;
  41019. light.prepareLightSpecificDefines(defines, lightIndex);
  41020. // FallOff.
  41021. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41022. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41023. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41024. switch (light.falloffType) {
  41025. case BABYLON.Light.FALLOFF_GLTF:
  41026. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41027. break;
  41028. case BABYLON.Light.FALLOFF_PHYSICAL:
  41029. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41030. break;
  41031. case BABYLON.Light.FALLOFF_STANDARD:
  41032. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41033. break;
  41034. }
  41035. // Specular
  41036. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41037. specularEnabled = true;
  41038. }
  41039. // Shadows
  41040. defines["SHADOW" + lightIndex] = false;
  41041. defines["SHADOWPCF" + lightIndex] = false;
  41042. defines["SHADOWPCSS" + lightIndex] = false;
  41043. defines["SHADOWPOISSON" + lightIndex] = false;
  41044. defines["SHADOWESM" + lightIndex] = false;
  41045. defines["SHADOWCUBE" + lightIndex] = false;
  41046. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41047. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41048. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41049. var shadowGenerator = light.getShadowGenerator();
  41050. if (shadowGenerator) {
  41051. var shadowMap = shadowGenerator.getShadowMap();
  41052. if (shadowMap) {
  41053. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41054. shadowEnabled = true;
  41055. shadowGenerator.prepareDefines(defines, lightIndex);
  41056. }
  41057. }
  41058. }
  41059. }
  41060. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41061. lightmapMode = true;
  41062. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41063. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41064. }
  41065. else {
  41066. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41067. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41068. }
  41069. lightIndex++;
  41070. if (lightIndex === maxSimultaneousLights)
  41071. break;
  41072. }
  41073. }
  41074. defines["SPECULARTERM"] = specularEnabled;
  41075. defines["SHADOWS"] = shadowEnabled;
  41076. // Resetting all other lights if any
  41077. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41078. if (defines["LIGHT" + index] !== undefined) {
  41079. defines["LIGHT" + index] = false;
  41080. defines["HEMILIGHT" + lightIndex] = false;
  41081. defines["POINTLIGHT" + lightIndex] = false;
  41082. defines["DIRLIGHT" + lightIndex] = false;
  41083. defines["SPOTLIGHT" + lightIndex] = false;
  41084. defines["SHADOW" + lightIndex] = false;
  41085. }
  41086. }
  41087. var caps = scene.getEngine().getCaps();
  41088. if (defines["SHADOWFLOAT"] === undefined) {
  41089. needRebuild = true;
  41090. }
  41091. defines["SHADOWFLOAT"] = shadowEnabled &&
  41092. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41093. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41094. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41095. if (needRebuild) {
  41096. defines.rebuild();
  41097. }
  41098. return needNormals;
  41099. };
  41100. /**
  41101. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41102. * that won t be acctive due to defines being turned off.
  41103. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41104. * @param samplersList The samplers list
  41105. * @param defines The defines helping in the list generation
  41106. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41107. */
  41108. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41109. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41110. var uniformsList;
  41111. var uniformBuffersList = null;
  41112. if (uniformsListOrOptions.uniformsNames) {
  41113. var options = uniformsListOrOptions;
  41114. uniformsList = options.uniformsNames;
  41115. uniformBuffersList = options.uniformBuffersNames;
  41116. samplersList = options.samplers;
  41117. defines = options.defines;
  41118. maxSimultaneousLights = options.maxSimultaneousLights;
  41119. }
  41120. else {
  41121. uniformsList = uniformsListOrOptions;
  41122. if (!samplersList) {
  41123. samplersList = [];
  41124. }
  41125. }
  41126. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41127. if (!defines["LIGHT" + lightIndex]) {
  41128. break;
  41129. }
  41130. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41131. if (uniformBuffersList) {
  41132. uniformBuffersList.push("Light" + lightIndex);
  41133. }
  41134. samplersList.push("shadowSampler" + lightIndex);
  41135. samplersList.push("depthSampler" + lightIndex);
  41136. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41137. samplersList.push("projectionLightSampler" + lightIndex);
  41138. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41139. }
  41140. }
  41141. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41142. uniformsList.push("morphTargetInfluences");
  41143. }
  41144. };
  41145. /**
  41146. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41147. * @param defines The defines to update while falling back
  41148. * @param fallbacks The authorized effect fallbacks
  41149. * @param maxSimultaneousLights The maximum number of lights allowed
  41150. * @param rank the current rank of the Effect
  41151. * @returns The newly affected rank
  41152. */
  41153. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41154. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41155. if (rank === void 0) { rank = 0; }
  41156. var lightFallbackRank = 0;
  41157. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41158. if (!defines["LIGHT" + lightIndex]) {
  41159. break;
  41160. }
  41161. if (lightIndex > 0) {
  41162. lightFallbackRank = rank + lightIndex;
  41163. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41164. }
  41165. if (!defines["SHADOWS"]) {
  41166. if (defines["SHADOW" + lightIndex]) {
  41167. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41168. }
  41169. if (defines["SHADOWPCF" + lightIndex]) {
  41170. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41171. }
  41172. if (defines["SHADOWPCSS" + lightIndex]) {
  41173. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41174. }
  41175. if (defines["SHADOWPOISSON" + lightIndex]) {
  41176. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41177. }
  41178. if (defines["SHADOWESM" + lightIndex]) {
  41179. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41180. }
  41181. }
  41182. }
  41183. return lightFallbackRank++;
  41184. };
  41185. /**
  41186. * Prepares the list of attributes required for morph targets according to the effect defines.
  41187. * @param attribs The current list of supported attribs
  41188. * @param mesh The mesh to prepare the morph targets attributes for
  41189. * @param defines The current Defines of the effect
  41190. */
  41191. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41192. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41193. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41194. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41195. var manager = mesh.morphTargetManager;
  41196. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41197. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41198. for (var index = 0; index < influencers; index++) {
  41199. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41200. if (normal) {
  41201. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41202. }
  41203. if (tangent) {
  41204. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41205. }
  41206. if (attribs.length > maxAttributesCount) {
  41207. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41208. }
  41209. }
  41210. }
  41211. };
  41212. /**
  41213. * Prepares the list of attributes required for bones according to the effect defines.
  41214. * @param attribs The current list of supported attribs
  41215. * @param mesh The mesh to prepare the bones attributes for
  41216. * @param defines The current Defines of the effect
  41217. * @param fallbacks The current efffect fallback strategy
  41218. */
  41219. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41220. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41221. fallbacks.addCPUSkinningFallback(0, mesh);
  41222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41224. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41227. }
  41228. }
  41229. };
  41230. /**
  41231. * Prepares the list of attributes required for instances according to the effect defines.
  41232. * @param attribs The current list of supported attribs
  41233. * @param defines The current Defines of the effect
  41234. */
  41235. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41236. if (defines["INSTANCES"]) {
  41237. attribs.push("world0");
  41238. attribs.push("world1");
  41239. attribs.push("world2");
  41240. attribs.push("world3");
  41241. }
  41242. };
  41243. /**
  41244. * Binds the light shadow information to the effect for the given mesh.
  41245. * @param light The light containing the generator
  41246. * @param scene The scene the lights belongs to
  41247. * @param mesh The mesh we are binding the information to render
  41248. * @param lightIndex The light index in the effect used to render the mesh
  41249. * @param effect The effect we are binding the data to
  41250. */
  41251. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41252. if (light.shadowEnabled && mesh.receiveShadows) {
  41253. var shadowGenerator = light.getShadowGenerator();
  41254. if (shadowGenerator) {
  41255. shadowGenerator.bindShadowLight(lightIndex, effect);
  41256. }
  41257. }
  41258. };
  41259. /**
  41260. * Binds the light information to the effect.
  41261. * @param light The light containing the generator
  41262. * @param effect The effect we are binding the data to
  41263. * @param lightIndex The light index in the effect used to render
  41264. */
  41265. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41266. light.transferToEffect(effect, lightIndex + "");
  41267. };
  41268. /**
  41269. * Binds the lights information from the scene to the effect for the given mesh.
  41270. * @param scene The scene the lights belongs to
  41271. * @param mesh The mesh we are binding the information to render
  41272. * @param effect The effect we are binding the data to
  41273. * @param defines The generated defines for the effect
  41274. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41275. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41276. */
  41277. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41278. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41279. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41280. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41281. for (var i = 0; i < len; i++) {
  41282. var light = mesh._lightSources[i];
  41283. var iAsString = i.toString();
  41284. var scaledIntensity = light.getScaledIntensity();
  41285. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41286. MaterialHelper.BindLightProperties(light, effect, i);
  41287. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41288. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41289. if (defines["SPECULARTERM"]) {
  41290. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41291. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41292. }
  41293. // Shadows
  41294. if (scene.shadowsEnabled) {
  41295. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41296. }
  41297. light._uniformBuffer.update();
  41298. }
  41299. };
  41300. /**
  41301. * Binds the fog information from the scene to the effect for the given mesh.
  41302. * @param scene The scene the lights belongs to
  41303. * @param mesh The mesh we are binding the information to render
  41304. * @param effect The effect we are binding the data to
  41305. * @param linearSpace Defines if the fog effect is applied in linear space
  41306. */
  41307. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41308. if (linearSpace === void 0) { linearSpace = false; }
  41309. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41310. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41311. // Convert fog color to linear space if used in a linear space computed shader.
  41312. if (linearSpace) {
  41313. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41314. effect.setColor3("vFogColor", this._tempFogColor);
  41315. }
  41316. else {
  41317. effect.setColor3("vFogColor", scene.fogColor);
  41318. }
  41319. }
  41320. };
  41321. /**
  41322. * Binds the bones information from the mesh to the effect.
  41323. * @param mesh The mesh we are binding the information to render
  41324. * @param effect The effect we are binding the data to
  41325. */
  41326. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41327. if (!effect || !mesh) {
  41328. return;
  41329. }
  41330. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41331. mesh.computeBonesUsingShaders = false;
  41332. }
  41333. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41334. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41335. if (matrices) {
  41336. effect.setMatrices("mBones", matrices);
  41337. }
  41338. }
  41339. };
  41340. /**
  41341. * Binds the morph targets information from the mesh to the effect.
  41342. * @param abstractMesh The mesh we are binding the information to render
  41343. * @param effect The effect we are binding the data to
  41344. */
  41345. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41346. var manager = abstractMesh.morphTargetManager;
  41347. if (!abstractMesh || !manager) {
  41348. return;
  41349. }
  41350. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41351. };
  41352. /**
  41353. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41354. * @param defines The generated defines used in the effect
  41355. * @param effect The effect we are binding the data to
  41356. * @param scene The scene we are willing to render with logarithmic scale for
  41357. */
  41358. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41359. if (defines["LOGARITHMICDEPTH"]) {
  41360. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41361. }
  41362. };
  41363. /**
  41364. * Binds the clip plane information from the scene to the effect.
  41365. * @param scene The scene the clip plane information are extracted from
  41366. * @param effect The effect we are binding the data to
  41367. */
  41368. MaterialHelper.BindClipPlane = function (effect, scene) {
  41369. if (scene.clipPlane) {
  41370. var clipPlane = scene.clipPlane;
  41371. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41372. }
  41373. if (scene.clipPlane2) {
  41374. var clipPlane = scene.clipPlane2;
  41375. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41376. }
  41377. if (scene.clipPlane3) {
  41378. var clipPlane = scene.clipPlane3;
  41379. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41380. }
  41381. if (scene.clipPlane4) {
  41382. var clipPlane = scene.clipPlane4;
  41383. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41384. }
  41385. };
  41386. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41387. return MaterialHelper;
  41388. }());
  41389. BABYLON.MaterialHelper = MaterialHelper;
  41390. })(BABYLON || (BABYLON = {}));
  41391. //# sourceMappingURL=babylon.materialHelper.js.map
  41392. var BABYLON;
  41393. (function (BABYLON) {
  41394. var PushMaterial = /** @class */ (function (_super) {
  41395. __extends(PushMaterial, _super);
  41396. function PushMaterial(name, scene) {
  41397. var _this = _super.call(this, name, scene) || this;
  41398. _this._normalMatrix = new BABYLON.Matrix();
  41399. _this.storeEffectOnSubMeshes = true;
  41400. return _this;
  41401. }
  41402. PushMaterial.prototype.getEffect = function () {
  41403. return this._activeEffect;
  41404. };
  41405. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41406. if (!mesh) {
  41407. return false;
  41408. }
  41409. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41410. return true;
  41411. }
  41412. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41413. };
  41414. /**
  41415. * Binds the given world matrix to the active effect
  41416. *
  41417. * @param world the matrix to bind
  41418. */
  41419. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41420. this._activeEffect.setMatrix("world", world);
  41421. };
  41422. /**
  41423. * Binds the given normal matrix to the active effect
  41424. *
  41425. * @param normalMatrix the matrix to bind
  41426. */
  41427. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41428. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41429. };
  41430. PushMaterial.prototype.bind = function (world, mesh) {
  41431. if (!mesh) {
  41432. return;
  41433. }
  41434. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41435. };
  41436. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41437. if (effect === void 0) { effect = null; }
  41438. _super.prototype._afterBind.call(this, mesh);
  41439. this.getScene()._cachedEffect = effect;
  41440. };
  41441. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41442. if (visibility === void 0) { visibility = 1; }
  41443. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41444. };
  41445. return PushMaterial;
  41446. }(BABYLON.Material));
  41447. BABYLON.PushMaterial = PushMaterial;
  41448. })(BABYLON || (BABYLON = {}));
  41449. //# sourceMappingURL=babylon.pushMaterial.js.map
  41450. var BABYLON;
  41451. (function (BABYLON) {
  41452. /** @hidden */
  41453. var StandardMaterialDefines = /** @class */ (function (_super) {
  41454. __extends(StandardMaterialDefines, _super);
  41455. function StandardMaterialDefines() {
  41456. var _this = _super.call(this) || this;
  41457. _this.MAINUV1 = false;
  41458. _this.MAINUV2 = false;
  41459. _this.DIFFUSE = false;
  41460. _this.DIFFUSEDIRECTUV = 0;
  41461. _this.AMBIENT = false;
  41462. _this.AMBIENTDIRECTUV = 0;
  41463. _this.OPACITY = false;
  41464. _this.OPACITYDIRECTUV = 0;
  41465. _this.OPACITYRGB = false;
  41466. _this.REFLECTION = false;
  41467. _this.EMISSIVE = false;
  41468. _this.EMISSIVEDIRECTUV = 0;
  41469. _this.SPECULAR = false;
  41470. _this.SPECULARDIRECTUV = 0;
  41471. _this.BUMP = false;
  41472. _this.BUMPDIRECTUV = 0;
  41473. _this.PARALLAX = false;
  41474. _this.PARALLAXOCCLUSION = false;
  41475. _this.SPECULAROVERALPHA = false;
  41476. _this.CLIPPLANE = false;
  41477. _this.CLIPPLANE2 = false;
  41478. _this.CLIPPLANE3 = false;
  41479. _this.CLIPPLANE4 = false;
  41480. _this.ALPHATEST = false;
  41481. _this.DEPTHPREPASS = false;
  41482. _this.ALPHAFROMDIFFUSE = false;
  41483. _this.POINTSIZE = false;
  41484. _this.FOG = false;
  41485. _this.SPECULARTERM = false;
  41486. _this.DIFFUSEFRESNEL = false;
  41487. _this.OPACITYFRESNEL = false;
  41488. _this.REFLECTIONFRESNEL = false;
  41489. _this.REFRACTIONFRESNEL = false;
  41490. _this.EMISSIVEFRESNEL = false;
  41491. _this.FRESNEL = false;
  41492. _this.NORMAL = false;
  41493. _this.UV1 = false;
  41494. _this.UV2 = false;
  41495. _this.VERTEXCOLOR = false;
  41496. _this.VERTEXALPHA = false;
  41497. _this.NUM_BONE_INFLUENCERS = 0;
  41498. _this.BonesPerMesh = 0;
  41499. _this.INSTANCES = false;
  41500. _this.GLOSSINESS = false;
  41501. _this.ROUGHNESS = false;
  41502. _this.EMISSIVEASILLUMINATION = false;
  41503. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41504. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41505. _this.LIGHTMAP = false;
  41506. _this.LIGHTMAPDIRECTUV = 0;
  41507. _this.OBJECTSPACE_NORMALMAP = false;
  41508. _this.USELIGHTMAPASSHADOWMAP = false;
  41509. _this.REFLECTIONMAP_3D = false;
  41510. _this.REFLECTIONMAP_SPHERICAL = false;
  41511. _this.REFLECTIONMAP_PLANAR = false;
  41512. _this.REFLECTIONMAP_CUBIC = false;
  41513. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41514. _this.REFLECTIONMAP_PROJECTION = false;
  41515. _this.REFLECTIONMAP_SKYBOX = false;
  41516. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41517. _this.REFLECTIONMAP_EXPLICIT = false;
  41518. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41519. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41520. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41521. _this.INVERTCUBICMAP = false;
  41522. _this.LOGARITHMICDEPTH = false;
  41523. _this.REFRACTION = false;
  41524. _this.REFRACTIONMAP_3D = false;
  41525. _this.REFLECTIONOVERALPHA = false;
  41526. _this.TWOSIDEDLIGHTING = false;
  41527. _this.SHADOWFLOAT = false;
  41528. _this.MORPHTARGETS = false;
  41529. _this.MORPHTARGETS_NORMAL = false;
  41530. _this.MORPHTARGETS_TANGENT = false;
  41531. _this.NUM_MORPH_INFLUENCERS = 0;
  41532. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41533. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41534. _this.IMAGEPROCESSING = false;
  41535. _this.VIGNETTE = false;
  41536. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41537. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41538. _this.TONEMAPPING = false;
  41539. _this.TONEMAPPING_ACES = false;
  41540. _this.CONTRAST = false;
  41541. _this.COLORCURVES = false;
  41542. _this.COLORGRADING = false;
  41543. _this.COLORGRADING3D = false;
  41544. _this.SAMPLER3DGREENDEPTH = false;
  41545. _this.SAMPLER3DBGRMAP = false;
  41546. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41547. /**
  41548. * If the reflection texture on this material is in linear color space
  41549. * @hidden
  41550. */
  41551. _this.IS_REFLECTION_LINEAR = false;
  41552. /**
  41553. * If the refraction texture on this material is in linear color space
  41554. * @hidden
  41555. */
  41556. _this.IS_REFRACTION_LINEAR = false;
  41557. _this.EXPOSURE = false;
  41558. _this.rebuild();
  41559. return _this;
  41560. }
  41561. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41562. var modes = [
  41563. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41564. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41565. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41566. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41567. ];
  41568. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41569. var mode = modes_1[_i];
  41570. this[mode] = (mode === modeToEnable);
  41571. }
  41572. };
  41573. return StandardMaterialDefines;
  41574. }(BABYLON.MaterialDefines));
  41575. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41576. var StandardMaterial = /** @class */ (function (_super) {
  41577. __extends(StandardMaterial, _super);
  41578. function StandardMaterial(name, scene) {
  41579. var _this = _super.call(this, name, scene) || this;
  41580. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41581. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41582. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41583. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41584. _this.specularPower = 64;
  41585. _this._useAlphaFromDiffuseTexture = false;
  41586. _this._useEmissiveAsIllumination = false;
  41587. _this._linkEmissiveWithDiffuse = false;
  41588. _this._useSpecularOverAlpha = false;
  41589. _this._useReflectionOverAlpha = false;
  41590. _this._disableLighting = false;
  41591. _this._useObjectSpaceNormalMap = false;
  41592. _this._useParallax = false;
  41593. _this._useParallaxOcclusion = false;
  41594. _this.parallaxScaleBias = 0.05;
  41595. _this._roughness = 0;
  41596. _this.indexOfRefraction = 0.98;
  41597. _this.invertRefractionY = true;
  41598. /**
  41599. * Defines the alpha limits in alpha test mode
  41600. */
  41601. _this.alphaCutOff = 0.4;
  41602. _this._useLightmapAsShadowmap = false;
  41603. _this._useReflectionFresnelFromSpecular = false;
  41604. _this._useGlossinessFromSpecularMapAlpha = false;
  41605. _this._maxSimultaneousLights = 4;
  41606. /**
  41607. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41608. */
  41609. _this._invertNormalMapX = false;
  41610. /**
  41611. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41612. */
  41613. _this._invertNormalMapY = false;
  41614. /**
  41615. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41616. */
  41617. _this._twoSidedLighting = false;
  41618. _this._renderTargets = new BABYLON.SmartArray(16);
  41619. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41620. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41621. // Setup the default processing configuration to the scene.
  41622. _this._attachImageProcessingConfiguration(null);
  41623. _this.getRenderTargetTextures = function () {
  41624. _this._renderTargets.reset();
  41625. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41626. _this._renderTargets.push(_this._reflectionTexture);
  41627. }
  41628. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41629. _this._renderTargets.push(_this._refractionTexture);
  41630. }
  41631. return _this._renderTargets;
  41632. };
  41633. return _this;
  41634. }
  41635. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41636. /**
  41637. * Gets the image processing configuration used either in this material.
  41638. */
  41639. get: function () {
  41640. return this._imageProcessingConfiguration;
  41641. },
  41642. /**
  41643. * Sets the Default image processing configuration used either in the this material.
  41644. *
  41645. * If sets to null, the scene one is in use.
  41646. */
  41647. set: function (value) {
  41648. this._attachImageProcessingConfiguration(value);
  41649. // Ensure the effect will be rebuilt.
  41650. this._markAllSubMeshesAsTexturesDirty();
  41651. },
  41652. enumerable: true,
  41653. configurable: true
  41654. });
  41655. /**
  41656. * Attaches a new image processing configuration to the Standard Material.
  41657. * @param configuration
  41658. */
  41659. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41660. var _this = this;
  41661. if (configuration === this._imageProcessingConfiguration) {
  41662. return;
  41663. }
  41664. // Detaches observer.
  41665. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41666. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41667. }
  41668. // Pick the scene configuration if needed.
  41669. if (!configuration) {
  41670. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41671. }
  41672. else {
  41673. this._imageProcessingConfiguration = configuration;
  41674. }
  41675. // Attaches observer.
  41676. if (this._imageProcessingConfiguration) {
  41677. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41678. _this._markAllSubMeshesAsImageProcessingDirty();
  41679. });
  41680. }
  41681. };
  41682. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41683. /**
  41684. * Gets wether the color curves effect is enabled.
  41685. */
  41686. get: function () {
  41687. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41688. },
  41689. /**
  41690. * Sets wether the color curves effect is enabled.
  41691. */
  41692. set: function (value) {
  41693. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41694. },
  41695. enumerable: true,
  41696. configurable: true
  41697. });
  41698. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41699. /**
  41700. * Gets wether the color grading effect is enabled.
  41701. */
  41702. get: function () {
  41703. return this.imageProcessingConfiguration.colorGradingEnabled;
  41704. },
  41705. /**
  41706. * Gets wether the color grading effect is enabled.
  41707. */
  41708. set: function (value) {
  41709. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41715. /**
  41716. * Gets wether tonemapping is enabled or not.
  41717. */
  41718. get: function () {
  41719. return this._imageProcessingConfiguration.toneMappingEnabled;
  41720. },
  41721. /**
  41722. * Sets wether tonemapping is enabled or not
  41723. */
  41724. set: function (value) {
  41725. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. ;
  41731. ;
  41732. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41733. /**
  41734. * The camera exposure used on this material.
  41735. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41736. * This corresponds to a photographic exposure.
  41737. */
  41738. get: function () {
  41739. return this._imageProcessingConfiguration.exposure;
  41740. },
  41741. /**
  41742. * The camera exposure used on this material.
  41743. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41744. * This corresponds to a photographic exposure.
  41745. */
  41746. set: function (value) {
  41747. this._imageProcessingConfiguration.exposure = value;
  41748. },
  41749. enumerable: true,
  41750. configurable: true
  41751. });
  41752. ;
  41753. ;
  41754. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41755. /**
  41756. * Gets The camera contrast used on this material.
  41757. */
  41758. get: function () {
  41759. return this._imageProcessingConfiguration.contrast;
  41760. },
  41761. /**
  41762. * Sets The camera contrast used on this material.
  41763. */
  41764. set: function (value) {
  41765. this._imageProcessingConfiguration.contrast = value;
  41766. },
  41767. enumerable: true,
  41768. configurable: true
  41769. });
  41770. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41771. /**
  41772. * Gets the Color Grading 2D Lookup Texture.
  41773. */
  41774. get: function () {
  41775. return this._imageProcessingConfiguration.colorGradingTexture;
  41776. },
  41777. /**
  41778. * Sets the Color Grading 2D Lookup Texture.
  41779. */
  41780. set: function (value) {
  41781. this._imageProcessingConfiguration.colorGradingTexture = value;
  41782. },
  41783. enumerable: true,
  41784. configurable: true
  41785. });
  41786. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41787. /**
  41788. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41789. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41790. * 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;
  41791. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41792. */
  41793. get: function () {
  41794. return this._imageProcessingConfiguration.colorCurves;
  41795. },
  41796. /**
  41797. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41798. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41799. * 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;
  41800. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41801. */
  41802. set: function (value) {
  41803. this._imageProcessingConfiguration.colorCurves = value;
  41804. },
  41805. enumerable: true,
  41806. configurable: true
  41807. });
  41808. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41809. /**
  41810. * Gets a boolean indicating that current material needs to register RTT
  41811. */
  41812. get: function () {
  41813. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41814. return true;
  41815. }
  41816. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41817. return true;
  41818. }
  41819. return false;
  41820. },
  41821. enumerable: true,
  41822. configurable: true
  41823. });
  41824. StandardMaterial.prototype.getClassName = function () {
  41825. return "StandardMaterial";
  41826. };
  41827. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41828. get: function () {
  41829. return this._useLogarithmicDepth;
  41830. },
  41831. set: function (value) {
  41832. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41833. this._markAllSubMeshesAsMiscDirty();
  41834. },
  41835. enumerable: true,
  41836. configurable: true
  41837. });
  41838. StandardMaterial.prototype.needAlphaBlending = function () {
  41839. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41840. };
  41841. StandardMaterial.prototype.needAlphaTesting = function () {
  41842. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41843. };
  41844. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41845. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41846. };
  41847. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41848. return this._diffuseTexture;
  41849. };
  41850. /**
  41851. * Child classes can use it to update shaders
  41852. */
  41853. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41854. if (useInstances === void 0) { useInstances = false; }
  41855. if (subMesh.effect && this.isFrozen) {
  41856. if (this._wasPreviouslyReady) {
  41857. return true;
  41858. }
  41859. }
  41860. if (!subMesh._materialDefines) {
  41861. subMesh._materialDefines = new StandardMaterialDefines();
  41862. }
  41863. var scene = this.getScene();
  41864. var defines = subMesh._materialDefines;
  41865. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41866. if (defines._renderId === scene.getRenderId()) {
  41867. return true;
  41868. }
  41869. }
  41870. var engine = scene.getEngine();
  41871. // Lights
  41872. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41873. // Textures
  41874. if (defines._areTexturesDirty) {
  41875. defines._needUVs = false;
  41876. defines.MAINUV1 = false;
  41877. defines.MAINUV2 = false;
  41878. if (scene.texturesEnabled) {
  41879. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41880. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41881. return false;
  41882. }
  41883. else {
  41884. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41885. }
  41886. }
  41887. else {
  41888. defines.DIFFUSE = false;
  41889. }
  41890. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41891. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41892. return false;
  41893. }
  41894. else {
  41895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41896. }
  41897. }
  41898. else {
  41899. defines.AMBIENT = false;
  41900. }
  41901. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41902. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41903. return false;
  41904. }
  41905. else {
  41906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41907. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41908. }
  41909. }
  41910. else {
  41911. defines.OPACITY = false;
  41912. }
  41913. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41914. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41915. return false;
  41916. }
  41917. else {
  41918. defines._needNormals = true;
  41919. defines.REFLECTION = true;
  41920. defines.ROUGHNESS = (this._roughness > 0);
  41921. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41922. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41923. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41924. switch (this._reflectionTexture.coordinatesMode) {
  41925. case BABYLON.Texture.EXPLICIT_MODE:
  41926. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41927. break;
  41928. case BABYLON.Texture.PLANAR_MODE:
  41929. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41930. break;
  41931. case BABYLON.Texture.PROJECTION_MODE:
  41932. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41933. break;
  41934. case BABYLON.Texture.SKYBOX_MODE:
  41935. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41936. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41937. break;
  41938. case BABYLON.Texture.SPHERICAL_MODE:
  41939. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41940. break;
  41941. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41942. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41943. break;
  41944. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41945. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41946. break;
  41947. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41948. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41949. break;
  41950. case BABYLON.Texture.CUBIC_MODE:
  41951. case BABYLON.Texture.INVCUBIC_MODE:
  41952. default:
  41953. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41954. break;
  41955. }
  41956. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41957. }
  41958. }
  41959. else {
  41960. defines.REFLECTION = false;
  41961. }
  41962. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41963. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41964. return false;
  41965. }
  41966. else {
  41967. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41968. }
  41969. }
  41970. else {
  41971. defines.EMISSIVE = false;
  41972. }
  41973. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41974. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41975. return false;
  41976. }
  41977. else {
  41978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41979. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41980. }
  41981. }
  41982. else {
  41983. defines.LIGHTMAP = false;
  41984. }
  41985. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41986. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41987. return false;
  41988. }
  41989. else {
  41990. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41991. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41992. }
  41993. }
  41994. else {
  41995. defines.SPECULAR = false;
  41996. }
  41997. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41998. // Bump texure can not be not blocking.
  41999. if (!this._bumpTexture.isReady()) {
  42000. return false;
  42001. }
  42002. else {
  42003. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42004. defines.PARALLAX = this._useParallax;
  42005. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42006. }
  42007. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42008. }
  42009. else {
  42010. defines.BUMP = false;
  42011. }
  42012. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42013. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42014. return false;
  42015. }
  42016. else {
  42017. defines._needUVs = true;
  42018. defines.REFRACTION = true;
  42019. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42020. }
  42021. }
  42022. else {
  42023. defines.REFRACTION = false;
  42024. }
  42025. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42026. }
  42027. else {
  42028. defines.DIFFUSE = false;
  42029. defines.AMBIENT = false;
  42030. defines.OPACITY = false;
  42031. defines.REFLECTION = false;
  42032. defines.EMISSIVE = false;
  42033. defines.LIGHTMAP = false;
  42034. defines.BUMP = false;
  42035. defines.REFRACTION = false;
  42036. }
  42037. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42038. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42039. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42040. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42041. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42042. }
  42043. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42044. if (!this._imageProcessingConfiguration.isReady()) {
  42045. return false;
  42046. }
  42047. this._imageProcessingConfiguration.prepareDefines(defines);
  42048. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42049. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42050. }
  42051. if (defines._areFresnelDirty) {
  42052. if (StandardMaterial.FresnelEnabled) {
  42053. // Fresnel
  42054. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42055. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42056. this._reflectionFresnelParameters) {
  42057. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42058. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42059. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42060. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42061. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42062. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42063. defines._needNormals = true;
  42064. defines.FRESNEL = true;
  42065. }
  42066. }
  42067. else {
  42068. defines.FRESNEL = false;
  42069. }
  42070. }
  42071. // Misc.
  42072. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42073. // Attribs
  42074. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42075. // Values that need to be evaluated on every frame
  42076. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42077. // Get correct effect
  42078. if (defines.isDirty) {
  42079. defines.markAsProcessed();
  42080. scene.resetCachedMaterial();
  42081. // Fallbacks
  42082. var fallbacks = new BABYLON.EffectFallbacks();
  42083. if (defines.REFLECTION) {
  42084. fallbacks.addFallback(0, "REFLECTION");
  42085. }
  42086. if (defines.SPECULAR) {
  42087. fallbacks.addFallback(0, "SPECULAR");
  42088. }
  42089. if (defines.BUMP) {
  42090. fallbacks.addFallback(0, "BUMP");
  42091. }
  42092. if (defines.PARALLAX) {
  42093. fallbacks.addFallback(1, "PARALLAX");
  42094. }
  42095. if (defines.PARALLAXOCCLUSION) {
  42096. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42097. }
  42098. if (defines.SPECULAROVERALPHA) {
  42099. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42100. }
  42101. if (defines.FOG) {
  42102. fallbacks.addFallback(1, "FOG");
  42103. }
  42104. if (defines.POINTSIZE) {
  42105. fallbacks.addFallback(0, "POINTSIZE");
  42106. }
  42107. if (defines.LOGARITHMICDEPTH) {
  42108. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42109. }
  42110. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42111. if (defines.SPECULARTERM) {
  42112. fallbacks.addFallback(0, "SPECULARTERM");
  42113. }
  42114. if (defines.DIFFUSEFRESNEL) {
  42115. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42116. }
  42117. if (defines.OPACITYFRESNEL) {
  42118. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42119. }
  42120. if (defines.REFLECTIONFRESNEL) {
  42121. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42122. }
  42123. if (defines.EMISSIVEFRESNEL) {
  42124. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42125. }
  42126. if (defines.FRESNEL) {
  42127. fallbacks.addFallback(4, "FRESNEL");
  42128. }
  42129. //Attributes
  42130. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42131. if (defines.NORMAL) {
  42132. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42133. }
  42134. if (defines.UV1) {
  42135. attribs.push(BABYLON.VertexBuffer.UVKind);
  42136. }
  42137. if (defines.UV2) {
  42138. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42139. }
  42140. if (defines.VERTEXCOLOR) {
  42141. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42142. }
  42143. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42144. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42145. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42146. var shaderName = "default";
  42147. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42148. "vFogInfos", "vFogColor", "pointSize",
  42149. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42150. "mBones",
  42151. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42152. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42153. "vReflectionPosition", "vReflectionSize",
  42154. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42155. ];
  42156. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42157. var uniformBuffers = ["Material", "Scene"];
  42158. if (BABYLON.ImageProcessingConfiguration) {
  42159. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42160. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42161. }
  42162. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42163. uniformsNames: uniforms,
  42164. uniformBuffersNames: uniformBuffers,
  42165. samplers: samplers,
  42166. defines: defines,
  42167. maxSimultaneousLights: this._maxSimultaneousLights
  42168. });
  42169. if (this.customShaderNameResolve) {
  42170. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42171. }
  42172. var join = defines.toString();
  42173. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42174. attributes: attribs,
  42175. uniformsNames: uniforms,
  42176. uniformBuffersNames: uniformBuffers,
  42177. samplers: samplers,
  42178. defines: join,
  42179. fallbacks: fallbacks,
  42180. onCompiled: this.onCompiled,
  42181. onError: this.onError,
  42182. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42183. }, engine), defines);
  42184. this.buildUniformLayout();
  42185. }
  42186. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42187. return false;
  42188. }
  42189. defines._renderId = scene.getRenderId();
  42190. this._wasPreviouslyReady = true;
  42191. return true;
  42192. };
  42193. StandardMaterial.prototype.buildUniformLayout = function () {
  42194. // Order is important !
  42195. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42196. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42197. this._uniformBuffer.addUniform("opacityParts", 4);
  42198. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42199. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42200. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42201. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42202. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42203. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42204. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42205. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42206. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42207. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42208. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42209. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42210. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42211. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42212. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42213. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42214. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42215. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42216. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42217. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42218. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42219. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42220. this._uniformBuffer.addUniform("specularMatrix", 16);
  42221. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42222. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42223. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42224. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42225. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42226. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42227. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42228. this._uniformBuffer.addUniform("pointSize", 1);
  42229. this._uniformBuffer.create();
  42230. };
  42231. StandardMaterial.prototype.unbind = function () {
  42232. if (this._activeEffect) {
  42233. var needFlag = false;
  42234. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42235. this._activeEffect.setTexture("reflection2DSampler", null);
  42236. needFlag = true;
  42237. }
  42238. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42239. this._activeEffect.setTexture("refraction2DSampler", null);
  42240. needFlag = true;
  42241. }
  42242. if (needFlag) {
  42243. this._markAllSubMeshesAsTexturesDirty();
  42244. }
  42245. }
  42246. _super.prototype.unbind.call(this);
  42247. };
  42248. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42249. var scene = this.getScene();
  42250. var defines = subMesh._materialDefines;
  42251. if (!defines) {
  42252. return;
  42253. }
  42254. var effect = subMesh.effect;
  42255. if (!effect) {
  42256. return;
  42257. }
  42258. this._activeEffect = effect;
  42259. // Matrices
  42260. this.bindOnlyWorldMatrix(world);
  42261. // Normal Matrix
  42262. if (defines.OBJECTSPACE_NORMALMAP) {
  42263. world.toNormalMatrix(this._normalMatrix);
  42264. this.bindOnlyNormalMatrix(this._normalMatrix);
  42265. }
  42266. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42267. // Bones
  42268. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42269. if (mustRebind) {
  42270. this._uniformBuffer.bindToEffect(effect, "Material");
  42271. this.bindViewProjection(effect);
  42272. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42273. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42274. // Fresnel
  42275. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42276. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42277. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42278. }
  42279. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42280. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42281. }
  42282. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42283. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42284. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42285. }
  42286. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42287. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42288. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42289. }
  42290. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42291. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42292. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42293. }
  42294. }
  42295. // Textures
  42296. if (scene.texturesEnabled) {
  42297. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42298. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42299. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42300. if (this._diffuseTexture.hasAlpha) {
  42301. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42302. }
  42303. }
  42304. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42305. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42306. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42307. }
  42308. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42309. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42310. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42311. }
  42312. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42313. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42314. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42315. if (this._reflectionTexture.boundingBoxSize) {
  42316. var cubeTexture = this._reflectionTexture;
  42317. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42318. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42319. }
  42320. }
  42321. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42322. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42323. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42324. }
  42325. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42326. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42327. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42328. }
  42329. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42330. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42331. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42332. }
  42333. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42334. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42335. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42336. if (scene._mirroredCameraPosition) {
  42337. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42338. }
  42339. else {
  42340. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42341. }
  42342. }
  42343. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42344. var depth = 1.0;
  42345. if (!this._refractionTexture.isCube) {
  42346. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42347. if (this._refractionTexture.depth) {
  42348. depth = this._refractionTexture.depth;
  42349. }
  42350. }
  42351. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42352. }
  42353. }
  42354. // Point size
  42355. if (this.pointsCloud) {
  42356. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42357. }
  42358. if (defines.SPECULARTERM) {
  42359. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42360. }
  42361. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42362. // Diffuse
  42363. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42364. }
  42365. // Textures
  42366. if (scene.texturesEnabled) {
  42367. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42368. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42369. }
  42370. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42371. effect.setTexture("ambientSampler", this._ambientTexture);
  42372. }
  42373. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42374. effect.setTexture("opacitySampler", this._opacityTexture);
  42375. }
  42376. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42377. if (this._reflectionTexture.isCube) {
  42378. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42379. }
  42380. else {
  42381. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42382. }
  42383. }
  42384. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42385. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42386. }
  42387. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42388. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42389. }
  42390. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42391. effect.setTexture("specularSampler", this._specularTexture);
  42392. }
  42393. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42394. effect.setTexture("bumpSampler", this._bumpTexture);
  42395. }
  42396. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42397. var depth = 1.0;
  42398. if (this._refractionTexture.isCube) {
  42399. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42400. }
  42401. else {
  42402. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42403. }
  42404. }
  42405. }
  42406. // Clip plane
  42407. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42408. // Colors
  42409. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42410. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42411. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42412. }
  42413. if (mustRebind || !this.isFrozen) {
  42414. // Lights
  42415. if (scene.lightsEnabled && !this._disableLighting) {
  42416. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42417. }
  42418. // View
  42419. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42420. this.bindView(effect);
  42421. }
  42422. // Fog
  42423. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42424. // Morph targets
  42425. if (defines.NUM_MORPH_INFLUENCERS) {
  42426. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42427. }
  42428. // Log. depth
  42429. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42430. // image processing
  42431. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42432. this._imageProcessingConfiguration.bind(this._activeEffect);
  42433. }
  42434. }
  42435. this._uniformBuffer.update();
  42436. this._afterBind(mesh, this._activeEffect);
  42437. };
  42438. StandardMaterial.prototype.getAnimatables = function () {
  42439. var results = [];
  42440. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42441. results.push(this._diffuseTexture);
  42442. }
  42443. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42444. results.push(this._ambientTexture);
  42445. }
  42446. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42447. results.push(this._opacityTexture);
  42448. }
  42449. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42450. results.push(this._reflectionTexture);
  42451. }
  42452. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42453. results.push(this._emissiveTexture);
  42454. }
  42455. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42456. results.push(this._specularTexture);
  42457. }
  42458. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42459. results.push(this._bumpTexture);
  42460. }
  42461. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42462. results.push(this._lightmapTexture);
  42463. }
  42464. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42465. results.push(this._refractionTexture);
  42466. }
  42467. return results;
  42468. };
  42469. StandardMaterial.prototype.getActiveTextures = function () {
  42470. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42471. if (this._diffuseTexture) {
  42472. activeTextures.push(this._diffuseTexture);
  42473. }
  42474. if (this._ambientTexture) {
  42475. activeTextures.push(this._ambientTexture);
  42476. }
  42477. if (this._opacityTexture) {
  42478. activeTextures.push(this._opacityTexture);
  42479. }
  42480. if (this._reflectionTexture) {
  42481. activeTextures.push(this._reflectionTexture);
  42482. }
  42483. if (this._emissiveTexture) {
  42484. activeTextures.push(this._emissiveTexture);
  42485. }
  42486. if (this._specularTexture) {
  42487. activeTextures.push(this._specularTexture);
  42488. }
  42489. if (this._bumpTexture) {
  42490. activeTextures.push(this._bumpTexture);
  42491. }
  42492. if (this._lightmapTexture) {
  42493. activeTextures.push(this._lightmapTexture);
  42494. }
  42495. if (this._refractionTexture) {
  42496. activeTextures.push(this._refractionTexture);
  42497. }
  42498. return activeTextures;
  42499. };
  42500. StandardMaterial.prototype.hasTexture = function (texture) {
  42501. if (_super.prototype.hasTexture.call(this, texture)) {
  42502. return true;
  42503. }
  42504. if (this._diffuseTexture === texture) {
  42505. return true;
  42506. }
  42507. if (this._ambientTexture === texture) {
  42508. return true;
  42509. }
  42510. if (this._opacityTexture === texture) {
  42511. return true;
  42512. }
  42513. if (this._reflectionTexture === texture) {
  42514. return true;
  42515. }
  42516. if (this._emissiveTexture === texture) {
  42517. return true;
  42518. }
  42519. if (this._specularTexture === texture) {
  42520. return true;
  42521. }
  42522. if (this._bumpTexture === texture) {
  42523. return true;
  42524. }
  42525. if (this._lightmapTexture === texture) {
  42526. return true;
  42527. }
  42528. if (this._refractionTexture === texture) {
  42529. return true;
  42530. }
  42531. return false;
  42532. };
  42533. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42534. if (forceDisposeTextures) {
  42535. if (this._diffuseTexture) {
  42536. this._diffuseTexture.dispose();
  42537. }
  42538. if (this._ambientTexture) {
  42539. this._ambientTexture.dispose();
  42540. }
  42541. if (this._opacityTexture) {
  42542. this._opacityTexture.dispose();
  42543. }
  42544. if (this._reflectionTexture) {
  42545. this._reflectionTexture.dispose();
  42546. }
  42547. if (this._emissiveTexture) {
  42548. this._emissiveTexture.dispose();
  42549. }
  42550. if (this._specularTexture) {
  42551. this._specularTexture.dispose();
  42552. }
  42553. if (this._bumpTexture) {
  42554. this._bumpTexture.dispose();
  42555. }
  42556. if (this._lightmapTexture) {
  42557. this._lightmapTexture.dispose();
  42558. }
  42559. if (this._refractionTexture) {
  42560. this._refractionTexture.dispose();
  42561. }
  42562. }
  42563. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42564. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42565. }
  42566. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42567. };
  42568. StandardMaterial.prototype.clone = function (name) {
  42569. var _this = this;
  42570. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42571. result.name = name;
  42572. result.id = name;
  42573. return result;
  42574. };
  42575. StandardMaterial.prototype.serialize = function () {
  42576. return BABYLON.SerializationHelper.Serialize(this);
  42577. };
  42578. // Statics
  42579. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42580. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42581. };
  42582. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42583. get: function () {
  42584. return StandardMaterial._DiffuseTextureEnabled;
  42585. },
  42586. set: function (value) {
  42587. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42588. return;
  42589. }
  42590. StandardMaterial._DiffuseTextureEnabled = value;
  42591. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42592. },
  42593. enumerable: true,
  42594. configurable: true
  42595. });
  42596. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42597. get: function () {
  42598. return StandardMaterial._AmbientTextureEnabled;
  42599. },
  42600. set: function (value) {
  42601. if (StandardMaterial._AmbientTextureEnabled === value) {
  42602. return;
  42603. }
  42604. StandardMaterial._AmbientTextureEnabled = value;
  42605. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42606. },
  42607. enumerable: true,
  42608. configurable: true
  42609. });
  42610. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42611. get: function () {
  42612. return StandardMaterial._OpacityTextureEnabled;
  42613. },
  42614. set: function (value) {
  42615. if (StandardMaterial._OpacityTextureEnabled === value) {
  42616. return;
  42617. }
  42618. StandardMaterial._OpacityTextureEnabled = value;
  42619. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42620. },
  42621. enumerable: true,
  42622. configurable: true
  42623. });
  42624. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42625. get: function () {
  42626. return StandardMaterial._ReflectionTextureEnabled;
  42627. },
  42628. set: function (value) {
  42629. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42630. return;
  42631. }
  42632. StandardMaterial._ReflectionTextureEnabled = value;
  42633. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42634. },
  42635. enumerable: true,
  42636. configurable: true
  42637. });
  42638. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42639. get: function () {
  42640. return StandardMaterial._EmissiveTextureEnabled;
  42641. },
  42642. set: function (value) {
  42643. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42644. return;
  42645. }
  42646. StandardMaterial._EmissiveTextureEnabled = value;
  42647. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42648. },
  42649. enumerable: true,
  42650. configurable: true
  42651. });
  42652. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42653. get: function () {
  42654. return StandardMaterial._SpecularTextureEnabled;
  42655. },
  42656. set: function (value) {
  42657. if (StandardMaterial._SpecularTextureEnabled === value) {
  42658. return;
  42659. }
  42660. StandardMaterial._SpecularTextureEnabled = value;
  42661. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42662. },
  42663. enumerable: true,
  42664. configurable: true
  42665. });
  42666. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42667. get: function () {
  42668. return StandardMaterial._BumpTextureEnabled;
  42669. },
  42670. set: function (value) {
  42671. if (StandardMaterial._BumpTextureEnabled === value) {
  42672. return;
  42673. }
  42674. StandardMaterial._BumpTextureEnabled = value;
  42675. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42676. },
  42677. enumerable: true,
  42678. configurable: true
  42679. });
  42680. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42681. get: function () {
  42682. return StandardMaterial._LightmapTextureEnabled;
  42683. },
  42684. set: function (value) {
  42685. if (StandardMaterial._LightmapTextureEnabled === value) {
  42686. return;
  42687. }
  42688. StandardMaterial._LightmapTextureEnabled = value;
  42689. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42690. },
  42691. enumerable: true,
  42692. configurable: true
  42693. });
  42694. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42695. get: function () {
  42696. return StandardMaterial._RefractionTextureEnabled;
  42697. },
  42698. set: function (value) {
  42699. if (StandardMaterial._RefractionTextureEnabled === value) {
  42700. return;
  42701. }
  42702. StandardMaterial._RefractionTextureEnabled = value;
  42703. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42704. },
  42705. enumerable: true,
  42706. configurable: true
  42707. });
  42708. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42709. get: function () {
  42710. return StandardMaterial._ColorGradingTextureEnabled;
  42711. },
  42712. set: function (value) {
  42713. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42714. return;
  42715. }
  42716. StandardMaterial._ColorGradingTextureEnabled = value;
  42717. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42718. },
  42719. enumerable: true,
  42720. configurable: true
  42721. });
  42722. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42723. get: function () {
  42724. return StandardMaterial._FresnelEnabled;
  42725. },
  42726. set: function (value) {
  42727. if (StandardMaterial._FresnelEnabled === value) {
  42728. return;
  42729. }
  42730. StandardMaterial._FresnelEnabled = value;
  42731. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42732. },
  42733. enumerable: true,
  42734. configurable: true
  42735. });
  42736. // Flags used to enable or disable a type of texture for all Standard Materials
  42737. StandardMaterial._DiffuseTextureEnabled = true;
  42738. StandardMaterial._AmbientTextureEnabled = true;
  42739. StandardMaterial._OpacityTextureEnabled = true;
  42740. StandardMaterial._ReflectionTextureEnabled = true;
  42741. StandardMaterial._EmissiveTextureEnabled = true;
  42742. StandardMaterial._SpecularTextureEnabled = true;
  42743. StandardMaterial._BumpTextureEnabled = true;
  42744. StandardMaterial._LightmapTextureEnabled = true;
  42745. StandardMaterial._RefractionTextureEnabled = true;
  42746. StandardMaterial._ColorGradingTextureEnabled = true;
  42747. StandardMaterial._FresnelEnabled = true;
  42748. __decorate([
  42749. BABYLON.serializeAsTexture("diffuseTexture")
  42750. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42751. __decorate([
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42753. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42754. __decorate([
  42755. BABYLON.serializeAsTexture("ambientTexture")
  42756. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42757. __decorate([
  42758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42759. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42760. __decorate([
  42761. BABYLON.serializeAsTexture("opacityTexture")
  42762. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42763. __decorate([
  42764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42765. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42766. __decorate([
  42767. BABYLON.serializeAsTexture("reflectionTexture")
  42768. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42769. __decorate([
  42770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42771. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42772. __decorate([
  42773. BABYLON.serializeAsTexture("emissiveTexture")
  42774. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42775. __decorate([
  42776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42777. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42778. __decorate([
  42779. BABYLON.serializeAsTexture("specularTexture")
  42780. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42781. __decorate([
  42782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42783. ], StandardMaterial.prototype, "specularTexture", void 0);
  42784. __decorate([
  42785. BABYLON.serializeAsTexture("bumpTexture")
  42786. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42787. __decorate([
  42788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42789. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42790. __decorate([
  42791. BABYLON.serializeAsTexture("lightmapTexture")
  42792. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42793. __decorate([
  42794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42795. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42796. __decorate([
  42797. BABYLON.serializeAsTexture("refractionTexture")
  42798. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42799. __decorate([
  42800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42801. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42802. __decorate([
  42803. BABYLON.serializeAsColor3("ambient")
  42804. ], StandardMaterial.prototype, "ambientColor", void 0);
  42805. __decorate([
  42806. BABYLON.serializeAsColor3("diffuse")
  42807. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42808. __decorate([
  42809. BABYLON.serializeAsColor3("specular")
  42810. ], StandardMaterial.prototype, "specularColor", void 0);
  42811. __decorate([
  42812. BABYLON.serializeAsColor3("emissive")
  42813. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42814. __decorate([
  42815. BABYLON.serialize()
  42816. ], StandardMaterial.prototype, "specularPower", void 0);
  42817. __decorate([
  42818. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42819. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42820. __decorate([
  42821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42822. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42823. __decorate([
  42824. BABYLON.serialize("useEmissiveAsIllumination")
  42825. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42826. __decorate([
  42827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42828. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42829. __decorate([
  42830. BABYLON.serialize("linkEmissiveWithDiffuse")
  42831. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42832. __decorate([
  42833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42834. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42835. __decorate([
  42836. BABYLON.serialize("useSpecularOverAlpha")
  42837. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42838. __decorate([
  42839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42840. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42841. __decorate([
  42842. BABYLON.serialize("useReflectionOverAlpha")
  42843. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42844. __decorate([
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42846. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42847. __decorate([
  42848. BABYLON.serialize("disableLighting")
  42849. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42850. __decorate([
  42851. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42852. ], StandardMaterial.prototype, "disableLighting", void 0);
  42853. __decorate([
  42854. BABYLON.serialize("useObjectSpaceNormalMap")
  42855. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42856. __decorate([
  42857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42858. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42859. __decorate([
  42860. BABYLON.serialize("useParallax")
  42861. ], StandardMaterial.prototype, "_useParallax", void 0);
  42862. __decorate([
  42863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42864. ], StandardMaterial.prototype, "useParallax", void 0);
  42865. __decorate([
  42866. BABYLON.serialize("useParallaxOcclusion")
  42867. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42868. __decorate([
  42869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42870. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42871. __decorate([
  42872. BABYLON.serialize()
  42873. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42874. __decorate([
  42875. BABYLON.serialize("roughness")
  42876. ], StandardMaterial.prototype, "_roughness", void 0);
  42877. __decorate([
  42878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42879. ], StandardMaterial.prototype, "roughness", void 0);
  42880. __decorate([
  42881. BABYLON.serialize()
  42882. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42883. __decorate([
  42884. BABYLON.serialize()
  42885. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42886. __decorate([
  42887. BABYLON.serialize()
  42888. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42889. __decorate([
  42890. BABYLON.serialize("useLightmapAsShadowmap")
  42891. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42892. __decorate([
  42893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42894. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42895. __decorate([
  42896. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42897. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42898. __decorate([
  42899. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42900. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42901. __decorate([
  42902. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42903. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42904. __decorate([
  42905. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42906. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42907. __decorate([
  42908. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42909. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42910. __decorate([
  42911. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42912. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42913. __decorate([
  42914. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42915. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42916. __decorate([
  42917. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42918. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42919. __decorate([
  42920. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42921. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42922. __decorate([
  42923. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42924. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42925. __decorate([
  42926. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42927. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42928. __decorate([
  42929. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42930. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42931. __decorate([
  42932. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42933. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42934. __decorate([
  42935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42936. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42937. __decorate([
  42938. BABYLON.serialize("maxSimultaneousLights")
  42939. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42940. __decorate([
  42941. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42942. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42943. __decorate([
  42944. BABYLON.serialize("invertNormalMapX")
  42945. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42946. __decorate([
  42947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42948. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42949. __decorate([
  42950. BABYLON.serialize("invertNormalMapY")
  42951. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42952. __decorate([
  42953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42954. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42955. __decorate([
  42956. BABYLON.serialize("twoSidedLighting")
  42957. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42958. __decorate([
  42959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42960. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42961. __decorate([
  42962. BABYLON.serialize()
  42963. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42964. return StandardMaterial;
  42965. }(BABYLON.PushMaterial));
  42966. BABYLON.StandardMaterial = StandardMaterial;
  42967. })(BABYLON || (BABYLON = {}));
  42968. //# sourceMappingURL=babylon.standardMaterial.js.map
  42969. var BABYLON;
  42970. (function (BABYLON) {
  42971. /**
  42972. * Class representing spherical polynomial coefficients to the 3rd degree
  42973. */
  42974. var SphericalPolynomial = /** @class */ (function () {
  42975. function SphericalPolynomial() {
  42976. /**
  42977. * The x coefficients of the spherical polynomial
  42978. */
  42979. this.x = BABYLON.Vector3.Zero();
  42980. /**
  42981. * The y coefficients of the spherical polynomial
  42982. */
  42983. this.y = BABYLON.Vector3.Zero();
  42984. /**
  42985. * The z coefficients of the spherical polynomial
  42986. */
  42987. this.z = BABYLON.Vector3.Zero();
  42988. /**
  42989. * The xx coefficients of the spherical polynomial
  42990. */
  42991. this.xx = BABYLON.Vector3.Zero();
  42992. /**
  42993. * The yy coefficients of the spherical polynomial
  42994. */
  42995. this.yy = BABYLON.Vector3.Zero();
  42996. /**
  42997. * The zz coefficients of the spherical polynomial
  42998. */
  42999. this.zz = BABYLON.Vector3.Zero();
  43000. /**
  43001. * The xy coefficients of the spherical polynomial
  43002. */
  43003. this.xy = BABYLON.Vector3.Zero();
  43004. /**
  43005. * The yz coefficients of the spherical polynomial
  43006. */
  43007. this.yz = BABYLON.Vector3.Zero();
  43008. /**
  43009. * The zx coefficients of the spherical polynomial
  43010. */
  43011. this.zx = BABYLON.Vector3.Zero();
  43012. }
  43013. /**
  43014. * Adds an ambient color to the spherical polynomial
  43015. * @param color the color to add
  43016. */
  43017. SphericalPolynomial.prototype.addAmbient = function (color) {
  43018. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43019. this.xx = this.xx.add(colorVector);
  43020. this.yy = this.yy.add(colorVector);
  43021. this.zz = this.zz.add(colorVector);
  43022. };
  43023. /**
  43024. * Scales the spherical polynomial by the given amount
  43025. * @param scale the amount to scale
  43026. */
  43027. SphericalPolynomial.prototype.scale = function (scale) {
  43028. this.x = this.x.scale(scale);
  43029. this.y = this.y.scale(scale);
  43030. this.z = this.z.scale(scale);
  43031. this.xx = this.xx.scale(scale);
  43032. this.yy = this.yy.scale(scale);
  43033. this.zz = this.zz.scale(scale);
  43034. this.yz = this.yz.scale(scale);
  43035. this.zx = this.zx.scale(scale);
  43036. this.xy = this.xy.scale(scale);
  43037. };
  43038. /**
  43039. * Gets the spherical polynomial from harmonics
  43040. * @param harmonics the spherical harmonics
  43041. * @returns the spherical polynomial
  43042. */
  43043. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43044. var result = new SphericalPolynomial();
  43045. result.x = harmonics.l11.scale(1.02333);
  43046. result.y = harmonics.l1_1.scale(1.02333);
  43047. result.z = harmonics.l10.scale(1.02333);
  43048. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43049. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43050. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43051. result.yz = harmonics.l2_1.scale(0.858086);
  43052. result.zx = harmonics.l21.scale(0.858086);
  43053. result.xy = harmonics.l2_2.scale(0.858086);
  43054. result.scale(1.0 / Math.PI);
  43055. return result;
  43056. };
  43057. /**
  43058. * Constructs a spherical polynomial from an array.
  43059. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43060. * @returns the spherical polynomial
  43061. */
  43062. SphericalPolynomial.FromArray = function (data) {
  43063. var sp = new SphericalPolynomial();
  43064. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43065. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43066. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43067. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43068. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43069. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43070. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43071. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43072. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43073. return sp;
  43074. };
  43075. return SphericalPolynomial;
  43076. }());
  43077. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43078. /**
  43079. * Class representing spherical harmonics coefficients to the 3rd degree
  43080. */
  43081. var SphericalHarmonics = /** @class */ (function () {
  43082. function SphericalHarmonics() {
  43083. /**
  43084. * The l0,0 coefficients of the spherical harmonics
  43085. */
  43086. this.l00 = BABYLON.Vector3.Zero();
  43087. /**
  43088. * The l1,-1 coefficients of the spherical harmonics
  43089. */
  43090. this.l1_1 = BABYLON.Vector3.Zero();
  43091. /**
  43092. * The l1,0 coefficients of the spherical harmonics
  43093. */
  43094. this.l10 = BABYLON.Vector3.Zero();
  43095. /**
  43096. * The l1,1 coefficients of the spherical harmonics
  43097. */
  43098. this.l11 = BABYLON.Vector3.Zero();
  43099. /**
  43100. * The l2,-2 coefficients of the spherical harmonics
  43101. */
  43102. this.l2_2 = BABYLON.Vector3.Zero();
  43103. /**
  43104. * The l2,-1 coefficients of the spherical harmonics
  43105. */
  43106. this.l2_1 = BABYLON.Vector3.Zero();
  43107. /**
  43108. * The l2,0 coefficients of the spherical harmonics
  43109. */
  43110. this.l20 = BABYLON.Vector3.Zero();
  43111. /**
  43112. * The l2,1 coefficients of the spherical harmonics
  43113. */
  43114. this.l21 = BABYLON.Vector3.Zero();
  43115. /**
  43116. * The l2,2 coefficients of the spherical harmonics
  43117. */
  43118. this.lL22 = BABYLON.Vector3.Zero();
  43119. }
  43120. /**
  43121. * Adds a light to the spherical harmonics
  43122. * @param direction the direction of the light
  43123. * @param color the color of the light
  43124. * @param deltaSolidAngle the delta solid angle of the light
  43125. */
  43126. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43127. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43128. var c = colorVector.scale(deltaSolidAngle);
  43129. this.l00 = this.l00.add(c.scale(0.282095));
  43130. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43131. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43132. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43133. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43134. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43135. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43136. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43137. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43138. };
  43139. /**
  43140. * Scales the spherical harmonics by the given amount
  43141. * @param scale the amount to scale
  43142. */
  43143. SphericalHarmonics.prototype.scale = function (scale) {
  43144. this.l00 = this.l00.scale(scale);
  43145. this.l1_1 = this.l1_1.scale(scale);
  43146. this.l10 = this.l10.scale(scale);
  43147. this.l11 = this.l11.scale(scale);
  43148. this.l2_2 = this.l2_2.scale(scale);
  43149. this.l2_1 = this.l2_1.scale(scale);
  43150. this.l20 = this.l20.scale(scale);
  43151. this.l21 = this.l21.scale(scale);
  43152. this.lL22 = this.lL22.scale(scale);
  43153. };
  43154. /**
  43155. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43156. *
  43157. * ```
  43158. * E_lm = A_l * L_lm
  43159. * ```
  43160. *
  43161. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43162. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43163. * the scaling factors are given in equation 9.
  43164. */
  43165. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43166. // Constant (Band 0)
  43167. this.l00 = this.l00.scale(3.141593);
  43168. // Linear (Band 1)
  43169. this.l1_1 = this.l1_1.scale(2.094395);
  43170. this.l10 = this.l10.scale(2.094395);
  43171. this.l11 = this.l11.scale(2.094395);
  43172. // Quadratic (Band 2)
  43173. this.l2_2 = this.l2_2.scale(0.785398);
  43174. this.l2_1 = this.l2_1.scale(0.785398);
  43175. this.l20 = this.l20.scale(0.785398);
  43176. this.l21 = this.l21.scale(0.785398);
  43177. this.lL22 = this.lL22.scale(0.785398);
  43178. };
  43179. /**
  43180. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43181. *
  43182. * ```
  43183. * L = (1/pi) * E * rho
  43184. * ```
  43185. *
  43186. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43187. */
  43188. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43189. this.scale(1.0 / Math.PI);
  43190. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43191. // (The pixel shader must apply albedo after texture fetches, etc).
  43192. };
  43193. /**
  43194. * Gets the spherical harmonics from polynomial
  43195. * @param polynomial the spherical polynomial
  43196. * @returns the spherical harmonics
  43197. */
  43198. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43199. var result = new SphericalHarmonics();
  43200. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43201. result.l1_1 = polynomial.y.scale(0.977204);
  43202. result.l10 = polynomial.z.scale(0.977204);
  43203. result.l11 = polynomial.x.scale(0.977204);
  43204. result.l2_2 = polynomial.xy.scale(1.16538);
  43205. result.l2_1 = polynomial.yz.scale(1.16538);
  43206. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43207. result.l21 = polynomial.zx.scale(1.16538);
  43208. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43209. result.scale(Math.PI);
  43210. return result;
  43211. };
  43212. /**
  43213. * Constructs a spherical harmonics from an array.
  43214. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43215. * @returns the spherical harmonics
  43216. */
  43217. SphericalHarmonics.FromArray = function (data) {
  43218. var sh = new SphericalHarmonics();
  43219. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43220. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43221. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43222. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43223. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43224. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43225. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43226. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43227. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43228. return sh;
  43229. };
  43230. return SphericalHarmonics;
  43231. }());
  43232. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43233. })(BABYLON || (BABYLON = {}));
  43234. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43235. var BABYLON;
  43236. (function (BABYLON) {
  43237. var FileFaceOrientation = /** @class */ (function () {
  43238. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43239. this.name = name;
  43240. this.worldAxisForNormal = worldAxisForNormal;
  43241. this.worldAxisForFileX = worldAxisForFileX;
  43242. this.worldAxisForFileY = worldAxisForFileY;
  43243. }
  43244. return FileFaceOrientation;
  43245. }());
  43246. ;
  43247. /**
  43248. * Helper class dealing with the extraction of spherical polynomial dataArray
  43249. * from a cube map.
  43250. */
  43251. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43252. function CubeMapToSphericalPolynomialTools() {
  43253. }
  43254. /**
  43255. * Converts a texture to the according Spherical Polynomial data.
  43256. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43257. *
  43258. * @param texture The texture to extract the information from.
  43259. * @return The Spherical Polynomial data.
  43260. */
  43261. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43262. if (!texture.isCube) {
  43263. // Only supports cube Textures currently.
  43264. return null;
  43265. }
  43266. var size = texture.getSize().width;
  43267. var right = texture.readPixels(0);
  43268. var left = texture.readPixels(1);
  43269. var up;
  43270. var down;
  43271. if (texture.isRenderTarget) {
  43272. up = texture.readPixels(3);
  43273. down = texture.readPixels(2);
  43274. }
  43275. else {
  43276. up = texture.readPixels(2);
  43277. down = texture.readPixels(3);
  43278. }
  43279. var front = texture.readPixels(4);
  43280. var back = texture.readPixels(5);
  43281. var gammaSpace = texture.gammaSpace;
  43282. // Always read as RGBA.
  43283. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43284. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43285. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43286. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43287. }
  43288. var cubeInfo = {
  43289. size: size,
  43290. right: right,
  43291. left: left,
  43292. up: up,
  43293. down: down,
  43294. front: front,
  43295. back: back,
  43296. format: format,
  43297. type: type,
  43298. gammaSpace: gammaSpace,
  43299. };
  43300. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43301. };
  43302. /**
  43303. * Converts a cubemap to the according Spherical Polynomial data.
  43304. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43305. *
  43306. * @param cubeInfo The Cube map to extract the information from.
  43307. * @return The Spherical Polynomial data.
  43308. */
  43309. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43310. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43311. var totalSolidAngle = 0.0;
  43312. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43313. var du = 2.0 / cubeInfo.size;
  43314. var dv = du;
  43315. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43316. var minUV = du * 0.5 - 1.0;
  43317. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43318. var fileFace = this.FileFaces[faceIndex];
  43319. var dataArray = cubeInfo[fileFace.name];
  43320. var v = minUV;
  43321. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43322. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43323. // Because SP is still linear, so summation is fine in that basis.
  43324. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43325. for (var y = 0; y < cubeInfo.size; y++) {
  43326. var u = minUV;
  43327. for (var x = 0; x < cubeInfo.size; x++) {
  43328. // World direction (not normalised)
  43329. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43330. worldDirection.normalize();
  43331. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43332. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43333. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43334. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43335. // Handle Integer types.
  43336. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43337. r /= 255;
  43338. g /= 255;
  43339. b /= 255;
  43340. }
  43341. // Handle Gamma space textures.
  43342. if (cubeInfo.gammaSpace) {
  43343. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43344. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43345. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43346. }
  43347. var color = new BABYLON.Color3(r, g, b);
  43348. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43349. totalSolidAngle += deltaSolidAngle;
  43350. u += du;
  43351. }
  43352. v += dv;
  43353. }
  43354. }
  43355. // Solid angle for entire sphere is 4*pi
  43356. var sphereSolidAngle = 4.0 * Math.PI;
  43357. // Adjust the solid angle to allow for how many faces we processed.
  43358. var facesProcessed = 6.0;
  43359. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43360. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43361. // This is needed because the numerical integration over the cube uses a
  43362. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43363. // and also to compensate for accumulative error due to float precision in the summation.
  43364. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43365. sphericalHarmonics.scale(correctionFactor);
  43366. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43367. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43368. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43369. };
  43370. CubeMapToSphericalPolynomialTools.FileFaces = [
  43371. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43372. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43373. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43374. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43375. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43376. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43377. ];
  43378. return CubeMapToSphericalPolynomialTools;
  43379. }());
  43380. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43381. })(BABYLON || (BABYLON = {}));
  43382. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43383. var BABYLON;
  43384. (function (BABYLON) {
  43385. /**
  43386. * Manages the defines for the PBR Material.
  43387. * @hiddenChildren
  43388. */
  43389. var PBRMaterialDefines = /** @class */ (function (_super) {
  43390. __extends(PBRMaterialDefines, _super);
  43391. /**
  43392. * Initializes the PBR Material defines.
  43393. */
  43394. function PBRMaterialDefines() {
  43395. var _this = _super.call(this) || this;
  43396. _this.PBR = true;
  43397. _this.MAINUV1 = false;
  43398. _this.MAINUV2 = false;
  43399. _this.UV1 = false;
  43400. _this.UV2 = false;
  43401. _this.ALBEDO = false;
  43402. _this.ALBEDODIRECTUV = 0;
  43403. _this.VERTEXCOLOR = false;
  43404. _this.AMBIENT = false;
  43405. _this.AMBIENTDIRECTUV = 0;
  43406. _this.AMBIENTINGRAYSCALE = false;
  43407. _this.OPACITY = false;
  43408. _this.VERTEXALPHA = false;
  43409. _this.OPACITYDIRECTUV = 0;
  43410. _this.OPACITYRGB = false;
  43411. _this.ALPHATEST = false;
  43412. _this.DEPTHPREPASS = false;
  43413. _this.ALPHABLEND = false;
  43414. _this.ALPHAFROMALBEDO = false;
  43415. _this.ALPHATESTVALUE = "0.5";
  43416. _this.SPECULAROVERALPHA = false;
  43417. _this.RADIANCEOVERALPHA = false;
  43418. _this.ALPHAFRESNEL = false;
  43419. _this.LINEARALPHAFRESNEL = false;
  43420. _this.PREMULTIPLYALPHA = false;
  43421. _this.EMISSIVE = false;
  43422. _this.EMISSIVEDIRECTUV = 0;
  43423. _this.REFLECTIVITY = false;
  43424. _this.REFLECTIVITYDIRECTUV = 0;
  43425. _this.SPECULARTERM = false;
  43426. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43427. _this.MICROSURFACEAUTOMATIC = false;
  43428. _this.LODBASEDMICROSFURACE = false;
  43429. _this.MICROSURFACEMAP = false;
  43430. _this.MICROSURFACEMAPDIRECTUV = 0;
  43431. _this.METALLICWORKFLOW = false;
  43432. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43433. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43434. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43435. _this.AOSTOREINMETALMAPRED = false;
  43436. _this.ENVIRONMENTBRDF = false;
  43437. _this.NORMAL = false;
  43438. _this.TANGENT = false;
  43439. _this.BUMP = false;
  43440. _this.BUMPDIRECTUV = 0;
  43441. _this.OBJECTSPACE_NORMALMAP = false;
  43442. _this.PARALLAX = false;
  43443. _this.PARALLAXOCCLUSION = false;
  43444. _this.NORMALXYSCALE = true;
  43445. _this.LIGHTMAP = false;
  43446. _this.LIGHTMAPDIRECTUV = 0;
  43447. _this.USELIGHTMAPASSHADOWMAP = false;
  43448. _this.GAMMALIGHTMAP = false;
  43449. _this.REFLECTION = false;
  43450. _this.REFLECTIONMAP_3D = false;
  43451. _this.REFLECTIONMAP_SPHERICAL = false;
  43452. _this.REFLECTIONMAP_PLANAR = false;
  43453. _this.REFLECTIONMAP_CUBIC = false;
  43454. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43455. _this.REFLECTIONMAP_PROJECTION = false;
  43456. _this.REFLECTIONMAP_SKYBOX = false;
  43457. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43458. _this.REFLECTIONMAP_EXPLICIT = false;
  43459. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43460. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43461. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43462. _this.INVERTCUBICMAP = false;
  43463. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43464. _this.USESPHERICALINVERTEX = false;
  43465. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43466. _this.LODINREFLECTIONALPHA = false;
  43467. _this.GAMMAREFLECTION = false;
  43468. _this.RGBDREFLECTION = false;
  43469. _this.RADIANCEOCCLUSION = false;
  43470. _this.HORIZONOCCLUSION = false;
  43471. _this.REFRACTION = false;
  43472. _this.REFRACTIONMAP_3D = false;
  43473. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43474. _this.LODINREFRACTIONALPHA = false;
  43475. _this.GAMMAREFRACTION = false;
  43476. _this.RGBDREFRACTION = false;
  43477. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43478. _this.INSTANCES = false;
  43479. _this.NUM_BONE_INFLUENCERS = 0;
  43480. _this.BonesPerMesh = 0;
  43481. _this.NONUNIFORMSCALING = false;
  43482. _this.MORPHTARGETS = false;
  43483. _this.MORPHTARGETS_NORMAL = false;
  43484. _this.MORPHTARGETS_TANGENT = false;
  43485. _this.NUM_MORPH_INFLUENCERS = 0;
  43486. _this.IMAGEPROCESSING = false;
  43487. _this.VIGNETTE = false;
  43488. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43489. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43490. _this.TONEMAPPING = false;
  43491. _this.TONEMAPPING_ACES = false;
  43492. _this.CONTRAST = false;
  43493. _this.COLORCURVES = false;
  43494. _this.COLORGRADING = false;
  43495. _this.COLORGRADING3D = false;
  43496. _this.SAMPLER3DGREENDEPTH = false;
  43497. _this.SAMPLER3DBGRMAP = false;
  43498. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43499. _this.EXPOSURE = false;
  43500. _this.USEPHYSICALLIGHTFALLOFF = false;
  43501. _this.USEGLTFLIGHTFALLOFF = false;
  43502. _this.TWOSIDEDLIGHTING = false;
  43503. _this.SHADOWFLOAT = false;
  43504. _this.CLIPPLANE = false;
  43505. _this.CLIPPLANE2 = false;
  43506. _this.CLIPPLANE3 = false;
  43507. _this.CLIPPLANE4 = false;
  43508. _this.POINTSIZE = false;
  43509. _this.FOG = false;
  43510. _this.LOGARITHMICDEPTH = false;
  43511. _this.FORCENORMALFORWARD = false;
  43512. _this.SPECULARAA = false;
  43513. _this.UNLIT = false;
  43514. _this.rebuild();
  43515. return _this;
  43516. }
  43517. /**
  43518. * Resets the PBR Material defines.
  43519. */
  43520. PBRMaterialDefines.prototype.reset = function () {
  43521. _super.prototype.reset.call(this);
  43522. this.ALPHATESTVALUE = "0.5";
  43523. this.PBR = true;
  43524. };
  43525. return PBRMaterialDefines;
  43526. }(BABYLON.MaterialDefines));
  43527. /**
  43528. * The Physically based material base class of BJS.
  43529. *
  43530. * This offers the main features of a standard PBR material.
  43531. * For more information, please refer to the documentation :
  43532. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43533. */
  43534. var PBRBaseMaterial = /** @class */ (function (_super) {
  43535. __extends(PBRBaseMaterial, _super);
  43536. /**
  43537. * Instantiates a new PBRMaterial instance.
  43538. *
  43539. * @param name The material name
  43540. * @param scene The scene the material will be use in.
  43541. */
  43542. function PBRBaseMaterial(name, scene) {
  43543. var _this = _super.call(this, name, scene) || this;
  43544. /**
  43545. * Intensity of the direct lights e.g. the four lights available in your scene.
  43546. * This impacts both the direct diffuse and specular highlights.
  43547. */
  43548. _this._directIntensity = 1.0;
  43549. /**
  43550. * Intensity of the emissive part of the material.
  43551. * This helps controlling the emissive effect without modifying the emissive color.
  43552. */
  43553. _this._emissiveIntensity = 1.0;
  43554. /**
  43555. * Intensity of the environment e.g. how much the environment will light the object
  43556. * either through harmonics for rough material or through the refelction for shiny ones.
  43557. */
  43558. _this._environmentIntensity = 1.0;
  43559. /**
  43560. * This is a special control allowing the reduction of the specular highlights coming from the
  43561. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43562. */
  43563. _this._specularIntensity = 1.0;
  43564. /**
  43565. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43566. */
  43567. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43568. /**
  43569. * Debug Control allowing disabling the bump map on this material.
  43570. */
  43571. _this._disableBumpMap = false;
  43572. /**
  43573. * AKA Occlusion Texture Intensity in other nomenclature.
  43574. */
  43575. _this._ambientTextureStrength = 1.0;
  43576. /**
  43577. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43578. * 1 means it completely occludes it
  43579. * 0 mean it has no impact
  43580. */
  43581. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43582. /**
  43583. * The color of a material in ambient lighting.
  43584. */
  43585. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43586. /**
  43587. * AKA Diffuse Color in other nomenclature.
  43588. */
  43589. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43590. /**
  43591. * AKA Specular Color in other nomenclature.
  43592. */
  43593. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43594. /**
  43595. * The color applied when light is reflected from a material.
  43596. */
  43597. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43598. /**
  43599. * The color applied when light is emitted from a material.
  43600. */
  43601. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43602. /**
  43603. * AKA Glossiness in other nomenclature.
  43604. */
  43605. _this._microSurface = 0.9;
  43606. /**
  43607. * source material index of refraction (IOR)' / 'destination material IOR.
  43608. */
  43609. _this._indexOfRefraction = 0.66;
  43610. /**
  43611. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43612. */
  43613. _this._invertRefractionY = false;
  43614. /**
  43615. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43616. * Materials half opaque for instance using refraction could benefit from this control.
  43617. */
  43618. _this._linkRefractionWithTransparency = false;
  43619. /**
  43620. * Specifies that the material will use the light map as a show map.
  43621. */
  43622. _this._useLightmapAsShadowmap = false;
  43623. /**
  43624. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43625. * makes the reflect vector face the model (under horizon).
  43626. */
  43627. _this._useHorizonOcclusion = true;
  43628. /**
  43629. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43630. * too much the area relying on ambient texture to define their ambient occlusion.
  43631. */
  43632. _this._useRadianceOcclusion = true;
  43633. /**
  43634. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43635. */
  43636. _this._useAlphaFromAlbedoTexture = false;
  43637. /**
  43638. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43639. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43640. */
  43641. _this._useSpecularOverAlpha = true;
  43642. /**
  43643. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43644. */
  43645. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43646. /**
  43647. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43648. */
  43649. _this._useRoughnessFromMetallicTextureAlpha = true;
  43650. /**
  43651. * Specifies if the metallic texture contains the roughness information in its green channel.
  43652. */
  43653. _this._useRoughnessFromMetallicTextureGreen = false;
  43654. /**
  43655. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43656. */
  43657. _this._useMetallnessFromMetallicTextureBlue = false;
  43658. /**
  43659. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43660. */
  43661. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43662. /**
  43663. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43664. */
  43665. _this._useAmbientInGrayScale = false;
  43666. /**
  43667. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43668. * The material will try to infer what glossiness each pixel should be.
  43669. */
  43670. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43671. /**
  43672. * Defines the falloff type used in this material.
  43673. * It by default is Physical.
  43674. */
  43675. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43676. /**
  43677. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43678. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43679. */
  43680. _this._useRadianceOverAlpha = true;
  43681. /**
  43682. * Allows using an object space normal map (instead of tangent space).
  43683. */
  43684. _this._useObjectSpaceNormalMap = false;
  43685. /**
  43686. * Allows using the bump map in parallax mode.
  43687. */
  43688. _this._useParallax = false;
  43689. /**
  43690. * Allows using the bump map in parallax occlusion mode.
  43691. */
  43692. _this._useParallaxOcclusion = false;
  43693. /**
  43694. * Controls the scale bias of the parallax mode.
  43695. */
  43696. _this._parallaxScaleBias = 0.05;
  43697. /**
  43698. * If sets to true, disables all the lights affecting the material.
  43699. */
  43700. _this._disableLighting = false;
  43701. /**
  43702. * Number of Simultaneous lights allowed on the material.
  43703. */
  43704. _this._maxSimultaneousLights = 4;
  43705. /**
  43706. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43707. */
  43708. _this._invertNormalMapX = false;
  43709. /**
  43710. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43711. */
  43712. _this._invertNormalMapY = false;
  43713. /**
  43714. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43715. */
  43716. _this._twoSidedLighting = false;
  43717. /**
  43718. * Defines the alpha limits in alpha test mode.
  43719. */
  43720. _this._alphaCutOff = 0.4;
  43721. /**
  43722. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43723. */
  43724. _this._forceAlphaTest = false;
  43725. /**
  43726. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43727. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43728. */
  43729. _this._useAlphaFresnel = false;
  43730. /**
  43731. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43732. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43733. */
  43734. _this._useLinearAlphaFresnel = false;
  43735. /**
  43736. * The transparency mode of the material.
  43737. */
  43738. _this._transparencyMode = null;
  43739. /**
  43740. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43741. * from cos thetav and roughness:
  43742. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43743. */
  43744. _this._environmentBRDFTexture = null;
  43745. /**
  43746. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43747. */
  43748. _this._forceIrradianceInFragment = false;
  43749. /**
  43750. * Force normal to face away from face.
  43751. */
  43752. _this._forceNormalForward = false;
  43753. /**
  43754. * Enables specular anti aliasing in the PBR shader.
  43755. * It will both interacts on the Geometry for analytical and IBL lighting.
  43756. * It also prefilter the roughness map based on the bump values.
  43757. */
  43758. _this._enableSpecularAntiAliasing = false;
  43759. /**
  43760. * Stores the available render targets.
  43761. */
  43762. _this._renderTargets = new BABYLON.SmartArray(16);
  43763. /**
  43764. * Sets the global ambient color for the material used in lighting calculations.
  43765. */
  43766. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43767. /**
  43768. * If set to true, no lighting calculations will be applied.
  43769. */
  43770. _this._unlit = false;
  43771. // Setup the default processing configuration to the scene.
  43772. _this._attachImageProcessingConfiguration(null);
  43773. _this.getRenderTargetTextures = function () {
  43774. _this._renderTargets.reset();
  43775. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43776. _this._renderTargets.push(_this._reflectionTexture);
  43777. }
  43778. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43779. _this._renderTargets.push(_this._refractionTexture);
  43780. }
  43781. return _this._renderTargets;
  43782. };
  43783. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43784. return _this;
  43785. }
  43786. /**
  43787. * Attaches a new image processing configuration to the PBR Material.
  43788. * @param configuration
  43789. */
  43790. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43791. var _this = this;
  43792. if (configuration === this._imageProcessingConfiguration) {
  43793. return;
  43794. }
  43795. // Detaches observer.
  43796. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43797. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43798. }
  43799. // Pick the scene configuration if needed.
  43800. if (!configuration) {
  43801. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43802. }
  43803. else {
  43804. this._imageProcessingConfiguration = configuration;
  43805. }
  43806. // Attaches observer.
  43807. if (this._imageProcessingConfiguration) {
  43808. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43809. _this._markAllSubMeshesAsImageProcessingDirty();
  43810. });
  43811. }
  43812. };
  43813. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43814. /**
  43815. * Gets a boolean indicating that current material needs to register RTT
  43816. */
  43817. get: function () {
  43818. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43819. return true;
  43820. }
  43821. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43822. return true;
  43823. }
  43824. return false;
  43825. },
  43826. enumerable: true,
  43827. configurable: true
  43828. });
  43829. /**
  43830. * Gets the name of the material class.
  43831. */
  43832. PBRBaseMaterial.prototype.getClassName = function () {
  43833. return "PBRBaseMaterial";
  43834. };
  43835. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43836. /**
  43837. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43838. */
  43839. get: function () {
  43840. return this._useLogarithmicDepth;
  43841. },
  43842. /**
  43843. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43844. */
  43845. set: function (value) {
  43846. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43847. },
  43848. enumerable: true,
  43849. configurable: true
  43850. });
  43851. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43852. /**
  43853. * Gets the current transparency mode.
  43854. */
  43855. get: function () {
  43856. return this._transparencyMode;
  43857. },
  43858. /**
  43859. * Sets the transparency mode of the material.
  43860. *
  43861. * | Value | Type | Description |
  43862. * | ----- | ----------------------------------- | ----------- |
  43863. * | 0 | OPAQUE | |
  43864. * | 1 | ALPHATEST | |
  43865. * | 2 | ALPHABLEND | |
  43866. * | 3 | ALPHATESTANDBLEND | |
  43867. *
  43868. */
  43869. set: function (value) {
  43870. if (this._transparencyMode === value) {
  43871. return;
  43872. }
  43873. this._transparencyMode = value;
  43874. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43875. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43881. /**
  43882. * Returns true if alpha blending should be disabled.
  43883. */
  43884. get: function () {
  43885. return (this._linkRefractionWithTransparency ||
  43886. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43887. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. /**
  43893. * Specifies whether or not this material should be rendered in alpha blend mode.
  43894. */
  43895. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43896. if (this._disableAlphaBlending) {
  43897. return false;
  43898. }
  43899. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43900. };
  43901. /**
  43902. * Specifies if the mesh will require alpha blending.
  43903. * @param mesh - BJS mesh.
  43904. */
  43905. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43906. if (this._disableAlphaBlending) {
  43907. return false;
  43908. }
  43909. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43910. };
  43911. /**
  43912. * Specifies whether or not this material should be rendered in alpha test mode.
  43913. */
  43914. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43915. if (this._forceAlphaTest) {
  43916. return true;
  43917. }
  43918. if (this._linkRefractionWithTransparency) {
  43919. return false;
  43920. }
  43921. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43922. };
  43923. /**
  43924. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43925. */
  43926. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43927. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43928. };
  43929. /**
  43930. * Gets the texture used for the alpha test.
  43931. */
  43932. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43933. return this._albedoTexture;
  43934. };
  43935. /**
  43936. * Specifies that the submesh is ready to be used.
  43937. * @param mesh - BJS mesh.
  43938. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43939. * @param useInstances - Specifies that instances should be used.
  43940. * @returns - boolean indicating that the submesh is ready or not.
  43941. */
  43942. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43943. if (subMesh.effect && this.isFrozen) {
  43944. if (this._wasPreviouslyReady) {
  43945. return true;
  43946. }
  43947. }
  43948. if (!subMesh._materialDefines) {
  43949. subMesh._materialDefines = new PBRMaterialDefines();
  43950. }
  43951. var defines = subMesh._materialDefines;
  43952. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43953. if (defines._renderId === this.getScene().getRenderId()) {
  43954. return true;
  43955. }
  43956. }
  43957. var scene = this.getScene();
  43958. var engine = scene.getEngine();
  43959. if (defines._areTexturesDirty) {
  43960. if (scene.texturesEnabled) {
  43961. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43962. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43963. return false;
  43964. }
  43965. }
  43966. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43967. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43968. return false;
  43969. }
  43970. }
  43971. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43972. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43973. return false;
  43974. }
  43975. }
  43976. var reflectionTexture = this._getReflectionTexture();
  43977. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43978. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43979. return false;
  43980. }
  43981. }
  43982. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43983. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43984. return false;
  43985. }
  43986. }
  43987. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43988. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43989. return false;
  43990. }
  43991. }
  43992. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43993. if (this._metallicTexture) {
  43994. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43995. return false;
  43996. }
  43997. }
  43998. else if (this._reflectivityTexture) {
  43999. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44000. return false;
  44001. }
  44002. }
  44003. if (this._microSurfaceTexture) {
  44004. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44005. return false;
  44006. }
  44007. }
  44008. }
  44009. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44010. // Bump texture cannot be not blocking.
  44011. if (!this._bumpTexture.isReady()) {
  44012. return false;
  44013. }
  44014. }
  44015. var refractionTexture = this._getRefractionTexture();
  44016. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44017. if (!refractionTexture.isReadyOrNotBlocking()) {
  44018. return false;
  44019. }
  44020. }
  44021. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44022. // This is blocking.
  44023. if (!this._environmentBRDFTexture.isReady()) {
  44024. return false;
  44025. }
  44026. }
  44027. }
  44028. }
  44029. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44030. if (!this._imageProcessingConfiguration.isReady()) {
  44031. return false;
  44032. }
  44033. }
  44034. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44035. mesh.createNormals(true);
  44036. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44037. }
  44038. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44039. if (effect) {
  44040. scene.resetCachedMaterial();
  44041. subMesh.setEffect(effect, defines);
  44042. this.buildUniformLayout();
  44043. }
  44044. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44045. return false;
  44046. }
  44047. defines._renderId = scene.getRenderId();
  44048. this._wasPreviouslyReady = true;
  44049. return true;
  44050. };
  44051. /**
  44052. * Specifies if the material uses metallic roughness workflow.
  44053. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44054. */
  44055. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44056. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44057. return true;
  44058. }
  44059. return false;
  44060. };
  44061. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44062. if (onCompiled === void 0) { onCompiled = null; }
  44063. if (onError === void 0) { onError = null; }
  44064. if (useInstances === void 0) { useInstances = null; }
  44065. if (useClipPlane === void 0) { useClipPlane = null; }
  44066. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44067. if (!defines.isDirty) {
  44068. return null;
  44069. }
  44070. defines.markAsProcessed();
  44071. var scene = this.getScene();
  44072. var engine = scene.getEngine();
  44073. // Fallbacks
  44074. var fallbacks = new BABYLON.EffectFallbacks();
  44075. var fallbackRank = 0;
  44076. if (defines.USESPHERICALINVERTEX) {
  44077. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44078. }
  44079. if (defines.FOG) {
  44080. fallbacks.addFallback(fallbackRank, "FOG");
  44081. }
  44082. if (defines.SPECULARAA) {
  44083. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44084. }
  44085. if (defines.POINTSIZE) {
  44086. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44087. }
  44088. if (defines.LOGARITHMICDEPTH) {
  44089. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44090. }
  44091. if (defines.PARALLAX) {
  44092. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44093. }
  44094. if (defines.PARALLAXOCCLUSION) {
  44095. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44096. }
  44097. if (defines.ENVIRONMENTBRDF) {
  44098. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44099. }
  44100. if (defines.TANGENT) {
  44101. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44102. }
  44103. if (defines.BUMP) {
  44104. fallbacks.addFallback(fallbackRank++, "BUMP");
  44105. }
  44106. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44107. if (defines.SPECULARTERM) {
  44108. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44109. }
  44110. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44111. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44112. }
  44113. if (defines.LIGHTMAP) {
  44114. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44115. }
  44116. if (defines.NORMAL) {
  44117. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44118. }
  44119. if (defines.AMBIENT) {
  44120. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44121. }
  44122. if (defines.EMISSIVE) {
  44123. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44124. }
  44125. if (defines.VERTEXCOLOR) {
  44126. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44127. }
  44128. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44129. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44130. }
  44131. if (defines.MORPHTARGETS) {
  44132. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44133. }
  44134. //Attributes
  44135. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44136. if (defines.NORMAL) {
  44137. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44138. }
  44139. if (defines.TANGENT) {
  44140. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44141. }
  44142. if (defines.UV1) {
  44143. attribs.push(BABYLON.VertexBuffer.UVKind);
  44144. }
  44145. if (defines.UV2) {
  44146. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44147. }
  44148. if (defines.VERTEXCOLOR) {
  44149. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44150. }
  44151. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44152. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44153. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44154. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44155. "vFogInfos", "vFogColor", "pointSize",
  44156. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44157. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44158. "mBones",
  44159. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44160. "vLightingIntensity",
  44161. "logarithmicDepthConstant",
  44162. "vSphericalX", "vSphericalY", "vSphericalZ",
  44163. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44164. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44165. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44166. "vTangentSpaceParams"
  44167. ];
  44168. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44169. "bumpSampler", "lightmapSampler", "opacitySampler",
  44170. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44171. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44172. "microSurfaceSampler", "environmentBrdfSampler"];
  44173. var uniformBuffers = ["Material", "Scene"];
  44174. if (BABYLON.ImageProcessingConfiguration) {
  44175. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44176. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44177. }
  44178. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44179. uniformsNames: uniforms,
  44180. uniformBuffersNames: uniformBuffers,
  44181. samplers: samplers,
  44182. defines: defines,
  44183. maxSimultaneousLights: this._maxSimultaneousLights
  44184. });
  44185. var join = defines.toString();
  44186. return engine.createEffect("pbr", {
  44187. attributes: attribs,
  44188. uniformsNames: uniforms,
  44189. uniformBuffersNames: uniformBuffers,
  44190. samplers: samplers,
  44191. defines: join,
  44192. fallbacks: fallbacks,
  44193. onCompiled: onCompiled,
  44194. onError: onError,
  44195. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44196. }, engine);
  44197. };
  44198. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44199. if (useInstances === void 0) { useInstances = null; }
  44200. if (useClipPlane === void 0) { useClipPlane = null; }
  44201. var scene = this.getScene();
  44202. var engine = scene.getEngine();
  44203. // Lights
  44204. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44205. defines._needNormals = true;
  44206. // Textures
  44207. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44208. if (defines._areTexturesDirty) {
  44209. defines._needUVs = false;
  44210. if (scene.texturesEnabled) {
  44211. if (scene.getEngine().getCaps().textureLOD) {
  44212. defines.LODBASEDMICROSFURACE = true;
  44213. }
  44214. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44216. }
  44217. else {
  44218. defines.ALBEDO = false;
  44219. }
  44220. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44222. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44223. }
  44224. else {
  44225. defines.AMBIENT = false;
  44226. }
  44227. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44228. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44229. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44230. }
  44231. else {
  44232. defines.OPACITY = false;
  44233. }
  44234. var reflectionTexture = this._getReflectionTexture();
  44235. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44236. defines.REFLECTION = true;
  44237. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44238. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44239. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44240. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44241. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44242. defines.INVERTCUBICMAP = true;
  44243. }
  44244. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44245. switch (reflectionTexture.coordinatesMode) {
  44246. case BABYLON.Texture.EXPLICIT_MODE:
  44247. defines.REFLECTIONMAP_EXPLICIT = true;
  44248. break;
  44249. case BABYLON.Texture.PLANAR_MODE:
  44250. defines.REFLECTIONMAP_PLANAR = true;
  44251. break;
  44252. case BABYLON.Texture.PROJECTION_MODE:
  44253. defines.REFLECTIONMAP_PROJECTION = true;
  44254. break;
  44255. case BABYLON.Texture.SKYBOX_MODE:
  44256. defines.REFLECTIONMAP_SKYBOX = true;
  44257. break;
  44258. case BABYLON.Texture.SPHERICAL_MODE:
  44259. defines.REFLECTIONMAP_SPHERICAL = true;
  44260. break;
  44261. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44262. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44263. break;
  44264. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44265. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44266. break;
  44267. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44268. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44269. break;
  44270. case BABYLON.Texture.CUBIC_MODE:
  44271. case BABYLON.Texture.INVCUBIC_MODE:
  44272. default:
  44273. defines.REFLECTIONMAP_CUBIC = true;
  44274. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44275. break;
  44276. }
  44277. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44278. if (reflectionTexture.sphericalPolynomial) {
  44279. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44280. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44281. defines.USESPHERICALINVERTEX = false;
  44282. }
  44283. else {
  44284. defines.USESPHERICALINVERTEX = true;
  44285. }
  44286. }
  44287. }
  44288. else {
  44289. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44290. }
  44291. }
  44292. else {
  44293. defines.REFLECTION = false;
  44294. defines.REFLECTIONMAP_3D = false;
  44295. defines.REFLECTIONMAP_SPHERICAL = false;
  44296. defines.REFLECTIONMAP_PLANAR = false;
  44297. defines.REFLECTIONMAP_CUBIC = false;
  44298. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44299. defines.REFLECTIONMAP_PROJECTION = false;
  44300. defines.REFLECTIONMAP_SKYBOX = false;
  44301. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44302. defines.REFLECTIONMAP_EXPLICIT = false;
  44303. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44304. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44305. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44306. defines.INVERTCUBICMAP = false;
  44307. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44308. defines.USESPHERICALINVERTEX = false;
  44309. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44310. defines.LODINREFLECTIONALPHA = false;
  44311. defines.GAMMAREFLECTION = false;
  44312. defines.RGBDREFLECTION = false;
  44313. }
  44314. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44316. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44317. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44318. }
  44319. else {
  44320. defines.LIGHTMAP = false;
  44321. }
  44322. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44323. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44324. }
  44325. else {
  44326. defines.EMISSIVE = false;
  44327. }
  44328. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44329. if (this._metallicTexture) {
  44330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44331. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44332. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44333. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44334. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44335. }
  44336. else if (this._reflectivityTexture) {
  44337. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44338. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44339. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44340. }
  44341. else {
  44342. defines.REFLECTIVITY = false;
  44343. }
  44344. if (this._microSurfaceTexture) {
  44345. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44346. }
  44347. else {
  44348. defines.MICROSURFACEMAP = false;
  44349. }
  44350. }
  44351. else {
  44352. defines.REFLECTIVITY = false;
  44353. defines.MICROSURFACEMAP = false;
  44354. }
  44355. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44356. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44357. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44358. defines.PARALLAX = true;
  44359. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44360. }
  44361. else {
  44362. defines.PARALLAX = false;
  44363. }
  44364. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44365. }
  44366. else {
  44367. defines.BUMP = false;
  44368. }
  44369. var refractionTexture = this._getRefractionTexture();
  44370. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44371. defines.REFRACTION = true;
  44372. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44373. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44374. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44375. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44376. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44377. if (this._linkRefractionWithTransparency) {
  44378. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44379. }
  44380. }
  44381. else {
  44382. defines.REFRACTION = false;
  44383. }
  44384. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44385. defines.ENVIRONMENTBRDF = true;
  44386. }
  44387. else {
  44388. defines.ENVIRONMENTBRDF = false;
  44389. }
  44390. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44391. defines.ALPHAFROMALBEDO = true;
  44392. }
  44393. else {
  44394. defines.ALPHAFROMALBEDO = false;
  44395. }
  44396. }
  44397. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44398. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44399. defines.USEPHYSICALLIGHTFALLOFF = false;
  44400. defines.USEGLTFLIGHTFALLOFF = false;
  44401. }
  44402. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44403. defines.USEPHYSICALLIGHTFALLOFF = false;
  44404. defines.USEGLTFLIGHTFALLOFF = true;
  44405. }
  44406. else {
  44407. defines.USEPHYSICALLIGHTFALLOFF = true;
  44408. defines.USEGLTFLIGHTFALLOFF = false;
  44409. }
  44410. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44411. if (!this.backFaceCulling && this._twoSidedLighting) {
  44412. defines.TWOSIDEDLIGHTING = true;
  44413. }
  44414. else {
  44415. defines.TWOSIDEDLIGHTING = false;
  44416. }
  44417. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44418. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44419. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44420. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44421. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44422. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44423. }
  44424. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44425. this._imageProcessingConfiguration.prepareDefines(defines);
  44426. }
  44427. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44428. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44429. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44430. // Misc.
  44431. if (defines._areMiscDirty) {
  44432. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44433. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44434. }
  44435. // Values that need to be evaluated on every frame
  44436. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44437. // Attribs
  44438. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44439. };
  44440. /**
  44441. * Force shader compilation
  44442. */
  44443. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44444. var _this = this;
  44445. var localOptions = __assign({ clipPlane: false }, options);
  44446. var defines = new PBRMaterialDefines();
  44447. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44448. if (effect.isReady()) {
  44449. if (onCompiled) {
  44450. onCompiled(this);
  44451. }
  44452. }
  44453. else {
  44454. effect.onCompileObservable.add(function () {
  44455. if (onCompiled) {
  44456. onCompiled(_this);
  44457. }
  44458. });
  44459. }
  44460. };
  44461. /**
  44462. * Initializes the uniform buffer layout for the shader.
  44463. */
  44464. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44465. // Order is important !
  44466. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44467. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44468. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44469. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44470. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44471. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44472. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44473. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44474. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44475. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44476. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44477. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44478. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44479. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44480. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44481. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44482. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44483. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44484. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44485. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44486. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44487. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44488. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44489. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44490. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44491. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44492. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44493. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44494. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44495. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44496. this._uniformBuffer.addUniform("pointSize", 1);
  44497. this._uniformBuffer.create();
  44498. };
  44499. /**
  44500. * Unbinds the textures.
  44501. */
  44502. PBRBaseMaterial.prototype.unbind = function () {
  44503. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44504. this._uniformBuffer.setTexture("reflectionSampler", null);
  44505. }
  44506. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44507. this._uniformBuffer.setTexture("refractionSampler", null);
  44508. }
  44509. _super.prototype.unbind.call(this);
  44510. };
  44511. /**
  44512. * Binds the submesh data.
  44513. * @param world - The world matrix.
  44514. * @param mesh - The BJS mesh.
  44515. * @param subMesh - A submesh of the BJS mesh.
  44516. */
  44517. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44518. var scene = this.getScene();
  44519. var defines = subMesh._materialDefines;
  44520. if (!defines) {
  44521. return;
  44522. }
  44523. var effect = subMesh.effect;
  44524. if (!effect) {
  44525. return;
  44526. }
  44527. this._activeEffect = effect;
  44528. // Matrices
  44529. this.bindOnlyWorldMatrix(world);
  44530. // Normal Matrix
  44531. if (defines.OBJECTSPACE_NORMALMAP) {
  44532. world.toNormalMatrix(this._normalMatrix);
  44533. this.bindOnlyNormalMatrix(this._normalMatrix);
  44534. }
  44535. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44536. // Bones
  44537. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44538. var reflectionTexture = null;
  44539. if (mustRebind) {
  44540. this._uniformBuffer.bindToEffect(effect, "Material");
  44541. this.bindViewProjection(effect);
  44542. reflectionTexture = this._getReflectionTexture();
  44543. var refractionTexture = this._getRefractionTexture();
  44544. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44545. // Texture uniforms
  44546. if (scene.texturesEnabled) {
  44547. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44548. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44549. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44550. }
  44551. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44552. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44553. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44554. }
  44555. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44556. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44557. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44558. }
  44559. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44560. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44561. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44562. if (reflectionTexture.boundingBoxSize) {
  44563. var cubeTexture = reflectionTexture;
  44564. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44565. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44566. }
  44567. var polynomials = reflectionTexture.sphericalPolynomial;
  44568. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44569. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44570. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44571. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44572. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44573. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44574. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44575. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44576. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44577. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44578. }
  44579. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44580. }
  44581. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44582. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44583. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44584. }
  44585. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44586. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44587. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44588. }
  44589. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44590. if (this._metallicTexture) {
  44591. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44592. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44593. }
  44594. else if (this._reflectivityTexture) {
  44595. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44596. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44597. }
  44598. if (this._microSurfaceTexture) {
  44599. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44600. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44601. }
  44602. }
  44603. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44604. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44605. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44606. if (scene._mirroredCameraPosition) {
  44607. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44608. }
  44609. else {
  44610. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44611. }
  44612. }
  44613. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44614. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44615. var depth = 1.0;
  44616. if (!refractionTexture.isCube) {
  44617. if (refractionTexture.depth) {
  44618. depth = refractionTexture.depth;
  44619. }
  44620. }
  44621. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44622. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44623. }
  44624. }
  44625. // Point size
  44626. if (this.pointsCloud) {
  44627. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44628. }
  44629. // Colors
  44630. if (defines.METALLICWORKFLOW) {
  44631. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44632. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44633. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44634. }
  44635. else {
  44636. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44637. }
  44638. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44639. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44640. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44641. // Misc
  44642. this._lightingInfos.x = this._directIntensity;
  44643. this._lightingInfos.y = this._emissiveIntensity;
  44644. this._lightingInfos.z = this._environmentIntensity;
  44645. this._lightingInfos.w = this._specularIntensity;
  44646. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44647. }
  44648. // Textures
  44649. if (scene.texturesEnabled) {
  44650. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44651. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44652. }
  44653. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44654. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44655. }
  44656. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44657. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44658. }
  44659. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44660. if (defines.LODBASEDMICROSFURACE) {
  44661. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44662. }
  44663. else {
  44664. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44665. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44666. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44667. }
  44668. }
  44669. if (defines.ENVIRONMENTBRDF) {
  44670. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44671. }
  44672. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44673. if (defines.LODBASEDMICROSFURACE) {
  44674. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44675. }
  44676. else {
  44677. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44678. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44679. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44680. }
  44681. }
  44682. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44683. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44684. }
  44685. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44686. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44687. }
  44688. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44689. if (this._metallicTexture) {
  44690. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44691. }
  44692. else if (this._reflectivityTexture) {
  44693. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44694. }
  44695. if (this._microSurfaceTexture) {
  44696. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44697. }
  44698. }
  44699. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44700. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44701. }
  44702. }
  44703. // Clip plane
  44704. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44705. // Colors
  44706. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44707. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44708. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44709. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44710. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44711. }
  44712. if (mustRebind || !this.isFrozen) {
  44713. // Lights
  44714. if (scene.lightsEnabled && !this._disableLighting) {
  44715. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44716. }
  44717. // View
  44718. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44719. this.bindView(effect);
  44720. }
  44721. // Fog
  44722. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44723. // Morph targets
  44724. if (defines.NUM_MORPH_INFLUENCERS) {
  44725. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44726. }
  44727. // image processing
  44728. this._imageProcessingConfiguration.bind(this._activeEffect);
  44729. // Log. depth
  44730. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44731. }
  44732. this._uniformBuffer.update();
  44733. this._afterBind(mesh, this._activeEffect);
  44734. };
  44735. /**
  44736. * Returns the animatable textures.
  44737. * @returns - Array of animatable textures.
  44738. */
  44739. PBRBaseMaterial.prototype.getAnimatables = function () {
  44740. var results = [];
  44741. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44742. results.push(this._albedoTexture);
  44743. }
  44744. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44745. results.push(this._ambientTexture);
  44746. }
  44747. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44748. results.push(this._opacityTexture);
  44749. }
  44750. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44751. results.push(this._reflectionTexture);
  44752. }
  44753. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44754. results.push(this._emissiveTexture);
  44755. }
  44756. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44757. results.push(this._metallicTexture);
  44758. }
  44759. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44760. results.push(this._reflectivityTexture);
  44761. }
  44762. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44763. results.push(this._bumpTexture);
  44764. }
  44765. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44766. results.push(this._lightmapTexture);
  44767. }
  44768. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44769. results.push(this._refractionTexture);
  44770. }
  44771. return results;
  44772. };
  44773. /**
  44774. * Returns the texture used for reflections.
  44775. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44776. */
  44777. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44778. if (this._reflectionTexture) {
  44779. return this._reflectionTexture;
  44780. }
  44781. return this.getScene().environmentTexture;
  44782. };
  44783. /**
  44784. * Returns the texture used for refraction or null if none is used.
  44785. * @returns - Refection texture if present. If no refraction texture and refraction
  44786. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44787. */
  44788. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44789. if (this._refractionTexture) {
  44790. return this._refractionTexture;
  44791. }
  44792. if (this._linkRefractionWithTransparency) {
  44793. return this.getScene().environmentTexture;
  44794. }
  44795. return null;
  44796. };
  44797. /**
  44798. * Disposes the resources of the material.
  44799. * @param forceDisposeEffect - Forces the disposal of effects.
  44800. * @param forceDisposeTextures - Forces the disposal of all textures.
  44801. */
  44802. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44803. if (forceDisposeTextures) {
  44804. if (this._albedoTexture) {
  44805. this._albedoTexture.dispose();
  44806. }
  44807. if (this._ambientTexture) {
  44808. this._ambientTexture.dispose();
  44809. }
  44810. if (this._opacityTexture) {
  44811. this._opacityTexture.dispose();
  44812. }
  44813. if (this._reflectionTexture) {
  44814. this._reflectionTexture.dispose();
  44815. }
  44816. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44817. this._environmentBRDFTexture.dispose();
  44818. }
  44819. if (this._emissiveTexture) {
  44820. this._emissiveTexture.dispose();
  44821. }
  44822. if (this._metallicTexture) {
  44823. this._metallicTexture.dispose();
  44824. }
  44825. if (this._reflectivityTexture) {
  44826. this._reflectivityTexture.dispose();
  44827. }
  44828. if (this._bumpTexture) {
  44829. this._bumpTexture.dispose();
  44830. }
  44831. if (this._lightmapTexture) {
  44832. this._lightmapTexture.dispose();
  44833. }
  44834. if (this._refractionTexture) {
  44835. this._refractionTexture.dispose();
  44836. }
  44837. }
  44838. this._renderTargets.dispose();
  44839. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44840. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44841. }
  44842. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44843. };
  44844. /**
  44845. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44846. */
  44847. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44848. /**
  44849. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44850. * to enhance interoperability with other engines.
  44851. */
  44852. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44853. /**
  44854. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44855. * to enhance interoperability with other materials.
  44856. */
  44857. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44858. /**
  44859. * Stores the reflectivity values based on metallic roughness workflow.
  44860. */
  44861. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44862. __decorate([
  44863. BABYLON.serializeAsImageProcessingConfiguration()
  44864. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44865. __decorate([
  44866. BABYLON.serialize()
  44867. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44868. __decorate([
  44869. BABYLON.serialize()
  44870. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44871. return PBRBaseMaterial;
  44872. }(BABYLON.PushMaterial));
  44873. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44874. })(BABYLON || (BABYLON = {}));
  44875. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44876. var BABYLON;
  44877. (function (BABYLON) {
  44878. /**
  44879. * The Physically based simple base material of BJS.
  44880. *
  44881. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44882. * It is used as the base class for both the specGloss and metalRough conventions.
  44883. */
  44884. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44885. __extends(PBRBaseSimpleMaterial, _super);
  44886. /**
  44887. * Instantiates a new PBRMaterial instance.
  44888. *
  44889. * @param name The material name
  44890. * @param scene The scene the material will be use in.
  44891. */
  44892. function PBRBaseSimpleMaterial(name, scene) {
  44893. var _this = _super.call(this, name, scene) || this;
  44894. /**
  44895. * Number of Simultaneous lights allowed on the material.
  44896. */
  44897. _this.maxSimultaneousLights = 4;
  44898. /**
  44899. * If sets to true, disables all the lights affecting the material.
  44900. */
  44901. _this.disableLighting = false;
  44902. /**
  44903. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44904. */
  44905. _this.invertNormalMapX = false;
  44906. /**
  44907. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44908. */
  44909. _this.invertNormalMapY = false;
  44910. /**
  44911. * Emissivie color used to self-illuminate the model.
  44912. */
  44913. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44914. /**
  44915. * Occlusion Channel Strenght.
  44916. */
  44917. _this.occlusionStrength = 1.0;
  44918. _this.useLightmapAsShadowmap = false;
  44919. _this._useAlphaFromAlbedoTexture = true;
  44920. _this._useAmbientInGrayScale = true;
  44921. return _this;
  44922. }
  44923. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44924. /**
  44925. * Gets the current double sided mode.
  44926. */
  44927. get: function () {
  44928. return this._twoSidedLighting;
  44929. },
  44930. /**
  44931. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44932. */
  44933. set: function (value) {
  44934. if (this._twoSidedLighting === value) {
  44935. return;
  44936. }
  44937. this._twoSidedLighting = value;
  44938. this.backFaceCulling = !value;
  44939. this._markAllSubMeshesAsTexturesDirty();
  44940. },
  44941. enumerable: true,
  44942. configurable: true
  44943. });
  44944. /**
  44945. * Return the active textures of the material.
  44946. */
  44947. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44948. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44949. if (this.environmentTexture) {
  44950. activeTextures.push(this.environmentTexture);
  44951. }
  44952. if (this.normalTexture) {
  44953. activeTextures.push(this.normalTexture);
  44954. }
  44955. if (this.emissiveTexture) {
  44956. activeTextures.push(this.emissiveTexture);
  44957. }
  44958. if (this.occlusionTexture) {
  44959. activeTextures.push(this.occlusionTexture);
  44960. }
  44961. if (this.lightmapTexture) {
  44962. activeTextures.push(this.lightmapTexture);
  44963. }
  44964. return activeTextures;
  44965. };
  44966. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44967. if (_super.prototype.hasTexture.call(this, texture)) {
  44968. return true;
  44969. }
  44970. if (this.lightmapTexture === texture) {
  44971. return true;
  44972. }
  44973. return false;
  44974. };
  44975. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44976. return "PBRBaseSimpleMaterial";
  44977. };
  44978. __decorate([
  44979. BABYLON.serialize(),
  44980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44981. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44982. __decorate([
  44983. BABYLON.serialize(),
  44984. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44985. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44986. __decorate([
  44987. BABYLON.serializeAsTexture(),
  44988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44989. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44990. __decorate([
  44991. BABYLON.serialize(),
  44992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44993. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44994. __decorate([
  44995. BABYLON.serialize(),
  44996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44997. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44998. __decorate([
  44999. BABYLON.serializeAsTexture(),
  45000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45001. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45002. __decorate([
  45003. BABYLON.serializeAsColor3("emissive"),
  45004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45005. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45006. __decorate([
  45007. BABYLON.serializeAsTexture(),
  45008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45009. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45010. __decorate([
  45011. BABYLON.serialize(),
  45012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45013. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45014. __decorate([
  45015. BABYLON.serializeAsTexture(),
  45016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45017. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45018. __decorate([
  45019. BABYLON.serialize(),
  45020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45021. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45022. __decorate([
  45023. BABYLON.serialize()
  45024. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45025. __decorate([
  45026. BABYLON.serializeAsTexture(),
  45027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45028. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45029. __decorate([
  45030. BABYLON.serialize(),
  45031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45032. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45033. return PBRBaseSimpleMaterial;
  45034. }(BABYLON.PBRBaseMaterial));
  45035. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45036. })(BABYLON || (BABYLON = {}));
  45037. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45038. var BABYLON;
  45039. (function (BABYLON) {
  45040. /**
  45041. * The Physically based material of BJS.
  45042. *
  45043. * This offers the main features of a standard PBR material.
  45044. * For more information, please refer to the documentation :
  45045. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45046. */
  45047. var PBRMaterial = /** @class */ (function (_super) {
  45048. __extends(PBRMaterial, _super);
  45049. /**
  45050. * Instantiates a new PBRMaterial instance.
  45051. *
  45052. * @param name The material name
  45053. * @param scene The scene the material will be use in.
  45054. */
  45055. function PBRMaterial(name, scene) {
  45056. var _this = _super.call(this, name, scene) || this;
  45057. /**
  45058. * Intensity of the direct lights e.g. the four lights available in your scene.
  45059. * This impacts both the direct diffuse and specular highlights.
  45060. */
  45061. _this.directIntensity = 1.0;
  45062. /**
  45063. * Intensity of the emissive part of the material.
  45064. * This helps controlling the emissive effect without modifying the emissive color.
  45065. */
  45066. _this.emissiveIntensity = 1.0;
  45067. /**
  45068. * Intensity of the environment e.g. how much the environment will light the object
  45069. * either through harmonics for rough material or through the refelction for shiny ones.
  45070. */
  45071. _this.environmentIntensity = 1.0;
  45072. /**
  45073. * This is a special control allowing the reduction of the specular highlights coming from the
  45074. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45075. */
  45076. _this.specularIntensity = 1.0;
  45077. /**
  45078. * Debug Control allowing disabling the bump map on this material.
  45079. */
  45080. _this.disableBumpMap = false;
  45081. /**
  45082. * AKA Occlusion Texture Intensity in other nomenclature.
  45083. */
  45084. _this.ambientTextureStrength = 1.0;
  45085. /**
  45086. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45087. * 1 means it completely occludes it
  45088. * 0 mean it has no impact
  45089. */
  45090. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45091. /**
  45092. * The color of a material in ambient lighting.
  45093. */
  45094. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45095. /**
  45096. * AKA Diffuse Color in other nomenclature.
  45097. */
  45098. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45099. /**
  45100. * AKA Specular Color in other nomenclature.
  45101. */
  45102. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45103. /**
  45104. * The color reflected from the material.
  45105. */
  45106. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45107. /**
  45108. * The color emitted from the material.
  45109. */
  45110. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45111. /**
  45112. * AKA Glossiness in other nomenclature.
  45113. */
  45114. _this.microSurface = 1.0;
  45115. /**
  45116. * source material index of refraction (IOR)' / 'destination material IOR.
  45117. */
  45118. _this.indexOfRefraction = 0.66;
  45119. /**
  45120. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45121. */
  45122. _this.invertRefractionY = false;
  45123. /**
  45124. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45125. * Materials half opaque for instance using refraction could benefit from this control.
  45126. */
  45127. _this.linkRefractionWithTransparency = false;
  45128. _this.useLightmapAsShadowmap = false;
  45129. /**
  45130. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45131. */
  45132. _this.useAlphaFromAlbedoTexture = false;
  45133. /**
  45134. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45135. */
  45136. _this.forceAlphaTest = false;
  45137. /**
  45138. * Defines the alpha limits in alpha test mode.
  45139. */
  45140. _this.alphaCutOff = 0.4;
  45141. /**
  45142. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45143. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45144. */
  45145. _this.useSpecularOverAlpha = true;
  45146. /**
  45147. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45148. */
  45149. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45150. /**
  45151. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45152. */
  45153. _this.useRoughnessFromMetallicTextureAlpha = true;
  45154. /**
  45155. * Specifies if the metallic texture contains the roughness information in its green channel.
  45156. */
  45157. _this.useRoughnessFromMetallicTextureGreen = false;
  45158. /**
  45159. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45160. */
  45161. _this.useMetallnessFromMetallicTextureBlue = false;
  45162. /**
  45163. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45164. */
  45165. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45166. /**
  45167. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45168. */
  45169. _this.useAmbientInGrayScale = false;
  45170. /**
  45171. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45172. * The material will try to infer what glossiness each pixel should be.
  45173. */
  45174. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45175. /**
  45176. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45177. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45178. */
  45179. _this.useRadianceOverAlpha = true;
  45180. /**
  45181. * Allows using an object space normal map (instead of tangent space).
  45182. */
  45183. _this.useObjectSpaceNormalMap = false;
  45184. /**
  45185. * Allows using the bump map in parallax mode.
  45186. */
  45187. _this.useParallax = false;
  45188. /**
  45189. * Allows using the bump map in parallax occlusion mode.
  45190. */
  45191. _this.useParallaxOcclusion = false;
  45192. /**
  45193. * Controls the scale bias of the parallax mode.
  45194. */
  45195. _this.parallaxScaleBias = 0.05;
  45196. /**
  45197. * If sets to true, disables all the lights affecting the material.
  45198. */
  45199. _this.disableLighting = false;
  45200. /**
  45201. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45202. */
  45203. _this.forceIrradianceInFragment = false;
  45204. /**
  45205. * Number of Simultaneous lights allowed on the material.
  45206. */
  45207. _this.maxSimultaneousLights = 4;
  45208. /**
  45209. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45210. */
  45211. _this.invertNormalMapX = false;
  45212. /**
  45213. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45214. */
  45215. _this.invertNormalMapY = false;
  45216. /**
  45217. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45218. */
  45219. _this.twoSidedLighting = false;
  45220. /**
  45221. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45222. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45223. */
  45224. _this.useAlphaFresnel = false;
  45225. /**
  45226. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45227. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45228. */
  45229. _this.useLinearAlphaFresnel = false;
  45230. /**
  45231. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45232. * And/Or occlude the blended part.
  45233. */
  45234. _this.environmentBRDFTexture = null;
  45235. /**
  45236. * Force normal to face away from face.
  45237. */
  45238. _this.forceNormalForward = false;
  45239. /**
  45240. * Enables specular anti aliasing in the PBR shader.
  45241. * It will both interacts on the Geometry for analytical and IBL lighting.
  45242. * It also prefilter the roughness map based on the bump values.
  45243. */
  45244. _this.enableSpecularAntiAliasing = false;
  45245. /**
  45246. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45247. * makes the reflect vector face the model (under horizon).
  45248. */
  45249. _this.useHorizonOcclusion = true;
  45250. /**
  45251. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45252. * too much the area relying on ambient texture to define their ambient occlusion.
  45253. */
  45254. _this.useRadianceOcclusion = true;
  45255. /**
  45256. * If set to true, no lighting calculations will be applied.
  45257. */
  45258. _this.unlit = false;
  45259. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45260. return _this;
  45261. }
  45262. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45263. /**
  45264. * BJS is using an harcoded light falloff based on a manually sets up range.
  45265. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45266. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45267. */
  45268. get: function () {
  45269. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45270. },
  45271. /**
  45272. * BJS is using an harcoded light falloff based on a manually sets up range.
  45273. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45274. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45275. */
  45276. set: function (value) {
  45277. if (value !== this.usePhysicalLightFalloff) {
  45278. // Ensure the effect will be rebuilt.
  45279. this._markAllSubMeshesAsTexturesDirty();
  45280. if (value) {
  45281. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45282. }
  45283. else {
  45284. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45285. }
  45286. }
  45287. },
  45288. enumerable: true,
  45289. configurable: true
  45290. });
  45291. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45292. /**
  45293. * In order to support the falloff compatibility with gltf, a special mode has been added
  45294. * to reproduce the gltf light falloff.
  45295. */
  45296. get: function () {
  45297. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45298. },
  45299. /**
  45300. * In order to support the falloff compatibility with gltf, a special mode has been added
  45301. * to reproduce the gltf light falloff.
  45302. */
  45303. set: function (value) {
  45304. if (value !== this.useGLTFLightFalloff) {
  45305. // Ensure the effect will be rebuilt.
  45306. this._markAllSubMeshesAsTexturesDirty();
  45307. if (value) {
  45308. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45309. }
  45310. else {
  45311. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45312. }
  45313. }
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45319. /**
  45320. * Gets the image processing configuration used either in this material.
  45321. */
  45322. get: function () {
  45323. return this._imageProcessingConfiguration;
  45324. },
  45325. /**
  45326. * Sets the Default image processing configuration used either in the this material.
  45327. *
  45328. * If sets to null, the scene one is in use.
  45329. */
  45330. set: function (value) {
  45331. this._attachImageProcessingConfiguration(value);
  45332. // Ensure the effect will be rebuilt.
  45333. this._markAllSubMeshesAsTexturesDirty();
  45334. },
  45335. enumerable: true,
  45336. configurable: true
  45337. });
  45338. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45339. /**
  45340. * Gets wether the color curves effect is enabled.
  45341. */
  45342. get: function () {
  45343. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45344. },
  45345. /**
  45346. * Sets wether the color curves effect is enabled.
  45347. */
  45348. set: function (value) {
  45349. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45350. },
  45351. enumerable: true,
  45352. configurable: true
  45353. });
  45354. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45355. /**
  45356. * Gets wether the color grading effect is enabled.
  45357. */
  45358. get: function () {
  45359. return this.imageProcessingConfiguration.colorGradingEnabled;
  45360. },
  45361. /**
  45362. * Gets wether the color grading effect is enabled.
  45363. */
  45364. set: function (value) {
  45365. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45366. },
  45367. enumerable: true,
  45368. configurable: true
  45369. });
  45370. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45371. /**
  45372. * Gets wether tonemapping is enabled or not.
  45373. */
  45374. get: function () {
  45375. return this._imageProcessingConfiguration.toneMappingEnabled;
  45376. },
  45377. /**
  45378. * Sets wether tonemapping is enabled or not
  45379. */
  45380. set: function (value) {
  45381. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45382. },
  45383. enumerable: true,
  45384. configurable: true
  45385. });
  45386. ;
  45387. ;
  45388. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45389. /**
  45390. * The camera exposure used on this material.
  45391. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45392. * This corresponds to a photographic exposure.
  45393. */
  45394. get: function () {
  45395. return this._imageProcessingConfiguration.exposure;
  45396. },
  45397. /**
  45398. * The camera exposure used on this material.
  45399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45400. * This corresponds to a photographic exposure.
  45401. */
  45402. set: function (value) {
  45403. this._imageProcessingConfiguration.exposure = value;
  45404. },
  45405. enumerable: true,
  45406. configurable: true
  45407. });
  45408. ;
  45409. ;
  45410. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45411. /**
  45412. * Gets The camera contrast used on this material.
  45413. */
  45414. get: function () {
  45415. return this._imageProcessingConfiguration.contrast;
  45416. },
  45417. /**
  45418. * Sets The camera contrast used on this material.
  45419. */
  45420. set: function (value) {
  45421. this._imageProcessingConfiguration.contrast = value;
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45427. /**
  45428. * Gets the Color Grading 2D Lookup Texture.
  45429. */
  45430. get: function () {
  45431. return this._imageProcessingConfiguration.colorGradingTexture;
  45432. },
  45433. /**
  45434. * Sets the Color Grading 2D Lookup Texture.
  45435. */
  45436. set: function (value) {
  45437. this._imageProcessingConfiguration.colorGradingTexture = value;
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45443. /**
  45444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45446. * 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;
  45447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45448. */
  45449. get: function () {
  45450. return this._imageProcessingConfiguration.colorCurves;
  45451. },
  45452. /**
  45453. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45454. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45455. * 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;
  45456. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45457. */
  45458. set: function (value) {
  45459. this._imageProcessingConfiguration.colorCurves = value;
  45460. },
  45461. enumerable: true,
  45462. configurable: true
  45463. });
  45464. /**
  45465. * Returns the name of this material class.
  45466. */
  45467. PBRMaterial.prototype.getClassName = function () {
  45468. return "PBRMaterial";
  45469. };
  45470. /**
  45471. * Returns an array of the actively used textures.
  45472. * @returns - Array of BaseTextures
  45473. */
  45474. PBRMaterial.prototype.getActiveTextures = function () {
  45475. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45476. if (this._albedoTexture) {
  45477. activeTextures.push(this._albedoTexture);
  45478. }
  45479. if (this._ambientTexture) {
  45480. activeTextures.push(this._ambientTexture);
  45481. }
  45482. if (this._opacityTexture) {
  45483. activeTextures.push(this._opacityTexture);
  45484. }
  45485. if (this._reflectionTexture) {
  45486. activeTextures.push(this._reflectionTexture);
  45487. }
  45488. if (this._emissiveTexture) {
  45489. activeTextures.push(this._emissiveTexture);
  45490. }
  45491. if (this._reflectivityTexture) {
  45492. activeTextures.push(this._reflectivityTexture);
  45493. }
  45494. if (this._metallicTexture) {
  45495. activeTextures.push(this._metallicTexture);
  45496. }
  45497. if (this._microSurfaceTexture) {
  45498. activeTextures.push(this._microSurfaceTexture);
  45499. }
  45500. if (this._bumpTexture) {
  45501. activeTextures.push(this._bumpTexture);
  45502. }
  45503. if (this._lightmapTexture) {
  45504. activeTextures.push(this._lightmapTexture);
  45505. }
  45506. if (this._refractionTexture) {
  45507. activeTextures.push(this._refractionTexture);
  45508. }
  45509. return activeTextures;
  45510. };
  45511. /**
  45512. * Checks to see if a texture is used in the material.
  45513. * @param texture - Base texture to use.
  45514. * @returns - Boolean specifying if a texture is used in the material.
  45515. */
  45516. PBRMaterial.prototype.hasTexture = function (texture) {
  45517. if (_super.prototype.hasTexture.call(this, texture)) {
  45518. return true;
  45519. }
  45520. if (this._albedoTexture === texture) {
  45521. return true;
  45522. }
  45523. if (this._ambientTexture === texture) {
  45524. return true;
  45525. }
  45526. if (this._opacityTexture === texture) {
  45527. return true;
  45528. }
  45529. if (this._reflectionTexture === texture) {
  45530. return true;
  45531. }
  45532. if (this._reflectivityTexture === texture) {
  45533. return true;
  45534. }
  45535. if (this._metallicTexture === texture) {
  45536. return true;
  45537. }
  45538. if (this._microSurfaceTexture === texture) {
  45539. return true;
  45540. }
  45541. if (this._bumpTexture === texture) {
  45542. return true;
  45543. }
  45544. if (this._lightmapTexture === texture) {
  45545. return true;
  45546. }
  45547. if (this._refractionTexture === texture) {
  45548. return true;
  45549. }
  45550. return false;
  45551. };
  45552. /**
  45553. * Makes a duplicate of the current material.
  45554. * @param name - name to use for the new material.
  45555. */
  45556. PBRMaterial.prototype.clone = function (name) {
  45557. var _this = this;
  45558. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45559. clone.id = name;
  45560. clone.name = name;
  45561. return clone;
  45562. };
  45563. /**
  45564. * Serializes this PBR Material.
  45565. * @returns - An object with the serialized material.
  45566. */
  45567. PBRMaterial.prototype.serialize = function () {
  45568. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45569. serializationObject.customType = "BABYLON.PBRMaterial";
  45570. return serializationObject;
  45571. };
  45572. // Statics
  45573. /**
  45574. * Parses a PBR Material from a serialized object.
  45575. * @param source - Serialized object.
  45576. * @param scene - BJS scene instance.
  45577. * @param rootUrl - url for the scene object
  45578. * @returns - PBRMaterial
  45579. */
  45580. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45581. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45582. };
  45583. /**
  45584. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45585. */
  45586. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45587. /**
  45588. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45589. */
  45590. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45591. /**
  45592. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45593. */
  45594. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45595. /**
  45596. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45597. * They are also discarded below the alpha cutoff threshold to improve performances.
  45598. */
  45599. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45600. /**
  45601. * Defines the default value of how much AO map is occluding the analytical lights
  45602. * (point spot...).
  45603. */
  45604. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45605. __decorate([
  45606. BABYLON.serialize(),
  45607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45608. ], PBRMaterial.prototype, "directIntensity", void 0);
  45609. __decorate([
  45610. BABYLON.serialize(),
  45611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45612. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45613. __decorate([
  45614. BABYLON.serialize(),
  45615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45616. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45617. __decorate([
  45618. BABYLON.serialize(),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45620. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45621. __decorate([
  45622. BABYLON.serialize(),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45624. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45625. __decorate([
  45626. BABYLON.serializeAsTexture(),
  45627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45628. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45629. __decorate([
  45630. BABYLON.serializeAsTexture(),
  45631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45632. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45633. __decorate([
  45634. BABYLON.serialize(),
  45635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45636. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45637. __decorate([
  45638. BABYLON.serialize(),
  45639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45640. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45641. __decorate([
  45642. BABYLON.serializeAsTexture(),
  45643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45644. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45645. __decorate([
  45646. BABYLON.serializeAsTexture(),
  45647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45648. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45649. __decorate([
  45650. BABYLON.serializeAsTexture(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45652. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45653. __decorate([
  45654. BABYLON.serializeAsTexture(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45656. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45657. __decorate([
  45658. BABYLON.serializeAsTexture(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45660. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45661. __decorate([
  45662. BABYLON.serialize(),
  45663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45664. ], PBRMaterial.prototype, "metallic", void 0);
  45665. __decorate([
  45666. BABYLON.serialize(),
  45667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45668. ], PBRMaterial.prototype, "roughness", void 0);
  45669. __decorate([
  45670. BABYLON.serializeAsTexture(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45672. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45673. __decorate([
  45674. BABYLON.serializeAsTexture(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45677. __decorate([
  45678. BABYLON.serializeAsTexture(),
  45679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45680. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45681. __decorate([
  45682. BABYLON.serializeAsTexture(),
  45683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45684. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45685. __decorate([
  45686. BABYLON.serializeAsColor3("ambient"),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45688. ], PBRMaterial.prototype, "ambientColor", void 0);
  45689. __decorate([
  45690. BABYLON.serializeAsColor3("albedo"),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45692. ], PBRMaterial.prototype, "albedoColor", void 0);
  45693. __decorate([
  45694. BABYLON.serializeAsColor3("reflectivity"),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45696. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45697. __decorate([
  45698. BABYLON.serializeAsColor3("reflection"),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45700. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45701. __decorate([
  45702. BABYLON.serializeAsColor3("emissive"),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45704. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45705. __decorate([
  45706. BABYLON.serialize(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45708. ], PBRMaterial.prototype, "microSurface", void 0);
  45709. __decorate([
  45710. BABYLON.serialize(),
  45711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45712. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45713. __decorate([
  45714. BABYLON.serialize(),
  45715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45716. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45717. __decorate([
  45718. BABYLON.serialize(),
  45719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45720. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45721. __decorate([
  45722. BABYLON.serialize(),
  45723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45724. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45725. __decorate([
  45726. BABYLON.serialize(),
  45727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45728. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45729. __decorate([
  45730. BABYLON.serialize(),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45732. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45733. __decorate([
  45734. BABYLON.serialize(),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45736. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45737. __decorate([
  45738. BABYLON.serialize(),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45740. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45741. __decorate([
  45742. BABYLON.serialize(),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45745. __decorate([
  45746. BABYLON.serialize(),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45749. __decorate([
  45750. BABYLON.serialize(),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45752. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45760. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45769. __decorate([
  45770. BABYLON.serialize()
  45771. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45772. __decorate([
  45773. BABYLON.serialize()
  45774. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45775. __decorate([
  45776. BABYLON.serialize(),
  45777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45778. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45779. __decorate([
  45780. BABYLON.serialize(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45782. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45783. __decorate([
  45784. BABYLON.serialize(),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRMaterial.prototype, "useParallax", void 0);
  45787. __decorate([
  45788. BABYLON.serialize(),
  45789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45790. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45791. __decorate([
  45792. BABYLON.serialize(),
  45793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45794. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45795. __decorate([
  45796. BABYLON.serialize(),
  45797. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45798. ], PBRMaterial.prototype, "disableLighting", void 0);
  45799. __decorate([
  45800. BABYLON.serialize(),
  45801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45802. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45803. __decorate([
  45804. BABYLON.serialize(),
  45805. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45806. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45807. __decorate([
  45808. BABYLON.serialize(),
  45809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45810. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45811. __decorate([
  45812. BABYLON.serialize(),
  45813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45814. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45815. __decorate([
  45816. BABYLON.serialize(),
  45817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45818. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45819. __decorate([
  45820. BABYLON.serialize(),
  45821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45822. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45823. __decorate([
  45824. BABYLON.serialize(),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45826. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45827. __decorate([
  45828. BABYLON.serializeAsTexture(),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45830. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45831. __decorate([
  45832. BABYLON.serialize(),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45834. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45838. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45839. __decorate([
  45840. BABYLON.serialize(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45842. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45843. __decorate([
  45844. BABYLON.serialize(),
  45845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45846. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45847. __decorate([
  45848. BABYLON.serialize(),
  45849. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45850. ], PBRMaterial.prototype, "unlit", void 0);
  45851. return PBRMaterial;
  45852. }(BABYLON.PBRBaseMaterial));
  45853. BABYLON.PBRMaterial = PBRMaterial;
  45854. })(BABYLON || (BABYLON = {}));
  45855. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45856. var BABYLON;
  45857. (function (BABYLON) {
  45858. /**
  45859. * The PBR material of BJS following the metal roughness convention.
  45860. *
  45861. * This fits to the PBR convention in the GLTF definition:
  45862. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45863. */
  45864. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45865. __extends(PBRMetallicRoughnessMaterial, _super);
  45866. /**
  45867. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45868. *
  45869. * @param name The material name
  45870. * @param scene The scene the material will be use in.
  45871. */
  45872. function PBRMetallicRoughnessMaterial(name, scene) {
  45873. var _this = _super.call(this, name, scene) || this;
  45874. _this._useRoughnessFromMetallicTextureAlpha = false;
  45875. _this._useRoughnessFromMetallicTextureGreen = true;
  45876. _this._useMetallnessFromMetallicTextureBlue = true;
  45877. _this.metallic = 1.0;
  45878. _this.roughness = 1.0;
  45879. return _this;
  45880. }
  45881. /**
  45882. * Return the currrent class name of the material.
  45883. */
  45884. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45885. return "PBRMetallicRoughnessMaterial";
  45886. };
  45887. /**
  45888. * Return the active textures of the material.
  45889. */
  45890. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45891. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45892. if (this.baseTexture) {
  45893. activeTextures.push(this.baseTexture);
  45894. }
  45895. if (this.metallicRoughnessTexture) {
  45896. activeTextures.push(this.metallicRoughnessTexture);
  45897. }
  45898. return activeTextures;
  45899. };
  45900. /**
  45901. * Checks to see if a texture is used in the material.
  45902. * @param texture - Base texture to use.
  45903. * @returns - Boolean specifying if a texture is used in the material.
  45904. */
  45905. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45906. if (_super.prototype.hasTexture.call(this, texture)) {
  45907. return true;
  45908. }
  45909. if (this.baseTexture === texture) {
  45910. return true;
  45911. }
  45912. if (this.metallicRoughnessTexture === texture) {
  45913. return true;
  45914. }
  45915. return false;
  45916. };
  45917. /**
  45918. * Makes a duplicate of the current material.
  45919. * @param name - name to use for the new material.
  45920. */
  45921. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45922. var _this = this;
  45923. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45924. clone.id = name;
  45925. clone.name = name;
  45926. return clone;
  45927. };
  45928. /**
  45929. * Serialize the material to a parsable JSON object.
  45930. */
  45931. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45933. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45934. return serializationObject;
  45935. };
  45936. /**
  45937. * Parses a JSON object correponding to the serialize function.
  45938. */
  45939. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45940. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45941. };
  45942. __decorate([
  45943. BABYLON.serializeAsColor3(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45945. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45946. __decorate([
  45947. BABYLON.serializeAsTexture(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45949. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45950. __decorate([
  45951. BABYLON.serialize(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45954. __decorate([
  45955. BABYLON.serialize(),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45958. __decorate([
  45959. BABYLON.serializeAsTexture(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45961. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45962. return PBRMetallicRoughnessMaterial;
  45963. }(BABYLON.PBRBaseSimpleMaterial));
  45964. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45965. })(BABYLON || (BABYLON = {}));
  45966. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45967. var BABYLON;
  45968. (function (BABYLON) {
  45969. /**
  45970. * The PBR material of BJS following the specular glossiness convention.
  45971. *
  45972. * This fits to the PBR convention in the GLTF definition:
  45973. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45974. */
  45975. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45976. __extends(PBRSpecularGlossinessMaterial, _super);
  45977. /**
  45978. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45979. *
  45980. * @param name The material name
  45981. * @param scene The scene the material will be use in.
  45982. */
  45983. function PBRSpecularGlossinessMaterial(name, scene) {
  45984. var _this = _super.call(this, name, scene) || this;
  45985. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45986. return _this;
  45987. }
  45988. /**
  45989. * Return the currrent class name of the material.
  45990. */
  45991. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45992. return "PBRSpecularGlossinessMaterial";
  45993. };
  45994. /**
  45995. * Return the active textures of the material.
  45996. */
  45997. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45998. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45999. if (this.diffuseTexture) {
  46000. activeTextures.push(this.diffuseTexture);
  46001. }
  46002. if (this.specularGlossinessTexture) {
  46003. activeTextures.push(this.specularGlossinessTexture);
  46004. }
  46005. return activeTextures;
  46006. };
  46007. /**
  46008. * Checks to see if a texture is used in the material.
  46009. * @param texture - Base texture to use.
  46010. * @returns - Boolean specifying if a texture is used in the material.
  46011. */
  46012. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46013. if (_super.prototype.hasTexture.call(this, texture)) {
  46014. return true;
  46015. }
  46016. if (this.diffuseTexture === texture) {
  46017. return true;
  46018. }
  46019. if (this.specularGlossinessTexture === texture) {
  46020. return true;
  46021. }
  46022. return false;
  46023. };
  46024. /**
  46025. * Makes a duplicate of the current material.
  46026. * @param name - name to use for the new material.
  46027. */
  46028. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46029. var _this = this;
  46030. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46031. clone.id = name;
  46032. clone.name = name;
  46033. return clone;
  46034. };
  46035. /**
  46036. * Serialize the material to a parsable JSON object.
  46037. */
  46038. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46040. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46041. return serializationObject;
  46042. };
  46043. /**
  46044. * Parses a JSON object correponding to the serialize function.
  46045. */
  46046. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46047. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46048. };
  46049. __decorate([
  46050. BABYLON.serializeAsColor3("diffuse"),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46052. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46053. __decorate([
  46054. BABYLON.serializeAsTexture(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46056. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46057. __decorate([
  46058. BABYLON.serializeAsColor3("specular"),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46060. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46061. __decorate([
  46062. BABYLON.serialize(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46064. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46065. __decorate([
  46066. BABYLON.serializeAsTexture(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46068. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46069. return PBRSpecularGlossinessMaterial;
  46070. }(BABYLON.PBRBaseSimpleMaterial));
  46071. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46074. var BABYLON;
  46075. (function (BABYLON) {
  46076. /**
  46077. * This is a list of all the different input types that are available in the application.
  46078. * Fo instance: ArcRotateCameraGamepadInput...
  46079. */
  46080. BABYLON.CameraInputTypes = {};
  46081. /**
  46082. * This represents the input manager used within a camera.
  46083. * It helps dealing with all the different kind of input attached to a camera.
  46084. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46085. */
  46086. var CameraInputsManager = /** @class */ (function () {
  46087. /**
  46088. * Instantiate a new Camera Input Manager.
  46089. * @param camera Defines the camera the input manager blongs to
  46090. */
  46091. function CameraInputsManager(camera) {
  46092. this.attached = {};
  46093. this.camera = camera;
  46094. this.checkInputs = function () { };
  46095. }
  46096. /**
  46097. * Add an input method to a camera
  46098. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46099. * @param input camera input method
  46100. */
  46101. CameraInputsManager.prototype.add = function (input) {
  46102. var type = input.getSimpleName();
  46103. if (this.attached[type]) {
  46104. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46105. return;
  46106. }
  46107. this.attached[type] = input;
  46108. input.camera = this.camera;
  46109. //for checkInputs, we are dynamically creating a function
  46110. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46111. if (input.checkInputs) {
  46112. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46113. }
  46114. if (this.attachedElement) {
  46115. input.attachControl(this.attachedElement);
  46116. }
  46117. };
  46118. /**
  46119. * Remove a specific input method from a camera
  46120. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46121. * @param inputToRemove camera input method
  46122. */
  46123. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46124. for (var cam in this.attached) {
  46125. var input = this.attached[cam];
  46126. if (input === inputToRemove) {
  46127. input.detachControl(this.attachedElement);
  46128. input.camera = null;
  46129. delete this.attached[cam];
  46130. this.rebuildInputCheck();
  46131. }
  46132. }
  46133. };
  46134. /**
  46135. * Remove a specific input type from a camera
  46136. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46137. * @param inputType the type of the input to remove
  46138. */
  46139. CameraInputsManager.prototype.removeByType = function (inputType) {
  46140. for (var cam in this.attached) {
  46141. var input = this.attached[cam];
  46142. if (input.getClassName() === inputType) {
  46143. input.detachControl(this.attachedElement);
  46144. input.camera = null;
  46145. delete this.attached[cam];
  46146. this.rebuildInputCheck();
  46147. }
  46148. }
  46149. };
  46150. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46151. var current = this.checkInputs;
  46152. return function () {
  46153. current();
  46154. fn();
  46155. };
  46156. };
  46157. /**
  46158. * Attach the input controls to the currently attached dom element to listen the events from.
  46159. * @param input Defines the input to attach
  46160. */
  46161. CameraInputsManager.prototype.attachInput = function (input) {
  46162. if (this.attachedElement) {
  46163. input.attachControl(this.attachedElement, this.noPreventDefault);
  46164. }
  46165. };
  46166. /**
  46167. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46168. * @param element Defines the dom element to collect the events from
  46169. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46170. */
  46171. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46172. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46173. if (this.attachedElement) {
  46174. return;
  46175. }
  46176. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46177. this.attachedElement = element;
  46178. this.noPreventDefault = noPreventDefault;
  46179. for (var cam in this.attached) {
  46180. this.attached[cam].attachControl(element, noPreventDefault);
  46181. }
  46182. };
  46183. /**
  46184. * Detach the current manager inputs controls from a specific dom element.
  46185. * @param element Defines the dom element to collect the events from
  46186. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46187. */
  46188. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46189. if (disconnect === void 0) { disconnect = false; }
  46190. if (this.attachedElement !== element) {
  46191. return;
  46192. }
  46193. for (var cam in this.attached) {
  46194. this.attached[cam].detachControl(element);
  46195. if (disconnect) {
  46196. this.attached[cam].camera = null;
  46197. }
  46198. }
  46199. this.attachedElement = null;
  46200. };
  46201. /**
  46202. * Rebuild the dynamic inputCheck function from the current list of
  46203. * defined inputs in the manager.
  46204. */
  46205. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46206. this.checkInputs = function () { };
  46207. for (var cam in this.attached) {
  46208. var input = this.attached[cam];
  46209. if (input.checkInputs) {
  46210. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46211. }
  46212. }
  46213. };
  46214. /**
  46215. * Remove all attached input methods from a camera
  46216. */
  46217. CameraInputsManager.prototype.clear = function () {
  46218. if (this.attachedElement) {
  46219. this.detachElement(this.attachedElement, true);
  46220. }
  46221. this.attached = {};
  46222. this.attachedElement = null;
  46223. this.checkInputs = function () { };
  46224. };
  46225. /**
  46226. * Serialize the current input manager attached to a camera.
  46227. * This ensures than once parsed,
  46228. * the input associated to the camera will be identical to the current ones
  46229. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46230. */
  46231. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46232. var inputs = {};
  46233. for (var cam in this.attached) {
  46234. var input = this.attached[cam];
  46235. var res = BABYLON.SerializationHelper.Serialize(input);
  46236. inputs[input.getClassName()] = res;
  46237. }
  46238. serializedCamera.inputsmgr = inputs;
  46239. };
  46240. /**
  46241. * Parses an input manager serialized JSON to restore the previous list of inputs
  46242. * and states associated to a camera.
  46243. * @param parsedCamera Defines the JSON to parse
  46244. */
  46245. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46246. var parsedInputs = parsedCamera.inputsmgr;
  46247. if (parsedInputs) {
  46248. this.clear();
  46249. for (var n in parsedInputs) {
  46250. var construct = BABYLON.CameraInputTypes[n];
  46251. if (construct) {
  46252. var parsedinput = parsedInputs[n];
  46253. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46254. this.add(input);
  46255. }
  46256. }
  46257. }
  46258. else {
  46259. //2016-03-08 this part is for managing backward compatibility
  46260. for (var n in this.attached) {
  46261. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46262. if (construct) {
  46263. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46264. this.remove(this.attached[n]);
  46265. this.add(input);
  46266. }
  46267. }
  46268. }
  46269. };
  46270. return CameraInputsManager;
  46271. }());
  46272. BABYLON.CameraInputsManager = CameraInputsManager;
  46273. })(BABYLON || (BABYLON = {}));
  46274. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46275. var BABYLON;
  46276. (function (BABYLON) {
  46277. /**
  46278. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46279. * This is the base of the follow, arc rotate cameras and Free camera
  46280. * @see http://doc.babylonjs.com/features/cameras
  46281. */
  46282. var TargetCamera = /** @class */ (function (_super) {
  46283. __extends(TargetCamera, _super);
  46284. /**
  46285. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46286. * This is the base of the follow, arc rotate cameras and Free camera
  46287. * @see http://doc.babylonjs.com/features/cameras
  46288. * @param name Defines the name of the camera in the scene
  46289. * @param position Defines the start position of the camera in the scene
  46290. * @param scene Defines the scene the camera belongs to
  46291. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46292. */
  46293. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46294. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46295. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46296. /**
  46297. * Define the current direction the camera is moving to
  46298. */
  46299. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46300. /**
  46301. * Define the current rotation the camera is rotating to
  46302. */
  46303. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46304. /**
  46305. * Define the current rotation of the camera
  46306. */
  46307. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46308. /**
  46309. * Define the current speed of the camera
  46310. */
  46311. _this.speed = 2.0;
  46312. /**
  46313. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46314. * around all axis.
  46315. */
  46316. _this.noRotationConstraint = false;
  46317. /**
  46318. * Define the current target of the camera as an object or a position.
  46319. */
  46320. _this.lockedTarget = null;
  46321. /** @hidden */
  46322. _this._currentTarget = BABYLON.Vector3.Zero();
  46323. /** @hidden */
  46324. _this._viewMatrix = BABYLON.Matrix.Zero();
  46325. /** @hidden */
  46326. _this._camMatrix = BABYLON.Matrix.Zero();
  46327. /** @hidden */
  46328. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46329. /** @hidden */
  46330. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46331. /** @hidden */
  46332. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46333. /** @hidden */
  46334. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46335. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46336. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46337. _this._defaultUp = BABYLON.Vector3.Up();
  46338. _this._cachedRotationZ = 0;
  46339. return _this;
  46340. }
  46341. /**
  46342. * Gets the position in front of the camera at a given distance.
  46343. * @param distance The distance from the camera we want the position to be
  46344. * @returns the position
  46345. */
  46346. TargetCamera.prototype.getFrontPosition = function (distance) {
  46347. this.getWorldMatrix();
  46348. var direction = this.getTarget().subtract(this.position);
  46349. direction.normalize();
  46350. direction.scaleInPlace(distance);
  46351. return this.globalPosition.add(direction);
  46352. };
  46353. /** @hidden */
  46354. TargetCamera.prototype._getLockedTargetPosition = function () {
  46355. if (!this.lockedTarget) {
  46356. return null;
  46357. }
  46358. if (this.lockedTarget.absolutePosition) {
  46359. this.lockedTarget.computeWorldMatrix();
  46360. }
  46361. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46362. };
  46363. /**
  46364. * Store current camera state of the camera (fov, position, rotation, etc..)
  46365. * @returns the camera
  46366. */
  46367. TargetCamera.prototype.storeState = function () {
  46368. this._storedPosition = this.position.clone();
  46369. this._storedRotation = this.rotation.clone();
  46370. if (this.rotationQuaternion) {
  46371. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46372. }
  46373. return _super.prototype.storeState.call(this);
  46374. };
  46375. /**
  46376. * Restored camera state. You must call storeState() first
  46377. * @returns whether it was successful or not
  46378. * @hidden
  46379. */
  46380. TargetCamera.prototype._restoreStateValues = function () {
  46381. if (!_super.prototype._restoreStateValues.call(this)) {
  46382. return false;
  46383. }
  46384. this.position = this._storedPosition.clone();
  46385. this.rotation = this._storedRotation.clone();
  46386. if (this.rotationQuaternion) {
  46387. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46388. }
  46389. this.cameraDirection.copyFromFloats(0, 0, 0);
  46390. this.cameraRotation.copyFromFloats(0, 0);
  46391. return true;
  46392. };
  46393. /** @hidden */
  46394. TargetCamera.prototype._initCache = function () {
  46395. _super.prototype._initCache.call(this);
  46396. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46397. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46398. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46399. };
  46400. /** @hidden */
  46401. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46402. if (!ignoreParentClass) {
  46403. _super.prototype._updateCache.call(this);
  46404. }
  46405. var lockedTargetPosition = this._getLockedTargetPosition();
  46406. if (!lockedTargetPosition) {
  46407. this._cache.lockedTarget = null;
  46408. }
  46409. else {
  46410. if (!this._cache.lockedTarget) {
  46411. this._cache.lockedTarget = lockedTargetPosition.clone();
  46412. }
  46413. else {
  46414. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46415. }
  46416. }
  46417. this._cache.rotation.copyFrom(this.rotation);
  46418. if (this.rotationQuaternion)
  46419. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46420. };
  46421. // Synchronized
  46422. /** @hidden */
  46423. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46424. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46425. return false;
  46426. }
  46427. var lockedTargetPosition = this._getLockedTargetPosition();
  46428. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46429. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46430. };
  46431. // Methods
  46432. /** @hidden */
  46433. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46434. var engine = this.getEngine();
  46435. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46436. };
  46437. // Target
  46438. /** @hidden */
  46439. TargetCamera.prototype.setTarget = function (target) {
  46440. this.upVector.normalize();
  46441. if (this.position.z === target.z) {
  46442. this.position.z += BABYLON.Epsilon;
  46443. }
  46444. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46445. this._camMatrix.invert();
  46446. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46447. var vDir = target.subtract(this.position);
  46448. if (vDir.x >= 0.0) {
  46449. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46450. }
  46451. else {
  46452. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46453. }
  46454. this.rotation.z = 0;
  46455. if (isNaN(this.rotation.x)) {
  46456. this.rotation.x = 0;
  46457. }
  46458. if (isNaN(this.rotation.y)) {
  46459. this.rotation.y = 0;
  46460. }
  46461. if (isNaN(this.rotation.z)) {
  46462. this.rotation.z = 0;
  46463. }
  46464. if (this.rotationQuaternion) {
  46465. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46466. }
  46467. };
  46468. /**
  46469. * Return the current target position of the camera. This value is expressed in local space.
  46470. * @returns the target position
  46471. */
  46472. TargetCamera.prototype.getTarget = function () {
  46473. return this._currentTarget;
  46474. };
  46475. /** @hidden */
  46476. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46477. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46478. };
  46479. /** @hidden */
  46480. TargetCamera.prototype._updatePosition = function () {
  46481. if (this.parent) {
  46482. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46483. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46484. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46485. return;
  46486. }
  46487. this.position.addInPlace(this.cameraDirection);
  46488. };
  46489. /** @hidden */
  46490. TargetCamera.prototype._checkInputs = function () {
  46491. var needToMove = this._decideIfNeedsToMove();
  46492. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46493. // Move
  46494. if (needToMove) {
  46495. this._updatePosition();
  46496. }
  46497. // Rotate
  46498. if (needToRotate) {
  46499. this.rotation.x += this.cameraRotation.x;
  46500. this.rotation.y += this.cameraRotation.y;
  46501. //rotate, if quaternion is set and rotation was used
  46502. if (this.rotationQuaternion) {
  46503. var len = this.rotation.lengthSquared();
  46504. if (len) {
  46505. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46506. }
  46507. }
  46508. if (!this.noRotationConstraint) {
  46509. var limit = (Math.PI / 2) * 0.95;
  46510. if (this.rotation.x > limit)
  46511. this.rotation.x = limit;
  46512. if (this.rotation.x < -limit)
  46513. this.rotation.x = -limit;
  46514. }
  46515. }
  46516. // Inertia
  46517. if (needToMove) {
  46518. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46519. this.cameraDirection.x = 0;
  46520. }
  46521. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46522. this.cameraDirection.y = 0;
  46523. }
  46524. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46525. this.cameraDirection.z = 0;
  46526. }
  46527. this.cameraDirection.scaleInPlace(this.inertia);
  46528. }
  46529. if (needToRotate) {
  46530. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46531. this.cameraRotation.x = 0;
  46532. }
  46533. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46534. this.cameraRotation.y = 0;
  46535. }
  46536. this.cameraRotation.scaleInPlace(this.inertia);
  46537. }
  46538. _super.prototype._checkInputs.call(this);
  46539. };
  46540. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46541. if (this.rotationQuaternion) {
  46542. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46543. }
  46544. else {
  46545. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46546. }
  46547. };
  46548. /**
  46549. * 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)
  46550. * @returns the current camera
  46551. */
  46552. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46553. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46554. return this;
  46555. };
  46556. /** @hidden */
  46557. TargetCamera.prototype._getViewMatrix = function () {
  46558. if (this.lockedTarget) {
  46559. this.setTarget(this._getLockedTargetPosition());
  46560. }
  46561. // Compute
  46562. this._updateCameraRotationMatrix();
  46563. // Apply the changed rotation to the upVector.
  46564. if (this._cachedRotationZ != this.rotation.z) {
  46565. this._rotateUpVectorWithCameraRotationMatrix();
  46566. this._cachedRotationZ = this.rotation.z;
  46567. }
  46568. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46569. // Computing target and final matrix
  46570. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46571. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46572. return this._viewMatrix;
  46573. };
  46574. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46575. if (this.parent) {
  46576. var parentWorldMatrix = this.parent.getWorldMatrix();
  46577. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46578. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46579. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46580. this._markSyncedWithParent();
  46581. }
  46582. else {
  46583. this._globalPosition.copyFrom(position);
  46584. this._globalCurrentTarget.copyFrom(target);
  46585. this._globalCurrentUpVector.copyFrom(up);
  46586. }
  46587. if (this.getScene().useRightHandedSystem) {
  46588. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46589. }
  46590. else {
  46591. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46592. }
  46593. };
  46594. /**
  46595. * @hidden
  46596. */
  46597. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46598. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46599. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46600. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46601. if (!this.rotationQuaternion) {
  46602. this.rotationQuaternion = new BABYLON.Quaternion();
  46603. }
  46604. rigCamera._cameraRigParams = {};
  46605. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46606. }
  46607. return rigCamera;
  46608. }
  46609. return null;
  46610. };
  46611. /**
  46612. * @hidden
  46613. */
  46614. TargetCamera.prototype._updateRigCameras = function () {
  46615. var camLeft = this._rigCameras[0];
  46616. var camRight = this._rigCameras[1];
  46617. switch (this.cameraRigMode) {
  46618. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46619. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46620. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46621. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46622. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46623. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46624. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46625. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46626. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46627. camLeft.setTarget(this.getTarget());
  46628. camRight.setTarget(this.getTarget());
  46629. break;
  46630. case BABYLON.Camera.RIG_MODE_VR:
  46631. if (camLeft.rotationQuaternion) {
  46632. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46633. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46634. }
  46635. else {
  46636. camLeft.rotation.copyFrom(this.rotation);
  46637. camRight.rotation.copyFrom(this.rotation);
  46638. }
  46639. camLeft.position.copyFrom(this.position);
  46640. camRight.position.copyFrom(this.position);
  46641. break;
  46642. }
  46643. _super.prototype._updateRigCameras.call(this);
  46644. };
  46645. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46646. if (!this._rigCamTransformMatrix) {
  46647. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46648. }
  46649. var target = this.getTarget();
  46650. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46651. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46652. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46653. };
  46654. /**
  46655. * Gets the current object class name.
  46656. * @return the class name
  46657. */
  46658. TargetCamera.prototype.getClassName = function () {
  46659. return "TargetCamera";
  46660. };
  46661. __decorate([
  46662. BABYLON.serializeAsVector3()
  46663. ], TargetCamera.prototype, "rotation", void 0);
  46664. __decorate([
  46665. BABYLON.serialize()
  46666. ], TargetCamera.prototype, "speed", void 0);
  46667. __decorate([
  46668. BABYLON.serializeAsMeshReference("lockedTargetId")
  46669. ], TargetCamera.prototype, "lockedTarget", void 0);
  46670. return TargetCamera;
  46671. }(BABYLON.Camera));
  46672. BABYLON.TargetCamera = TargetCamera;
  46673. })(BABYLON || (BABYLON = {}));
  46674. //# sourceMappingURL=babylon.targetCamera.js.map
  46675. var BABYLON;
  46676. (function (BABYLON) {
  46677. /**
  46678. * Manage the mouse inputs to control the movement of a free camera.
  46679. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46680. */
  46681. var FreeCameraMouseInput = /** @class */ (function () {
  46682. /**
  46683. * Manage the mouse inputs to control the movement of a free camera.
  46684. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46685. * @param touchEnabled Defines if touch is enabled or not
  46686. */
  46687. function FreeCameraMouseInput(
  46688. /**
  46689. * Define if touch is enabled in the mouse input
  46690. */
  46691. touchEnabled) {
  46692. if (touchEnabled === void 0) { touchEnabled = true; }
  46693. this.touchEnabled = touchEnabled;
  46694. /**
  46695. * Defines the buttons associated with the input to handle camera move.
  46696. */
  46697. this.buttons = [0, 1, 2];
  46698. /**
  46699. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46700. */
  46701. this.angularSensibility = 2000.0;
  46702. this.previousPosition = null;
  46703. }
  46704. /**
  46705. * Attach the input controls to a specific dom element to get the input from.
  46706. * @param element Defines the element the controls should be listened from
  46707. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46708. */
  46709. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46710. var _this = this;
  46711. var engine = this.camera.getEngine();
  46712. if (!this._pointerInput) {
  46713. this._pointerInput = function (p, s) {
  46714. var evt = p.event;
  46715. if (engine.isInVRExclusivePointerMode) {
  46716. return;
  46717. }
  46718. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46719. return;
  46720. }
  46721. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46722. return;
  46723. }
  46724. var srcElement = (evt.srcElement || evt.target);
  46725. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46726. try {
  46727. srcElement.setPointerCapture(evt.pointerId);
  46728. }
  46729. catch (e) {
  46730. //Nothing to do with the error. Execution will continue.
  46731. }
  46732. _this.previousPosition = {
  46733. x: evt.clientX,
  46734. y: evt.clientY
  46735. };
  46736. if (!noPreventDefault) {
  46737. evt.preventDefault();
  46738. element.focus();
  46739. }
  46740. }
  46741. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46742. try {
  46743. srcElement.releasePointerCapture(evt.pointerId);
  46744. }
  46745. catch (e) {
  46746. //Nothing to do with the error.
  46747. }
  46748. _this.previousPosition = null;
  46749. if (!noPreventDefault) {
  46750. evt.preventDefault();
  46751. }
  46752. }
  46753. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46754. if (!_this.previousPosition || engine.isPointerLock) {
  46755. return;
  46756. }
  46757. var offsetX = evt.clientX - _this.previousPosition.x;
  46758. if (_this.camera.getScene().useRightHandedSystem)
  46759. offsetX *= -1;
  46760. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46761. offsetX *= -1;
  46762. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46763. var offsetY = evt.clientY - _this.previousPosition.y;
  46764. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46765. _this.previousPosition = {
  46766. x: evt.clientX,
  46767. y: evt.clientY
  46768. };
  46769. if (!noPreventDefault) {
  46770. evt.preventDefault();
  46771. }
  46772. }
  46773. };
  46774. }
  46775. this._onMouseMove = function (evt) {
  46776. if (!engine.isPointerLock) {
  46777. return;
  46778. }
  46779. if (engine.isInVRExclusivePointerMode) {
  46780. return;
  46781. }
  46782. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46783. if (_this.camera.getScene().useRightHandedSystem)
  46784. offsetX *= -1;
  46785. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46786. offsetX *= -1;
  46787. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46788. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46789. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46790. _this.previousPosition = null;
  46791. if (!noPreventDefault) {
  46792. evt.preventDefault();
  46793. }
  46794. };
  46795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46796. element.addEventListener("mousemove", this._onMouseMove, false);
  46797. };
  46798. /**
  46799. * Detach the current controls from the specified dom element.
  46800. * @param element Defines the element to stop listening the inputs from
  46801. */
  46802. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46803. if (this._observer && element) {
  46804. this.camera.getScene().onPointerObservable.remove(this._observer);
  46805. if (this._onMouseMove) {
  46806. element.removeEventListener("mousemove", this._onMouseMove);
  46807. }
  46808. this._observer = null;
  46809. this._onMouseMove = null;
  46810. this.previousPosition = null;
  46811. }
  46812. };
  46813. /**
  46814. * Gets the class name of the current intput.
  46815. * @returns the class name
  46816. */
  46817. FreeCameraMouseInput.prototype.getClassName = function () {
  46818. return "FreeCameraMouseInput";
  46819. };
  46820. /**
  46821. * Get the friendly name associated with the input class.
  46822. * @returns the input friendly name
  46823. */
  46824. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46825. return "mouse";
  46826. };
  46827. __decorate([
  46828. BABYLON.serialize()
  46829. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46830. __decorate([
  46831. BABYLON.serialize()
  46832. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46833. return FreeCameraMouseInput;
  46834. }());
  46835. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46836. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46837. })(BABYLON || (BABYLON = {}));
  46838. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46839. var BABYLON;
  46840. (function (BABYLON) {
  46841. /**
  46842. * Manage the keyboard inputs to control the movement of a free camera.
  46843. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46844. */
  46845. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46846. function FreeCameraKeyboardMoveInput() {
  46847. /**
  46848. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46849. */
  46850. this.keysUp = [38];
  46851. /**
  46852. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46853. */
  46854. this.keysDown = [40];
  46855. /**
  46856. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46857. */
  46858. this.keysLeft = [37];
  46859. /**
  46860. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46861. */
  46862. this.keysRight = [39];
  46863. this._keys = new Array();
  46864. }
  46865. /**
  46866. * Attach the input controls to a specific dom element to get the input from.
  46867. * @param element Defines the element the controls should be listened from
  46868. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46869. */
  46870. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46871. var _this = this;
  46872. if (this._onCanvasBlurObserver) {
  46873. return;
  46874. }
  46875. this._scene = this.camera.getScene();
  46876. this._engine = this._scene.getEngine();
  46877. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46878. _this._keys = [];
  46879. });
  46880. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46881. var evt = info.event;
  46882. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46883. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46884. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46885. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46886. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46887. var index = _this._keys.indexOf(evt.keyCode);
  46888. if (index === -1) {
  46889. _this._keys.push(evt.keyCode);
  46890. }
  46891. if (!noPreventDefault) {
  46892. evt.preventDefault();
  46893. }
  46894. }
  46895. }
  46896. else {
  46897. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46898. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46899. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46900. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46901. var index = _this._keys.indexOf(evt.keyCode);
  46902. if (index >= 0) {
  46903. _this._keys.splice(index, 1);
  46904. }
  46905. if (!noPreventDefault) {
  46906. evt.preventDefault();
  46907. }
  46908. }
  46909. }
  46910. });
  46911. };
  46912. /**
  46913. * Detach the current controls from the specified dom element.
  46914. * @param element Defines the element to stop listening the inputs from
  46915. */
  46916. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46917. if (this._scene) {
  46918. if (this._onKeyboardObserver) {
  46919. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46920. }
  46921. if (this._onCanvasBlurObserver) {
  46922. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46923. }
  46924. this._onKeyboardObserver = null;
  46925. this._onCanvasBlurObserver = null;
  46926. }
  46927. this._keys = [];
  46928. };
  46929. /**
  46930. * Update the current camera state depending on the inputs that have been used this frame.
  46931. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  46932. */
  46933. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46934. if (this._onKeyboardObserver) {
  46935. var camera = this.camera;
  46936. // Keyboard
  46937. for (var index = 0; index < this._keys.length; index++) {
  46938. var keyCode = this._keys[index];
  46939. var speed = camera._computeLocalCameraSpeed();
  46940. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46941. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46942. }
  46943. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46944. camera._localDirection.copyFromFloats(0, 0, speed);
  46945. }
  46946. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46947. camera._localDirection.copyFromFloats(speed, 0, 0);
  46948. }
  46949. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46950. camera._localDirection.copyFromFloats(0, 0, -speed);
  46951. }
  46952. if (camera.getScene().useRightHandedSystem) {
  46953. camera._localDirection.z *= -1;
  46954. }
  46955. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46956. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46957. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46958. }
  46959. }
  46960. };
  46961. /**
  46962. * Gets the class name of the current intput.
  46963. * @returns the class name
  46964. */
  46965. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46966. return "FreeCameraKeyboardMoveInput";
  46967. };
  46968. /** @hidden */
  46969. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46970. this._keys = [];
  46971. };
  46972. /**
  46973. * Get the friendly name associated with the input class.
  46974. * @returns the input friendly name
  46975. */
  46976. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46977. return "keyboard";
  46978. };
  46979. __decorate([
  46980. BABYLON.serialize()
  46981. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46982. __decorate([
  46983. BABYLON.serialize()
  46984. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46985. __decorate([
  46986. BABYLON.serialize()
  46987. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46988. __decorate([
  46989. BABYLON.serialize()
  46990. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46991. return FreeCameraKeyboardMoveInput;
  46992. }());
  46993. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46994. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46995. })(BABYLON || (BABYLON = {}));
  46996. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46997. var BABYLON;
  46998. (function (BABYLON) {
  46999. /**
  47000. * Default Inputs manager for the FreeCamera.
  47001. * It groups all the default supported inputs for ease of use.
  47002. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47003. */
  47004. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47005. __extends(FreeCameraInputsManager, _super);
  47006. /**
  47007. * Instantiates a new FreeCameraInputsManager.
  47008. * @param camera Defines the camera the inputs belong to
  47009. */
  47010. function FreeCameraInputsManager(camera) {
  47011. return _super.call(this, camera) || this;
  47012. }
  47013. /**
  47014. * Add keyboard input support to the input manager.
  47015. * @returns the current input manager
  47016. */
  47017. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47018. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47019. return this;
  47020. };
  47021. /**
  47022. * Add mouse input support to the input manager.
  47023. * @returns the current input manager
  47024. */
  47025. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47026. if (touchEnabled === void 0) { touchEnabled = true; }
  47027. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47028. return this;
  47029. };
  47030. /**
  47031. * Add orientation input support to the input manager.
  47032. * @returns the current input manager
  47033. */
  47034. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47035. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47036. return this;
  47037. };
  47038. /**
  47039. * Add touch input support to the input manager.
  47040. * @returns the current input manager
  47041. */
  47042. FreeCameraInputsManager.prototype.addTouch = function () {
  47043. this.add(new BABYLON.FreeCameraTouchInput());
  47044. return this;
  47045. };
  47046. /**
  47047. * Add virtual joystick input support to the input manager.
  47048. * @returns the current input manager
  47049. */
  47050. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47051. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47052. return this;
  47053. };
  47054. return FreeCameraInputsManager;
  47055. }(BABYLON.CameraInputsManager));
  47056. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47057. })(BABYLON || (BABYLON = {}));
  47058. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47059. var BABYLON;
  47060. (function (BABYLON) {
  47061. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47062. // Forcing to use the Universal camera
  47063. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47064. });
  47065. /**
  47066. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47067. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47068. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47069. */
  47070. var FreeCamera = /** @class */ (function (_super) {
  47071. __extends(FreeCamera, _super);
  47072. /**
  47073. * Instantiates a Free Camera.
  47074. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47075. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47076. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47077. * @param name Define the name of the camera in the scene
  47078. * @param position Define the start position of the camera in the scene
  47079. * @param scene Define the scene the camera belongs to
  47080. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47081. */
  47082. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47083. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47084. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47085. /**
  47086. * Define the collision ellipsoid of the camera.
  47087. * This is helpful to simulate a camera body like the player body around the camera
  47088. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47089. */
  47090. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47091. /**
  47092. * Define an offset for the position of the ellipsoid around the camera.
  47093. * This can be helpful to determine the center of the body near the gravity center of the body
  47094. * instead of its head.
  47095. */
  47096. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47097. /**
  47098. * Enable or disable collisions of the camera with the rest of the scene objects.
  47099. */
  47100. _this.checkCollisions = false;
  47101. /**
  47102. * Enable or disable gravity on the camera.
  47103. */
  47104. _this.applyGravity = false;
  47105. _this._needMoveForGravity = false;
  47106. _this._oldPosition = BABYLON.Vector3.Zero();
  47107. _this._diffPosition = BABYLON.Vector3.Zero();
  47108. _this._newPosition = BABYLON.Vector3.Zero();
  47109. // Collisions
  47110. _this._collisionMask = -1;
  47111. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47112. if (collidedMesh === void 0) { collidedMesh = null; }
  47113. //TODO move this to the collision coordinator!
  47114. if (_this.getScene().workerCollisions)
  47115. newPosition.multiplyInPlace(_this._collider._radius);
  47116. var updatePosition = function (newPos) {
  47117. _this._newPosition.copyFrom(newPos);
  47118. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47119. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47120. _this.position.addInPlace(_this._diffPosition);
  47121. if (_this.onCollide && collidedMesh) {
  47122. _this.onCollide(collidedMesh);
  47123. }
  47124. }
  47125. };
  47126. updatePosition(newPosition);
  47127. };
  47128. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47129. _this.inputs.addKeyboard().addMouse();
  47130. return _this;
  47131. }
  47132. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47133. /**
  47134. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47135. * Higher values reduce sensitivity.
  47136. */
  47137. get: function () {
  47138. var mouse = this.inputs.attached["mouse"];
  47139. if (mouse)
  47140. return mouse.angularSensibility;
  47141. return 0;
  47142. },
  47143. /**
  47144. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47145. * Higher values reduce sensitivity.
  47146. */
  47147. set: function (value) {
  47148. var mouse = this.inputs.attached["mouse"];
  47149. if (mouse)
  47150. mouse.angularSensibility = value;
  47151. },
  47152. enumerable: true,
  47153. configurable: true
  47154. });
  47155. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47156. /**
  47157. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47158. */
  47159. get: function () {
  47160. var keyboard = this.inputs.attached["keyboard"];
  47161. if (keyboard)
  47162. return keyboard.keysUp;
  47163. return [];
  47164. },
  47165. set: function (value) {
  47166. var keyboard = this.inputs.attached["keyboard"];
  47167. if (keyboard)
  47168. keyboard.keysUp = value;
  47169. },
  47170. enumerable: true,
  47171. configurable: true
  47172. });
  47173. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47174. /**
  47175. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47176. */
  47177. get: function () {
  47178. var keyboard = this.inputs.attached["keyboard"];
  47179. if (keyboard)
  47180. return keyboard.keysDown;
  47181. return [];
  47182. },
  47183. set: function (value) {
  47184. var keyboard = this.inputs.attached["keyboard"];
  47185. if (keyboard)
  47186. keyboard.keysDown = value;
  47187. },
  47188. enumerable: true,
  47189. configurable: true
  47190. });
  47191. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47192. /**
  47193. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47194. */
  47195. get: function () {
  47196. var keyboard = this.inputs.attached["keyboard"];
  47197. if (keyboard)
  47198. return keyboard.keysLeft;
  47199. return [];
  47200. },
  47201. set: function (value) {
  47202. var keyboard = this.inputs.attached["keyboard"];
  47203. if (keyboard)
  47204. keyboard.keysLeft = value;
  47205. },
  47206. enumerable: true,
  47207. configurable: true
  47208. });
  47209. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47210. /**
  47211. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47212. */
  47213. get: function () {
  47214. var keyboard = this.inputs.attached["keyboard"];
  47215. if (keyboard)
  47216. return keyboard.keysRight;
  47217. return [];
  47218. },
  47219. set: function (value) {
  47220. var keyboard = this.inputs.attached["keyboard"];
  47221. if (keyboard)
  47222. keyboard.keysRight = value;
  47223. },
  47224. enumerable: true,
  47225. configurable: true
  47226. });
  47227. /**
  47228. * Attached controls to the current camera.
  47229. * @param element Defines the element the controls should be listened from
  47230. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47231. */
  47232. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47233. this.inputs.attachElement(element, noPreventDefault);
  47234. };
  47235. /**
  47236. * Detach the current controls from the camera.
  47237. * The camera will stop reacting to inputs.
  47238. * @param element Defines the element to stop listening the inputs from
  47239. */
  47240. FreeCamera.prototype.detachControl = function (element) {
  47241. this.inputs.detachElement(element);
  47242. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47243. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47244. };
  47245. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47246. /**
  47247. * Define a collision mask to limit the list of object the camera can collide with
  47248. */
  47249. get: function () {
  47250. return this._collisionMask;
  47251. },
  47252. set: function (mask) {
  47253. this._collisionMask = !isNaN(mask) ? mask : -1;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. /** @hidden */
  47259. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47260. var globalPosition;
  47261. if (this.parent) {
  47262. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47263. }
  47264. else {
  47265. globalPosition = this.position;
  47266. }
  47267. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47268. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47269. if (!this._collider) {
  47270. this._collider = new BABYLON.Collider();
  47271. }
  47272. this._collider._radius = this.ellipsoid;
  47273. this._collider.collisionMask = this._collisionMask;
  47274. //no need for clone, as long as gravity is not on.
  47275. var actualDisplacement = displacement;
  47276. //add gravity to the direction to prevent the dual-collision checking
  47277. if (this.applyGravity) {
  47278. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47279. actualDisplacement = displacement.add(this.getScene().gravity);
  47280. }
  47281. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47282. };
  47283. /** @hidden */
  47284. FreeCamera.prototype._checkInputs = function () {
  47285. if (!this._localDirection) {
  47286. this._localDirection = BABYLON.Vector3.Zero();
  47287. this._transformedDirection = BABYLON.Vector3.Zero();
  47288. }
  47289. this.inputs.checkInputs();
  47290. _super.prototype._checkInputs.call(this);
  47291. };
  47292. /** @hidden */
  47293. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47294. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47295. };
  47296. /** @hidden */
  47297. FreeCamera.prototype._updatePosition = function () {
  47298. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47299. this._collideWithWorld(this.cameraDirection);
  47300. }
  47301. else {
  47302. _super.prototype._updatePosition.call(this);
  47303. }
  47304. };
  47305. /**
  47306. * Destroy the camera and release the current resources hold by it.
  47307. */
  47308. FreeCamera.prototype.dispose = function () {
  47309. this.inputs.clear();
  47310. _super.prototype.dispose.call(this);
  47311. };
  47312. /**
  47313. * Gets the current object class name.
  47314. * @return the class name
  47315. */
  47316. FreeCamera.prototype.getClassName = function () {
  47317. return "FreeCamera";
  47318. };
  47319. __decorate([
  47320. BABYLON.serializeAsVector3()
  47321. ], FreeCamera.prototype, "ellipsoid", void 0);
  47322. __decorate([
  47323. BABYLON.serializeAsVector3()
  47324. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47325. __decorate([
  47326. BABYLON.serialize()
  47327. ], FreeCamera.prototype, "checkCollisions", void 0);
  47328. __decorate([
  47329. BABYLON.serialize()
  47330. ], FreeCamera.prototype, "applyGravity", void 0);
  47331. return FreeCamera;
  47332. }(BABYLON.TargetCamera));
  47333. BABYLON.FreeCamera = FreeCamera;
  47334. })(BABYLON || (BABYLON = {}));
  47335. //# sourceMappingURL=babylon.freeCamera.js.map
  47336. var BABYLON;
  47337. (function (BABYLON) {
  47338. /**
  47339. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47340. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47341. */
  47342. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47343. function ArcRotateCameraKeyboardMoveInput() {
  47344. /**
  47345. * Defines the list of key codes associated with the up action (increase alpha)
  47346. */
  47347. this.keysUp = [38];
  47348. /**
  47349. * Defines the list of key codes associated with the down action (decrease alpha)
  47350. */
  47351. this.keysDown = [40];
  47352. /**
  47353. * Defines the list of key codes associated with the left action (increase beta)
  47354. */
  47355. this.keysLeft = [37];
  47356. /**
  47357. * Defines the list of key codes associated with the right action (decrease beta)
  47358. */
  47359. this.keysRight = [39];
  47360. /**
  47361. * Defines the list of key codes associated with the reset action.
  47362. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47363. */
  47364. this.keysReset = [220];
  47365. /**
  47366. * Defines the panning sensibility of the inputs.
  47367. * (How fast is the camera paning)
  47368. */
  47369. this.panningSensibility = 50.0;
  47370. /**
  47371. * Defines the zooming sensibility of the inputs.
  47372. * (How fast is the camera zooming)
  47373. */
  47374. this.zoomingSensibility = 25.0;
  47375. /**
  47376. * Defines wether maintaining the alt key down switch the movement mode from
  47377. * orientation to zoom.
  47378. */
  47379. this.useAltToZoom = true;
  47380. this._keys = new Array();
  47381. }
  47382. /**
  47383. * Attach the input controls to a specific dom element to get the input from.
  47384. * @param element Defines the element the controls should be listened from
  47385. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47386. */
  47387. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47388. var _this = this;
  47389. if (this._onCanvasBlurObserver) {
  47390. return;
  47391. }
  47392. this._scene = this.camera.getScene();
  47393. this._engine = this._scene.getEngine();
  47394. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47395. _this._keys = [];
  47396. });
  47397. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47398. var evt = info.event;
  47399. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47400. _this._ctrlPressed = evt.ctrlKey;
  47401. _this._altPressed = evt.altKey;
  47402. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47403. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47404. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47405. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47406. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47407. var index = _this._keys.indexOf(evt.keyCode);
  47408. if (index === -1) {
  47409. _this._keys.push(evt.keyCode);
  47410. }
  47411. if (evt.preventDefault) {
  47412. if (!noPreventDefault) {
  47413. evt.preventDefault();
  47414. }
  47415. }
  47416. }
  47417. }
  47418. else {
  47419. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47420. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47421. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47422. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47423. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47424. var index = _this._keys.indexOf(evt.keyCode);
  47425. if (index >= 0) {
  47426. _this._keys.splice(index, 1);
  47427. }
  47428. if (evt.preventDefault) {
  47429. if (!noPreventDefault) {
  47430. evt.preventDefault();
  47431. }
  47432. }
  47433. }
  47434. }
  47435. });
  47436. };
  47437. /**
  47438. * Detach the current controls from the specified dom element.
  47439. * @param element Defines the element to stop listening the inputs from
  47440. */
  47441. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47442. if (this._scene) {
  47443. if (this._onKeyboardObserver) {
  47444. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47445. }
  47446. if (this._onCanvasBlurObserver) {
  47447. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47448. }
  47449. this._onKeyboardObserver = null;
  47450. this._onCanvasBlurObserver = null;
  47451. }
  47452. this._keys = [];
  47453. };
  47454. /**
  47455. * Update the current camera state depending on the inputs that have been used this frame.
  47456. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47457. */
  47458. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47459. if (this._onKeyboardObserver) {
  47460. var camera = this.camera;
  47461. for (var index = 0; index < this._keys.length; index++) {
  47462. var keyCode = this._keys[index];
  47463. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47464. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47465. camera.inertialPanningX -= 1 / this.panningSensibility;
  47466. }
  47467. else {
  47468. camera.inertialAlphaOffset -= 0.01;
  47469. }
  47470. }
  47471. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47472. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47473. camera.inertialPanningY += 1 / this.panningSensibility;
  47474. }
  47475. else if (this._altPressed && this.useAltToZoom) {
  47476. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47477. }
  47478. else {
  47479. camera.inertialBetaOffset -= 0.01;
  47480. }
  47481. }
  47482. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47483. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47484. camera.inertialPanningX += 1 / this.panningSensibility;
  47485. }
  47486. else {
  47487. camera.inertialAlphaOffset += 0.01;
  47488. }
  47489. }
  47490. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47491. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47492. camera.inertialPanningY -= 1 / this.panningSensibility;
  47493. }
  47494. else if (this._altPressed && this.useAltToZoom) {
  47495. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47496. }
  47497. else {
  47498. camera.inertialBetaOffset += 0.01;
  47499. }
  47500. }
  47501. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47502. if (camera.useInputToRestoreState) {
  47503. camera.restoreState();
  47504. }
  47505. }
  47506. }
  47507. }
  47508. };
  47509. /**
  47510. * Gets the class name of the current intput.
  47511. * @returns the class name
  47512. */
  47513. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47514. return "ArcRotateCameraKeyboardMoveInput";
  47515. };
  47516. /**
  47517. * Get the friendly name associated with the input class.
  47518. * @returns the input friendly name
  47519. */
  47520. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47521. return "keyboard";
  47522. };
  47523. __decorate([
  47524. BABYLON.serialize()
  47525. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47526. __decorate([
  47527. BABYLON.serialize()
  47528. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47529. __decorate([
  47530. BABYLON.serialize()
  47531. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47532. __decorate([
  47533. BABYLON.serialize()
  47534. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47535. __decorate([
  47536. BABYLON.serialize()
  47537. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47538. __decorate([
  47539. BABYLON.serialize()
  47540. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47541. __decorate([
  47542. BABYLON.serialize()
  47543. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47544. __decorate([
  47545. BABYLON.serialize()
  47546. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47547. return ArcRotateCameraKeyboardMoveInput;
  47548. }());
  47549. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47550. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47551. })(BABYLON || (BABYLON = {}));
  47552. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47553. var BABYLON;
  47554. (function (BABYLON) {
  47555. /**
  47556. * Manage the mouse wheel inputs to control an arc rotate camera.
  47557. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47558. */
  47559. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47560. function ArcRotateCameraMouseWheelInput() {
  47561. /**
  47562. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47563. */
  47564. this.wheelPrecision = 3.0;
  47565. /**
  47566. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47567. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47568. */
  47569. this.wheelDeltaPercentage = 0;
  47570. }
  47571. /**
  47572. * Attach the input controls to a specific dom element to get the input from.
  47573. * @param element Defines the element the controls should be listened from
  47574. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47575. */
  47576. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47577. var _this = this;
  47578. this._wheel = function (p, s) {
  47579. //sanity check - this should be a PointerWheel event.
  47580. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47581. return;
  47582. var event = p.event;
  47583. var delta = 0;
  47584. if (event.wheelDelta) {
  47585. if (_this.wheelDeltaPercentage) {
  47586. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47587. if (event.wheelDelta > 0) {
  47588. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47589. }
  47590. else {
  47591. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47592. }
  47593. }
  47594. else {
  47595. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47596. }
  47597. }
  47598. else if (event.detail) {
  47599. delta = -event.detail / _this.wheelPrecision;
  47600. }
  47601. if (delta)
  47602. _this.camera.inertialRadiusOffset += delta;
  47603. if (event.preventDefault) {
  47604. if (!noPreventDefault) {
  47605. event.preventDefault();
  47606. }
  47607. }
  47608. };
  47609. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47610. };
  47611. /**
  47612. * Detach the current controls from the specified dom element.
  47613. * @param element Defines the element to stop listening the inputs from
  47614. */
  47615. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47616. if (this._observer && element) {
  47617. this.camera.getScene().onPointerObservable.remove(this._observer);
  47618. this._observer = null;
  47619. this._wheel = null;
  47620. }
  47621. };
  47622. /**
  47623. * Gets the class name of the current intput.
  47624. * @returns the class name
  47625. */
  47626. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47627. return "ArcRotateCameraMouseWheelInput";
  47628. };
  47629. /**
  47630. * Get the friendly name associated with the input class.
  47631. * @returns the input friendly name
  47632. */
  47633. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47634. return "mousewheel";
  47635. };
  47636. __decorate([
  47637. BABYLON.serialize()
  47638. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47639. __decorate([
  47640. BABYLON.serialize()
  47641. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47642. return ArcRotateCameraMouseWheelInput;
  47643. }());
  47644. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47645. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47646. })(BABYLON || (BABYLON = {}));
  47647. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47648. var BABYLON;
  47649. (function (BABYLON) {
  47650. /**
  47651. * Manage the pointers inputs to control an arc rotate camera.
  47652. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47653. */
  47654. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47655. function ArcRotateCameraPointersInput() {
  47656. /**
  47657. * Defines the buttons associated with the input to handle camera move.
  47658. */
  47659. this.buttons = [0, 1, 2];
  47660. /**
  47661. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47662. */
  47663. this.angularSensibilityX = 1000.0;
  47664. /**
  47665. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47666. */
  47667. this.angularSensibilityY = 1000.0;
  47668. /**
  47669. * Defines the pointer pinch precision or how fast is the camera zooming.
  47670. */
  47671. this.pinchPrecision = 12.0;
  47672. /**
  47673. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47674. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47675. */
  47676. this.pinchDeltaPercentage = 0;
  47677. /**
  47678. * Defines the pointer panning sensibility or how fast is the camera moving.
  47679. */
  47680. this.panningSensibility = 1000.0;
  47681. /**
  47682. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47683. */
  47684. this.multiTouchPanning = true;
  47685. /**
  47686. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47687. */
  47688. this.multiTouchPanAndZoom = true;
  47689. /**
  47690. * Revers pinch action direction.
  47691. */
  47692. this.pinchInwards = true;
  47693. this._isPanClick = false;
  47694. }
  47695. /**
  47696. * Attach the input controls to a specific dom element to get the input from.
  47697. * @param element Defines the element the controls should be listened from
  47698. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47699. */
  47700. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47701. var _this = this;
  47702. var engine = this.camera.getEngine();
  47703. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47704. var pointA = null;
  47705. var pointB = null;
  47706. var previousPinchSquaredDistance = 0;
  47707. var initialDistance = 0;
  47708. var twoFingerActivityCount = 0;
  47709. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47710. this._pointerInput = function (p, s) {
  47711. var evt = p.event;
  47712. var isTouch = p.event.pointerType === "touch";
  47713. if (engine.isInVRExclusivePointerMode) {
  47714. return;
  47715. }
  47716. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47717. return;
  47718. }
  47719. var srcElement = (evt.srcElement || evt.target);
  47720. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47721. try {
  47722. srcElement.setPointerCapture(evt.pointerId);
  47723. }
  47724. catch (e) {
  47725. //Nothing to do with the error. Execution will continue.
  47726. }
  47727. // Manage panning with pan button click
  47728. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47729. // manage pointers
  47730. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47731. if (pointA === null) {
  47732. pointA = cacheSoloPointer;
  47733. }
  47734. else if (pointB === null) {
  47735. pointB = cacheSoloPointer;
  47736. }
  47737. if (!noPreventDefault) {
  47738. evt.preventDefault();
  47739. element.focus();
  47740. }
  47741. }
  47742. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47743. if (_this.camera.useInputToRestoreState) {
  47744. _this.camera.restoreState();
  47745. }
  47746. }
  47747. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47748. try {
  47749. srcElement.releasePointerCapture(evt.pointerId);
  47750. }
  47751. catch (e) {
  47752. //Nothing to do with the error.
  47753. }
  47754. cacheSoloPointer = null;
  47755. previousPinchSquaredDistance = 0;
  47756. previousMultiTouchPanPosition.isPaning = false;
  47757. previousMultiTouchPanPosition.isPinching = false;
  47758. twoFingerActivityCount = 0;
  47759. initialDistance = 0;
  47760. if (!isTouch) {
  47761. pointB = null; // Mouse and pen are mono pointer
  47762. }
  47763. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47764. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47765. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47766. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47767. if (engine._badOS) {
  47768. pointA = pointB = null;
  47769. }
  47770. else {
  47771. //only remove the impacted pointer in case of multitouch allowing on most
  47772. //platforms switching from rotate to zoom and pan seamlessly.
  47773. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47774. pointA = pointB;
  47775. pointB = null;
  47776. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47777. }
  47778. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47779. pointB = null;
  47780. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47781. }
  47782. else {
  47783. pointA = pointB = null;
  47784. }
  47785. }
  47786. if (!noPreventDefault) {
  47787. evt.preventDefault();
  47788. }
  47789. }
  47790. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47791. if (!noPreventDefault) {
  47792. evt.preventDefault();
  47793. }
  47794. // One button down
  47795. if (pointA && pointB === null && cacheSoloPointer) {
  47796. if (_this.panningSensibility !== 0 &&
  47797. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47798. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47799. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47800. }
  47801. else {
  47802. var offsetX = evt.clientX - cacheSoloPointer.x;
  47803. var offsetY = evt.clientY - cacheSoloPointer.y;
  47804. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47805. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47806. }
  47807. cacheSoloPointer.x = evt.clientX;
  47808. cacheSoloPointer.y = evt.clientY;
  47809. }
  47810. // Two buttons down: pinch/pan
  47811. else if (pointA && pointB) {
  47812. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47813. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47814. ed.x = evt.clientX;
  47815. ed.y = evt.clientY;
  47816. var direction = _this.pinchInwards ? 1 : -1;
  47817. var distX = pointA.x - pointB.x;
  47818. var distY = pointA.y - pointB.y;
  47819. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47820. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47821. if (previousPinchSquaredDistance === 0) {
  47822. initialDistance = pinchDistance;
  47823. previousPinchSquaredDistance = pinchSquaredDistance;
  47824. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47825. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47826. return;
  47827. }
  47828. if (_this.multiTouchPanAndZoom) {
  47829. if (_this.pinchDeltaPercentage) {
  47830. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47831. }
  47832. else {
  47833. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47834. (_this.pinchPrecision *
  47835. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47836. direction);
  47837. }
  47838. if (_this.panningSensibility !== 0) {
  47839. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47840. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47841. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47842. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47843. previousMultiTouchPanPosition.x = pointersCenterX;
  47844. previousMultiTouchPanPosition.y = pointersCenterY;
  47845. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47846. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47847. }
  47848. }
  47849. else {
  47850. twoFingerActivityCount++;
  47851. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47852. if (_this.pinchDeltaPercentage) {
  47853. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47854. }
  47855. else {
  47856. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47857. (_this.pinchPrecision *
  47858. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47859. direction);
  47860. }
  47861. previousMultiTouchPanPosition.isPaning = false;
  47862. previousMultiTouchPanPosition.isPinching = true;
  47863. }
  47864. else {
  47865. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47866. if (!previousMultiTouchPanPosition.isPaning) {
  47867. previousMultiTouchPanPosition.isPaning = true;
  47868. previousMultiTouchPanPosition.isPinching = false;
  47869. previousMultiTouchPanPosition.x = ed.x;
  47870. previousMultiTouchPanPosition.y = ed.y;
  47871. return;
  47872. }
  47873. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47874. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47875. }
  47876. }
  47877. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47878. previousMultiTouchPanPosition.x = ed.x;
  47879. previousMultiTouchPanPosition.y = ed.y;
  47880. }
  47881. }
  47882. previousPinchSquaredDistance = pinchSquaredDistance;
  47883. }
  47884. }
  47885. };
  47886. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47887. this._onContextMenu = function (evt) {
  47888. evt.preventDefault();
  47889. };
  47890. if (!this.camera._useCtrlForPanning) {
  47891. element.addEventListener("contextmenu", this._onContextMenu, false);
  47892. }
  47893. this._onLostFocus = function () {
  47894. //this._keys = [];
  47895. pointA = pointB = null;
  47896. previousPinchSquaredDistance = 0;
  47897. previousMultiTouchPanPosition.isPaning = false;
  47898. previousMultiTouchPanPosition.isPinching = false;
  47899. twoFingerActivityCount = 0;
  47900. cacheSoloPointer = null;
  47901. initialDistance = 0;
  47902. };
  47903. this._onMouseMove = function (evt) {
  47904. if (!engine.isPointerLock) {
  47905. return;
  47906. }
  47907. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47908. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47909. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47910. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47911. if (!noPreventDefault) {
  47912. evt.preventDefault();
  47913. }
  47914. };
  47915. this._onGestureStart = function (e) {
  47916. if (window.MSGesture === undefined) {
  47917. return;
  47918. }
  47919. if (!_this._MSGestureHandler) {
  47920. _this._MSGestureHandler = new MSGesture();
  47921. _this._MSGestureHandler.target = element;
  47922. }
  47923. _this._MSGestureHandler.addPointer(e.pointerId);
  47924. };
  47925. this._onGesture = function (e) {
  47926. _this.camera.radius *= e.scale;
  47927. if (e.preventDefault) {
  47928. if (!noPreventDefault) {
  47929. e.stopPropagation();
  47930. e.preventDefault();
  47931. }
  47932. }
  47933. };
  47934. element.addEventListener("mousemove", this._onMouseMove, false);
  47935. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47936. element.addEventListener("MSGestureChange", this._onGesture, false);
  47937. BABYLON.Tools.RegisterTopRootEvents([
  47938. { name: "blur", handler: this._onLostFocus }
  47939. ]);
  47940. };
  47941. /**
  47942. * Detach the current controls from the specified dom element.
  47943. * @param element Defines the element to stop listening the inputs from
  47944. */
  47945. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47946. if (this._onLostFocus) {
  47947. BABYLON.Tools.UnregisterTopRootEvents([
  47948. { name: "blur", handler: this._onLostFocus }
  47949. ]);
  47950. }
  47951. if (element && this._observer) {
  47952. this.camera.getScene().onPointerObservable.remove(this._observer);
  47953. this._observer = null;
  47954. if (this._onContextMenu) {
  47955. element.removeEventListener("contextmenu", this._onContextMenu);
  47956. }
  47957. if (this._onMouseMove) {
  47958. element.removeEventListener("mousemove", this._onMouseMove);
  47959. }
  47960. if (this._onGestureStart) {
  47961. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47962. }
  47963. if (this._onGesture) {
  47964. element.removeEventListener("MSGestureChange", this._onGesture);
  47965. }
  47966. this._isPanClick = false;
  47967. this.pinchInwards = true;
  47968. this._onMouseMove = null;
  47969. this._onGestureStart = null;
  47970. this._onGesture = null;
  47971. this._MSGestureHandler = null;
  47972. this._onLostFocus = null;
  47973. this._onContextMenu = null;
  47974. }
  47975. };
  47976. /**
  47977. * Gets the class name of the current intput.
  47978. * @returns the class name
  47979. */
  47980. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47981. return "ArcRotateCameraPointersInput";
  47982. };
  47983. /**
  47984. * Get the friendly name associated with the input class.
  47985. * @returns the input friendly name
  47986. */
  47987. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47988. return "pointers";
  47989. };
  47990. __decorate([
  47991. BABYLON.serialize()
  47992. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47993. __decorate([
  47994. BABYLON.serialize()
  47995. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48002. __decorate([
  48003. BABYLON.serialize()
  48004. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48005. __decorate([
  48006. BABYLON.serialize()
  48007. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48008. __decorate([
  48009. BABYLON.serialize()
  48010. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48011. __decorate([
  48012. BABYLON.serialize()
  48013. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48014. return ArcRotateCameraPointersInput;
  48015. }());
  48016. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48017. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48018. })(BABYLON || (BABYLON = {}));
  48019. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48020. var BABYLON;
  48021. (function (BABYLON) {
  48022. /**
  48023. * Default Inputs manager for the ArcRotateCamera.
  48024. * It groups all the default supported inputs for ease of use.
  48025. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48026. */
  48027. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48028. __extends(ArcRotateCameraInputsManager, _super);
  48029. /**
  48030. * Instantiates a new ArcRotateCameraInputsManager.
  48031. * @param camera Defines the camera the inputs belong to
  48032. */
  48033. function ArcRotateCameraInputsManager(camera) {
  48034. return _super.call(this, camera) || this;
  48035. }
  48036. /**
  48037. * Add mouse wheel input support to the input manager.
  48038. * @returns the current input manager
  48039. */
  48040. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48041. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48042. return this;
  48043. };
  48044. /**
  48045. * Add pointers input support to the input manager.
  48046. * @returns the current input manager
  48047. */
  48048. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48049. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48050. return this;
  48051. };
  48052. /**
  48053. * Add keyboard input support to the input manager.
  48054. * @returns the current input manager
  48055. */
  48056. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48057. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48058. return this;
  48059. };
  48060. /**
  48061. * Add orientation input support to the input manager.
  48062. * @returns the current input manager
  48063. */
  48064. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48065. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48066. return this;
  48067. };
  48068. return ArcRotateCameraInputsManager;
  48069. }(BABYLON.CameraInputsManager));
  48070. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48071. })(BABYLON || (BABYLON = {}));
  48072. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48073. var BABYLON;
  48074. (function (BABYLON) {
  48075. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48076. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48077. });
  48078. /**
  48079. * This represents an orbital type of camera.
  48080. *
  48081. * 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.
  48082. * 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.
  48083. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48084. */
  48085. var ArcRotateCamera = /** @class */ (function (_super) {
  48086. __extends(ArcRotateCamera, _super);
  48087. /**
  48088. * Instantiates a new ArcRotateCamera in a given scene
  48089. * @param name Defines the name of the camera
  48090. * @param alpha Defines the camera rotation along the logitudinal axis
  48091. * @param beta Defines the camera rotation along the latitudinal axis
  48092. * @param radius Defines the camera distance from its target
  48093. * @param target Defines the camera target
  48094. * @param scene Defines the scene the camera belongs to
  48095. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48096. */
  48097. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48098. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48099. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48100. /**
  48101. * Current inertia value on the longitudinal axis.
  48102. * The bigger this number the longer it will take for the camera to stop.
  48103. */
  48104. _this.inertialAlphaOffset = 0;
  48105. /**
  48106. * Current inertia value on the latitudinal axis.
  48107. * The bigger this number the longer it will take for the camera to stop.
  48108. */
  48109. _this.inertialBetaOffset = 0;
  48110. /**
  48111. * Current inertia value on the radius axis.
  48112. * The bigger this number the longer it will take for the camera to stop.
  48113. */
  48114. _this.inertialRadiusOffset = 0;
  48115. /**
  48116. * Minimum allowed angle on the longitudinal axis.
  48117. * This can help limiting how the Camera is able to move in the scene.
  48118. */
  48119. _this.lowerAlphaLimit = null;
  48120. /**
  48121. * Maximum allowed angle on the longitudinal axis.
  48122. * This can help limiting how the Camera is able to move in the scene.
  48123. */
  48124. _this.upperAlphaLimit = null;
  48125. /**
  48126. * Minimum allowed angle on the latitudinal axis.
  48127. * This can help limiting how the Camera is able to move in the scene.
  48128. */
  48129. _this.lowerBetaLimit = 0.01;
  48130. /**
  48131. * Maximum allowed angle on the latitudinal axis.
  48132. * This can help limiting how the Camera is able to move in the scene.
  48133. */
  48134. _this.upperBetaLimit = Math.PI;
  48135. /**
  48136. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48137. * This can help limiting how the Camera is able to move in the scene.
  48138. */
  48139. _this.lowerRadiusLimit = null;
  48140. /**
  48141. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48142. * This can help limiting how the Camera is able to move in the scene.
  48143. */
  48144. _this.upperRadiusLimit = null;
  48145. /**
  48146. * Defines the current inertia value used during panning of the camera along the X axis.
  48147. */
  48148. _this.inertialPanningX = 0;
  48149. /**
  48150. * Defines the current inertia value used during panning of the camera along the Y axis.
  48151. */
  48152. _this.inertialPanningY = 0;
  48153. /**
  48154. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48155. * Basically if your fingers moves away from more than this distance you will be considered
  48156. * in pinch mode.
  48157. */
  48158. _this.pinchToPanMaxDistance = 20;
  48159. /**
  48160. * Defines the maximum distance the camera can pan.
  48161. * This could help keeping the cammera always in your scene.
  48162. */
  48163. _this.panningDistanceLimit = null;
  48164. /**
  48165. * Defines the target of the camera before paning.
  48166. */
  48167. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48168. /**
  48169. * Defines the value of the inertia used during panning.
  48170. * 0 would mean stop inertia and one would mean no decelleration at all.
  48171. */
  48172. _this.panningInertia = 0.9;
  48173. //-- end properties for backward compatibility for inputs
  48174. /**
  48175. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48176. */
  48177. _this.zoomOnFactor = 1;
  48178. /**
  48179. * Defines a screen offset for the camera position.
  48180. */
  48181. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48182. /**
  48183. * Allows the camera to be completely reversed.
  48184. * If false the camera can not arrive upside down.
  48185. */
  48186. _this.allowUpsideDown = true;
  48187. /**
  48188. * Define if double tap/click is used to restore the previously saved state of the camera.
  48189. */
  48190. _this.useInputToRestoreState = true;
  48191. /** @hidden */
  48192. _this._viewMatrix = new BABYLON.Matrix();
  48193. /**
  48194. * Defines the allowed panning axis.
  48195. */
  48196. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48197. /**
  48198. * Observable triggered when the mesh target has been changed on the camera.
  48199. */
  48200. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48201. /**
  48202. * Defines whether the camera should check collision with the objects oh the scene.
  48203. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48204. */
  48205. _this.checkCollisions = false;
  48206. /**
  48207. * Defines the collision radius of the camera.
  48208. * This simulates a sphere around the camera.
  48209. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48210. */
  48211. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48212. _this._previousPosition = BABYLON.Vector3.Zero();
  48213. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48214. _this._newPosition = BABYLON.Vector3.Zero();
  48215. _this._computationVector = BABYLON.Vector3.Zero();
  48216. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48217. if (collidedMesh === void 0) { collidedMesh = null; }
  48218. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48219. newPosition.multiplyInPlace(_this._collider._radius);
  48220. }
  48221. if (!collidedMesh) {
  48222. _this._previousPosition.copyFrom(_this.position);
  48223. }
  48224. else {
  48225. _this.setPosition(newPosition);
  48226. if (_this.onCollide) {
  48227. _this.onCollide(collidedMesh);
  48228. }
  48229. }
  48230. // Recompute because of constraints
  48231. var cosa = Math.cos(_this.alpha);
  48232. var sina = Math.sin(_this.alpha);
  48233. var cosb = Math.cos(_this.beta);
  48234. var sinb = Math.sin(_this.beta);
  48235. if (sinb === 0) {
  48236. sinb = 0.0001;
  48237. }
  48238. var target = _this._getTargetPosition();
  48239. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48240. target.addToRef(_this._computationVector, _this._newPosition);
  48241. _this.position.copyFrom(_this._newPosition);
  48242. var up = _this.upVector;
  48243. if (_this.allowUpsideDown && _this.beta < 0) {
  48244. up = up.clone();
  48245. up = up.negate();
  48246. }
  48247. _this._computeViewMatrix(_this.position, target, up);
  48248. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48249. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48250. _this._collisionTriggered = false;
  48251. };
  48252. _this._target = BABYLON.Vector3.Zero();
  48253. if (target) {
  48254. _this.setTarget(target);
  48255. }
  48256. _this.alpha = alpha;
  48257. _this.beta = beta;
  48258. _this.radius = radius;
  48259. _this.getViewMatrix();
  48260. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48261. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48262. return _this;
  48263. }
  48264. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48265. /**
  48266. * Defines the target point of the camera.
  48267. * The camera looks towards it form the radius distance.
  48268. */
  48269. get: function () {
  48270. return this._target;
  48271. },
  48272. set: function (value) {
  48273. this.setTarget(value);
  48274. },
  48275. enumerable: true,
  48276. configurable: true
  48277. });
  48278. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48279. //-- begin properties for backward compatibility for inputs
  48280. /**
  48281. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48282. */
  48283. get: function () {
  48284. var pointers = this.inputs.attached["pointers"];
  48285. if (pointers)
  48286. return pointers.angularSensibilityX;
  48287. return 0;
  48288. },
  48289. set: function (value) {
  48290. var pointers = this.inputs.attached["pointers"];
  48291. if (pointers) {
  48292. pointers.angularSensibilityX = value;
  48293. }
  48294. },
  48295. enumerable: true,
  48296. configurable: true
  48297. });
  48298. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48299. /**
  48300. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48301. */
  48302. get: function () {
  48303. var pointers = this.inputs.attached["pointers"];
  48304. if (pointers)
  48305. return pointers.angularSensibilityY;
  48306. return 0;
  48307. },
  48308. set: function (value) {
  48309. var pointers = this.inputs.attached["pointers"];
  48310. if (pointers) {
  48311. pointers.angularSensibilityY = value;
  48312. }
  48313. },
  48314. enumerable: true,
  48315. configurable: true
  48316. });
  48317. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48318. /**
  48319. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48320. */
  48321. get: function () {
  48322. var pointers = this.inputs.attached["pointers"];
  48323. if (pointers)
  48324. return pointers.pinchPrecision;
  48325. return 0;
  48326. },
  48327. set: function (value) {
  48328. var pointers = this.inputs.attached["pointers"];
  48329. if (pointers) {
  48330. pointers.pinchPrecision = value;
  48331. }
  48332. },
  48333. enumerable: true,
  48334. configurable: true
  48335. });
  48336. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48337. /**
  48338. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48339. * It will be used instead of pinchDeltaPrecision if different from 0.
  48340. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48341. */
  48342. get: function () {
  48343. var pointers = this.inputs.attached["pointers"];
  48344. if (pointers)
  48345. return pointers.pinchDeltaPercentage;
  48346. return 0;
  48347. },
  48348. set: function (value) {
  48349. var pointers = this.inputs.attached["pointers"];
  48350. if (pointers) {
  48351. pointers.pinchDeltaPercentage = value;
  48352. }
  48353. },
  48354. enumerable: true,
  48355. configurable: true
  48356. });
  48357. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48358. /**
  48359. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48360. */
  48361. get: function () {
  48362. var pointers = this.inputs.attached["pointers"];
  48363. if (pointers)
  48364. return pointers.panningSensibility;
  48365. return 0;
  48366. },
  48367. set: function (value) {
  48368. var pointers = this.inputs.attached["pointers"];
  48369. if (pointers) {
  48370. pointers.panningSensibility = value;
  48371. }
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48377. /**
  48378. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48379. */
  48380. get: function () {
  48381. var keyboard = this.inputs.attached["keyboard"];
  48382. if (keyboard)
  48383. return keyboard.keysUp;
  48384. return [];
  48385. },
  48386. set: function (value) {
  48387. var keyboard = this.inputs.attached["keyboard"];
  48388. if (keyboard)
  48389. keyboard.keysUp = value;
  48390. },
  48391. enumerable: true,
  48392. configurable: true
  48393. });
  48394. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48395. /**
  48396. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48397. */
  48398. get: function () {
  48399. var keyboard = this.inputs.attached["keyboard"];
  48400. if (keyboard)
  48401. return keyboard.keysDown;
  48402. return [];
  48403. },
  48404. set: function (value) {
  48405. var keyboard = this.inputs.attached["keyboard"];
  48406. if (keyboard)
  48407. keyboard.keysDown = value;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48413. /**
  48414. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48415. */
  48416. get: function () {
  48417. var keyboard = this.inputs.attached["keyboard"];
  48418. if (keyboard)
  48419. return keyboard.keysLeft;
  48420. return [];
  48421. },
  48422. set: function (value) {
  48423. var keyboard = this.inputs.attached["keyboard"];
  48424. if (keyboard)
  48425. keyboard.keysLeft = value;
  48426. },
  48427. enumerable: true,
  48428. configurable: true
  48429. });
  48430. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48431. /**
  48432. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48433. */
  48434. get: function () {
  48435. var keyboard = this.inputs.attached["keyboard"];
  48436. if (keyboard)
  48437. return keyboard.keysRight;
  48438. return [];
  48439. },
  48440. set: function (value) {
  48441. var keyboard = this.inputs.attached["keyboard"];
  48442. if (keyboard)
  48443. keyboard.keysRight = value;
  48444. },
  48445. enumerable: true,
  48446. configurable: true
  48447. });
  48448. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48449. /**
  48450. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48451. */
  48452. get: function () {
  48453. var mousewheel = this.inputs.attached["mousewheel"];
  48454. if (mousewheel)
  48455. return mousewheel.wheelPrecision;
  48456. return 0;
  48457. },
  48458. set: function (value) {
  48459. var mousewheel = this.inputs.attached["mousewheel"];
  48460. if (mousewheel)
  48461. mousewheel.wheelPrecision = value;
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48467. /**
  48468. * Gets or Set the mouse wheel 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 mousewheel = this.inputs.attached["mousewheel"];
  48474. if (mousewheel)
  48475. return mousewheel.wheelDeltaPercentage;
  48476. return 0;
  48477. },
  48478. set: function (value) {
  48479. var mousewheel = this.inputs.attached["mousewheel"];
  48480. if (mousewheel)
  48481. mousewheel.wheelDeltaPercentage = value;
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48487. /**
  48488. * Gets the bouncing behavior of the camera if it has been enabled.
  48489. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48490. */
  48491. get: function () {
  48492. return this._bouncingBehavior;
  48493. },
  48494. enumerable: true,
  48495. configurable: true
  48496. });
  48497. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48498. /**
  48499. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48500. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48501. */
  48502. get: function () {
  48503. return this._bouncingBehavior != null;
  48504. },
  48505. set: function (value) {
  48506. if (value === this.useBouncingBehavior) {
  48507. return;
  48508. }
  48509. if (value) {
  48510. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48511. this.addBehavior(this._bouncingBehavior);
  48512. }
  48513. else if (this._bouncingBehavior) {
  48514. this.removeBehavior(this._bouncingBehavior);
  48515. this._bouncingBehavior = null;
  48516. }
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48522. /**
  48523. * Gets the framing behavior of the camera if it has been enabled.
  48524. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48525. */
  48526. get: function () {
  48527. return this._framingBehavior;
  48528. },
  48529. enumerable: true,
  48530. configurable: true
  48531. });
  48532. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48533. /**
  48534. * Defines if the framing behavior of the camera is enabled on the camera.
  48535. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48536. */
  48537. get: function () {
  48538. return this._framingBehavior != null;
  48539. },
  48540. set: function (value) {
  48541. if (value === this.useFramingBehavior) {
  48542. return;
  48543. }
  48544. if (value) {
  48545. this._framingBehavior = new BABYLON.FramingBehavior();
  48546. this.addBehavior(this._framingBehavior);
  48547. }
  48548. else if (this._framingBehavior) {
  48549. this.removeBehavior(this._framingBehavior);
  48550. this._framingBehavior = null;
  48551. }
  48552. },
  48553. enumerable: true,
  48554. configurable: true
  48555. });
  48556. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48557. /**
  48558. * Gets the auto rotation behavior of the camera if it has been enabled.
  48559. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48560. */
  48561. get: function () {
  48562. return this._autoRotationBehavior;
  48563. },
  48564. enumerable: true,
  48565. configurable: true
  48566. });
  48567. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48568. /**
  48569. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48570. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48571. */
  48572. get: function () {
  48573. return this._autoRotationBehavior != null;
  48574. },
  48575. set: function (value) {
  48576. if (value === this.useAutoRotationBehavior) {
  48577. return;
  48578. }
  48579. if (value) {
  48580. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48581. this.addBehavior(this._autoRotationBehavior);
  48582. }
  48583. else if (this._autoRotationBehavior) {
  48584. this.removeBehavior(this._autoRotationBehavior);
  48585. this._autoRotationBehavior = null;
  48586. }
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. // Cache
  48592. /** @hidden */
  48593. ArcRotateCamera.prototype._initCache = function () {
  48594. _super.prototype._initCache.call(this);
  48595. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48596. this._cache.alpha = undefined;
  48597. this._cache.beta = undefined;
  48598. this._cache.radius = undefined;
  48599. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48600. };
  48601. /** @hidden */
  48602. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48603. if (!ignoreParentClass) {
  48604. _super.prototype._updateCache.call(this);
  48605. }
  48606. this._cache._target.copyFrom(this._getTargetPosition());
  48607. this._cache.alpha = this.alpha;
  48608. this._cache.beta = this.beta;
  48609. this._cache.radius = this.radius;
  48610. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48611. };
  48612. ArcRotateCamera.prototype._getTargetPosition = function () {
  48613. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48614. var pos = this._targetHost.getAbsolutePosition();
  48615. if (this._targetBoundingCenter) {
  48616. pos.addToRef(this._targetBoundingCenter, this._target);
  48617. }
  48618. else {
  48619. this._target.copyFrom(pos);
  48620. }
  48621. }
  48622. var lockedTargetPosition = this._getLockedTargetPosition();
  48623. if (lockedTargetPosition) {
  48624. return lockedTargetPosition;
  48625. }
  48626. return this._target;
  48627. };
  48628. /**
  48629. * Stores the current state of the camera (alpha, beta, radius and target)
  48630. * @returns the camera itself
  48631. */
  48632. ArcRotateCamera.prototype.storeState = function () {
  48633. this._storedAlpha = this.alpha;
  48634. this._storedBeta = this.beta;
  48635. this._storedRadius = this.radius;
  48636. this._storedTarget = this._getTargetPosition().clone();
  48637. return _super.prototype.storeState.call(this);
  48638. };
  48639. /**
  48640. * @hidden
  48641. * Restored camera state. You must call storeState() first
  48642. */
  48643. ArcRotateCamera.prototype._restoreStateValues = function () {
  48644. if (!_super.prototype._restoreStateValues.call(this)) {
  48645. return false;
  48646. }
  48647. this.alpha = this._storedAlpha;
  48648. this.beta = this._storedBeta;
  48649. this.radius = this._storedRadius;
  48650. this.setTarget(this._storedTarget.clone());
  48651. this.inertialAlphaOffset = 0;
  48652. this.inertialBetaOffset = 0;
  48653. this.inertialRadiusOffset = 0;
  48654. this.inertialPanningX = 0;
  48655. this.inertialPanningY = 0;
  48656. return true;
  48657. };
  48658. // Synchronized
  48659. /** @hidden */
  48660. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48661. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48662. return false;
  48663. return this._cache._target.equals(this._getTargetPosition())
  48664. && this._cache.alpha === this.alpha
  48665. && this._cache.beta === this.beta
  48666. && this._cache.radius === this.radius
  48667. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48668. };
  48669. /**
  48670. * Attached controls to the current camera.
  48671. * @param element Defines the element the controls should be listened from
  48672. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48673. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48674. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48675. */
  48676. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48677. var _this = this;
  48678. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48679. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48680. this._useCtrlForPanning = useCtrlForPanning;
  48681. this._panningMouseButton = panningMouseButton;
  48682. this.inputs.attachElement(element, noPreventDefault);
  48683. this._reset = function () {
  48684. _this.inertialAlphaOffset = 0;
  48685. _this.inertialBetaOffset = 0;
  48686. _this.inertialRadiusOffset = 0;
  48687. _this.inertialPanningX = 0;
  48688. _this.inertialPanningY = 0;
  48689. };
  48690. };
  48691. /**
  48692. * Detach the current controls from the camera.
  48693. * The camera will stop reacting to inputs.
  48694. * @param element Defines the element to stop listening the inputs from
  48695. */
  48696. ArcRotateCamera.prototype.detachControl = function (element) {
  48697. this.inputs.detachElement(element);
  48698. if (this._reset) {
  48699. this._reset();
  48700. }
  48701. };
  48702. /** @hidden */
  48703. ArcRotateCamera.prototype._checkInputs = function () {
  48704. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48705. if (this._collisionTriggered) {
  48706. return;
  48707. }
  48708. this.inputs.checkInputs();
  48709. // Inertia
  48710. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48711. var inertialAlphaOffset = this.inertialAlphaOffset;
  48712. if (this.beta <= 0)
  48713. inertialAlphaOffset *= -1;
  48714. if (this.getScene().useRightHandedSystem)
  48715. inertialAlphaOffset *= -1;
  48716. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48717. inertialAlphaOffset *= -1;
  48718. this.alpha += inertialAlphaOffset;
  48719. this.beta += this.inertialBetaOffset;
  48720. this.radius -= this.inertialRadiusOffset;
  48721. this.inertialAlphaOffset *= this.inertia;
  48722. this.inertialBetaOffset *= this.inertia;
  48723. this.inertialRadiusOffset *= this.inertia;
  48724. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48725. this.inertialAlphaOffset = 0;
  48726. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48727. this.inertialBetaOffset = 0;
  48728. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48729. this.inertialRadiusOffset = 0;
  48730. }
  48731. // Panning inertia
  48732. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48733. if (!this._localDirection) {
  48734. this._localDirection = BABYLON.Vector3.Zero();
  48735. this._transformedDirection = BABYLON.Vector3.Zero();
  48736. }
  48737. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48738. this._localDirection.multiplyInPlace(this.panningAxis);
  48739. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48740. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48741. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48742. if (!this.panningAxis.y) {
  48743. this._transformedDirection.y = 0;
  48744. }
  48745. if (!this._targetHost) {
  48746. if (this.panningDistanceLimit) {
  48747. this._transformedDirection.addInPlace(this._target);
  48748. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48749. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48750. this._target.copyFrom(this._transformedDirection);
  48751. }
  48752. }
  48753. else {
  48754. this._target.addInPlace(this._transformedDirection);
  48755. }
  48756. }
  48757. this.inertialPanningX *= this.panningInertia;
  48758. this.inertialPanningY *= this.panningInertia;
  48759. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48760. this.inertialPanningX = 0;
  48761. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48762. this.inertialPanningY = 0;
  48763. }
  48764. // Limits
  48765. this._checkLimits();
  48766. _super.prototype._checkInputs.call(this);
  48767. };
  48768. ArcRotateCamera.prototype._checkLimits = function () {
  48769. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48770. if (this.allowUpsideDown && this.beta > Math.PI) {
  48771. this.beta = this.beta - (2 * Math.PI);
  48772. }
  48773. }
  48774. else {
  48775. if (this.beta < this.lowerBetaLimit) {
  48776. this.beta = this.lowerBetaLimit;
  48777. }
  48778. }
  48779. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48780. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48781. this.beta = this.beta + (2 * Math.PI);
  48782. }
  48783. }
  48784. else {
  48785. if (this.beta > this.upperBetaLimit) {
  48786. this.beta = this.upperBetaLimit;
  48787. }
  48788. }
  48789. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48790. this.alpha = this.lowerAlphaLimit;
  48791. }
  48792. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48793. this.alpha = this.upperAlphaLimit;
  48794. }
  48795. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48796. this.radius = this.lowerRadiusLimit;
  48797. }
  48798. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48799. this.radius = this.upperRadiusLimit;
  48800. }
  48801. };
  48802. /**
  48803. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48804. */
  48805. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48806. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48807. this.radius = this._computationVector.length();
  48808. if (this.radius === 0) {
  48809. this.radius = 0.0001; // Just to avoid division by zero
  48810. }
  48811. // Alpha
  48812. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48813. if (this._computationVector.z < 0) {
  48814. this.alpha = 2 * Math.PI - this.alpha;
  48815. }
  48816. // Beta
  48817. this.beta = Math.acos(this._computationVector.y / this.radius);
  48818. this._checkLimits();
  48819. };
  48820. /**
  48821. * Use a position to define the current camera related information like aplha, beta and radius
  48822. * @param position Defines the position to set the camera at
  48823. */
  48824. ArcRotateCamera.prototype.setPosition = function (position) {
  48825. if (this.position.equals(position)) {
  48826. return;
  48827. }
  48828. this.position.copyFrom(position);
  48829. this.rebuildAnglesAndRadius();
  48830. };
  48831. /**
  48832. * Defines the target the camera should look at.
  48833. * This will automatically adapt alpha beta and radius to fit within the new target.
  48834. * @param target Defines the new target as a Vector or a mesh
  48835. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48836. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48837. */
  48838. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48839. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48840. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48841. if (target.getBoundingInfo) {
  48842. if (toBoundingCenter) {
  48843. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48844. }
  48845. else {
  48846. this._targetBoundingCenter = null;
  48847. }
  48848. this._targetHost = target;
  48849. this._target = this._getTargetPosition();
  48850. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48851. }
  48852. else {
  48853. var newTarget = target;
  48854. var currentTarget = this._getTargetPosition();
  48855. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48856. return;
  48857. }
  48858. this._targetHost = null;
  48859. this._target = newTarget;
  48860. this._targetBoundingCenter = null;
  48861. this.onMeshTargetChangedObservable.notifyObservers(null);
  48862. }
  48863. this.rebuildAnglesAndRadius();
  48864. };
  48865. /** @hidden */
  48866. ArcRotateCamera.prototype._getViewMatrix = function () {
  48867. // Compute
  48868. var cosa = Math.cos(this.alpha);
  48869. var sina = Math.sin(this.alpha);
  48870. var cosb = Math.cos(this.beta);
  48871. var sinb = Math.sin(this.beta);
  48872. if (sinb === 0) {
  48873. sinb = 0.0001;
  48874. }
  48875. var target = this._getTargetPosition();
  48876. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48877. target.addToRef(this._computationVector, this._newPosition);
  48878. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48879. if (!this._collider) {
  48880. this._collider = new BABYLON.Collider();
  48881. }
  48882. this._collider._radius = this.collisionRadius;
  48883. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48884. this._collisionTriggered = true;
  48885. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48886. }
  48887. else {
  48888. this.position.copyFrom(this._newPosition);
  48889. var up = this.upVector;
  48890. if (this.allowUpsideDown && sinb < 0) {
  48891. up = up.clone();
  48892. up = up.negate();
  48893. }
  48894. this._computeViewMatrix(this.position, target, up);
  48895. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48896. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48897. }
  48898. this._currentTarget = target;
  48899. return this._viewMatrix;
  48900. };
  48901. /**
  48902. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48903. * @param meshes Defines the mesh to zoom on
  48904. * @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)
  48905. */
  48906. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48907. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48908. meshes = meshes || this.getScene().meshes;
  48909. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48910. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48911. this.radius = distance * this.zoomOnFactor;
  48912. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48913. };
  48914. /**
  48915. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48916. * The target will be changed but the radius
  48917. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48918. * @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)
  48919. */
  48920. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48921. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48922. var meshesOrMinMaxVector;
  48923. var distance;
  48924. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48925. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48926. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48927. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48928. }
  48929. else { //minMaxVector and distance
  48930. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48931. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48932. distance = minMaxVectorAndDistance.distance;
  48933. }
  48934. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48935. if (!doNotUpdateMaxZ) {
  48936. this.maxZ = distance * 2;
  48937. }
  48938. };
  48939. /**
  48940. * @override
  48941. * Override Camera.createRigCamera
  48942. */
  48943. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48944. var alphaShift = 0;
  48945. switch (this.cameraRigMode) {
  48946. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48947. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48948. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48949. case BABYLON.Camera.RIG_MODE_VR:
  48950. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48951. break;
  48952. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48953. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48954. break;
  48955. }
  48956. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48957. rigCam._cameraRigParams = {};
  48958. return rigCam;
  48959. };
  48960. /**
  48961. * @hidden
  48962. * @override
  48963. * Override Camera._updateRigCameras
  48964. */
  48965. ArcRotateCamera.prototype._updateRigCameras = function () {
  48966. var camLeft = this._rigCameras[0];
  48967. var camRight = this._rigCameras[1];
  48968. camLeft.beta = camRight.beta = this.beta;
  48969. camLeft.radius = camRight.radius = this.radius;
  48970. switch (this.cameraRigMode) {
  48971. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48972. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48974. case BABYLON.Camera.RIG_MODE_VR:
  48975. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48976. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48977. break;
  48978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48979. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48980. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48981. break;
  48982. }
  48983. _super.prototype._updateRigCameras.call(this);
  48984. };
  48985. /**
  48986. * Destroy the camera and release the current resources hold by it.
  48987. */
  48988. ArcRotateCamera.prototype.dispose = function () {
  48989. this.inputs.clear();
  48990. _super.prototype.dispose.call(this);
  48991. };
  48992. /**
  48993. * Gets the current object class name.
  48994. * @return the class name
  48995. */
  48996. ArcRotateCamera.prototype.getClassName = function () {
  48997. return "ArcRotateCamera";
  48998. };
  48999. __decorate([
  49000. BABYLON.serialize()
  49001. ], ArcRotateCamera.prototype, "alpha", void 0);
  49002. __decorate([
  49003. BABYLON.serialize()
  49004. ], ArcRotateCamera.prototype, "beta", void 0);
  49005. __decorate([
  49006. BABYLON.serialize()
  49007. ], ArcRotateCamera.prototype, "radius", void 0);
  49008. __decorate([
  49009. BABYLON.serializeAsVector3("target")
  49010. ], ArcRotateCamera.prototype, "_target", void 0);
  49011. __decorate([
  49012. BABYLON.serialize()
  49013. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49014. __decorate([
  49015. BABYLON.serialize()
  49016. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49017. __decorate([
  49018. BABYLON.serialize()
  49019. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49020. __decorate([
  49021. BABYLON.serialize()
  49022. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49023. __decorate([
  49024. BABYLON.serialize()
  49025. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49026. __decorate([
  49027. BABYLON.serialize()
  49028. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49029. __decorate([
  49030. BABYLON.serialize()
  49031. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49032. __decorate([
  49033. BABYLON.serialize()
  49034. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49035. __decorate([
  49036. BABYLON.serialize()
  49037. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49038. __decorate([
  49039. BABYLON.serialize()
  49040. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49041. __decorate([
  49042. BABYLON.serialize()
  49043. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49044. __decorate([
  49045. BABYLON.serialize()
  49046. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49047. __decorate([
  49048. BABYLON.serialize()
  49049. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49050. __decorate([
  49051. BABYLON.serializeAsVector3()
  49052. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49053. __decorate([
  49054. BABYLON.serialize()
  49055. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49065. __decorate([
  49066. BABYLON.serialize()
  49067. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49068. return ArcRotateCamera;
  49069. }(BABYLON.TargetCamera));
  49070. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49071. })(BABYLON || (BABYLON = {}));
  49072. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49073. var BABYLON;
  49074. (function (BABYLON) {
  49075. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49076. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49077. });
  49078. /**
  49079. * The HemisphericLight simulates the ambient environment light,
  49080. * so the passed direction is the light reflection direction, not the incoming direction.
  49081. */
  49082. var HemisphericLight = /** @class */ (function (_super) {
  49083. __extends(HemisphericLight, _super);
  49084. /**
  49085. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49086. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49087. * The HemisphericLight can't cast shadows.
  49088. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49089. * @param name The friendly name of the light
  49090. * @param direction The direction of the light reflection
  49091. * @param scene The scene the light belongs to
  49092. */
  49093. function HemisphericLight(name, direction, scene) {
  49094. var _this = _super.call(this, name, scene) || this;
  49095. /**
  49096. * The groundColor is the light in the opposite direction to the one specified during creation.
  49097. * 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.
  49098. */
  49099. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49100. _this.direction = direction || BABYLON.Vector3.Up();
  49101. return _this;
  49102. }
  49103. HemisphericLight.prototype._buildUniformLayout = function () {
  49104. this._uniformBuffer.addUniform("vLightData", 4);
  49105. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49106. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49107. this._uniformBuffer.addUniform("vLightGround", 3);
  49108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49109. this._uniformBuffer.addUniform("depthValues", 2);
  49110. this._uniformBuffer.create();
  49111. };
  49112. /**
  49113. * Returns the string "HemisphericLight".
  49114. * @return The class name
  49115. */
  49116. HemisphericLight.prototype.getClassName = function () {
  49117. return "HemisphericLight";
  49118. };
  49119. /**
  49120. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49121. * Returns the updated direction.
  49122. * @param target The target the direction should point to
  49123. * @return The computed direction
  49124. */
  49125. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49126. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49127. return this.direction;
  49128. };
  49129. /**
  49130. * Returns the shadow generator associated to the light.
  49131. * @returns Always null for hemispheric lights because it does not support shadows.
  49132. */
  49133. HemisphericLight.prototype.getShadowGenerator = function () {
  49134. return null;
  49135. };
  49136. /**
  49137. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49138. * @param effect The effect to update
  49139. * @param lightIndex The index of the light in the effect to update
  49140. * @returns The hemispheric light
  49141. */
  49142. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49143. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49144. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49145. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49146. return this;
  49147. };
  49148. /**
  49149. * Computes the world matrix of the node
  49150. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49151. * @param useWasUpdatedFlag defines a reserved property
  49152. * @returns the world matrix
  49153. */
  49154. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49155. if (!this._worldMatrix) {
  49156. this._worldMatrix = BABYLON.Matrix.Identity();
  49157. }
  49158. return this._worldMatrix;
  49159. };
  49160. /**
  49161. * Returns the integer 3.
  49162. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49163. */
  49164. HemisphericLight.prototype.getTypeID = function () {
  49165. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49166. };
  49167. /**
  49168. * Prepares the list of defines specific to the light type.
  49169. * @param defines the list of defines
  49170. * @param lightIndex defines the index of the light for the effect
  49171. */
  49172. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49173. defines["HEMILIGHT" + lightIndex] = true;
  49174. };
  49175. __decorate([
  49176. BABYLON.serializeAsColor3()
  49177. ], HemisphericLight.prototype, "groundColor", void 0);
  49178. __decorate([
  49179. BABYLON.serializeAsVector3()
  49180. ], HemisphericLight.prototype, "direction", void 0);
  49181. return HemisphericLight;
  49182. }(BABYLON.Light));
  49183. BABYLON.HemisphericLight = HemisphericLight;
  49184. })(BABYLON || (BABYLON = {}));
  49185. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49186. var BABYLON;
  49187. (function (BABYLON) {
  49188. /**
  49189. * Base implementation IShadowLight
  49190. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49191. */
  49192. var ShadowLight = /** @class */ (function (_super) {
  49193. __extends(ShadowLight, _super);
  49194. function ShadowLight() {
  49195. var _this = _super !== null && _super.apply(this, arguments) || this;
  49196. _this._needProjectionMatrixCompute = true;
  49197. return _this;
  49198. }
  49199. ShadowLight.prototype._setPosition = function (value) {
  49200. this._position = value;
  49201. };
  49202. Object.defineProperty(ShadowLight.prototype, "position", {
  49203. /**
  49204. * Sets the position the shadow will be casted from. Also use as the light position for both
  49205. * point and spot lights.
  49206. */
  49207. get: function () {
  49208. return this._position;
  49209. },
  49210. /**
  49211. * Sets the position the shadow will be casted from. Also use as the light position for both
  49212. * point and spot lights.
  49213. */
  49214. set: function (value) {
  49215. this._setPosition(value);
  49216. },
  49217. enumerable: true,
  49218. configurable: true
  49219. });
  49220. ShadowLight.prototype._setDirection = function (value) {
  49221. this._direction = value;
  49222. };
  49223. Object.defineProperty(ShadowLight.prototype, "direction", {
  49224. /**
  49225. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49226. * Also use as the light direction on spot and directional lights.
  49227. */
  49228. get: function () {
  49229. return this._direction;
  49230. },
  49231. /**
  49232. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49233. * Also use as the light direction on spot and directional lights.
  49234. */
  49235. set: function (value) {
  49236. this._setDirection(value);
  49237. },
  49238. enumerable: true,
  49239. configurable: true
  49240. });
  49241. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49242. /**
  49243. * Gets the shadow projection clipping minimum z value.
  49244. */
  49245. get: function () {
  49246. return this._shadowMinZ;
  49247. },
  49248. /**
  49249. * Sets the shadow projection clipping minimum z value.
  49250. */
  49251. set: function (value) {
  49252. this._shadowMinZ = value;
  49253. this.forceProjectionMatrixCompute();
  49254. },
  49255. enumerable: true,
  49256. configurable: true
  49257. });
  49258. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49259. /**
  49260. * Sets the shadow projection clipping maximum z value.
  49261. */
  49262. get: function () {
  49263. return this._shadowMaxZ;
  49264. },
  49265. /**
  49266. * Gets the shadow projection clipping maximum z value.
  49267. */
  49268. set: function (value) {
  49269. this._shadowMaxZ = value;
  49270. this.forceProjectionMatrixCompute();
  49271. },
  49272. enumerable: true,
  49273. configurable: true
  49274. });
  49275. /**
  49276. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49277. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49278. */
  49279. ShadowLight.prototype.computeTransformedInformation = function () {
  49280. if (this.parent && this.parent.getWorldMatrix) {
  49281. if (!this.transformedPosition) {
  49282. this.transformedPosition = BABYLON.Vector3.Zero();
  49283. }
  49284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49285. // In case the direction is present.
  49286. if (this.direction) {
  49287. if (!this.transformedDirection) {
  49288. this.transformedDirection = BABYLON.Vector3.Zero();
  49289. }
  49290. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49291. }
  49292. return true;
  49293. }
  49294. return false;
  49295. };
  49296. /**
  49297. * Return the depth scale used for the shadow map.
  49298. * @returns the depth scale.
  49299. */
  49300. ShadowLight.prototype.getDepthScale = function () {
  49301. return 50.0;
  49302. };
  49303. /**
  49304. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49305. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49306. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49307. */
  49308. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49309. return this.transformedDirection ? this.transformedDirection : this.direction;
  49310. };
  49311. /**
  49312. * Returns the ShadowLight absolute position in the World.
  49313. * @returns the position vector in world space
  49314. */
  49315. ShadowLight.prototype.getAbsolutePosition = function () {
  49316. return this.transformedPosition ? this.transformedPosition : this.position;
  49317. };
  49318. /**
  49319. * Sets the ShadowLight direction toward the passed target.
  49320. * @param target The point tot target in local space
  49321. * @returns the updated ShadowLight direction
  49322. */
  49323. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49324. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49325. return this.direction;
  49326. };
  49327. /**
  49328. * Returns the light rotation in euler definition.
  49329. * @returns the x y z rotation in local space.
  49330. */
  49331. ShadowLight.prototype.getRotation = function () {
  49332. this.direction.normalize();
  49333. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49334. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49335. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49336. };
  49337. /**
  49338. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49339. * @returns true if a cube texture needs to be use
  49340. */
  49341. ShadowLight.prototype.needCube = function () {
  49342. return false;
  49343. };
  49344. /**
  49345. * Detects if the projection matrix requires to be recomputed this frame.
  49346. * @returns true if it requires to be recomputed otherwise, false.
  49347. */
  49348. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49349. return this._needProjectionMatrixCompute;
  49350. };
  49351. /**
  49352. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49353. */
  49354. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49355. this._needProjectionMatrixCompute = true;
  49356. };
  49357. /** @hidden */
  49358. ShadowLight.prototype._initCache = function () {
  49359. _super.prototype._initCache.call(this);
  49360. this._cache.position = BABYLON.Vector3.Zero();
  49361. };
  49362. /** @hidden */
  49363. ShadowLight.prototype._isSynchronized = function () {
  49364. if (!this._cache.position.equals(this.position))
  49365. return false;
  49366. return true;
  49367. };
  49368. /**
  49369. * Computes the world matrix of the node
  49370. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49371. * @returns the world matrix
  49372. */
  49373. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49374. if (!force && this.isSynchronized()) {
  49375. this._currentRenderId = this.getScene().getRenderId();
  49376. return this._worldMatrix;
  49377. }
  49378. this._updateCache();
  49379. this._cache.position.copyFrom(this.position);
  49380. if (!this._worldMatrix) {
  49381. this._worldMatrix = BABYLON.Matrix.Identity();
  49382. }
  49383. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49384. if (this.parent && this.parent.getWorldMatrix) {
  49385. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49386. this._markSyncedWithParent();
  49387. }
  49388. // Cache the determinant
  49389. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49390. return this._worldMatrix;
  49391. };
  49392. /**
  49393. * Gets the minZ used for shadow according to both the scene and the light.
  49394. * @param activeCamera The camera we are returning the min for
  49395. * @returns the depth min z
  49396. */
  49397. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49398. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49399. };
  49400. /**
  49401. * Gets the maxZ used for shadow according to both the scene and the light.
  49402. * @param activeCamera The camera we are returning the max for
  49403. * @returns the depth max z
  49404. */
  49405. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49406. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49407. };
  49408. /**
  49409. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49410. * @param matrix The materix to updated with the projection information
  49411. * @param viewMatrix The transform matrix of the light
  49412. * @param renderList The list of mesh to render in the map
  49413. * @returns The current light
  49414. */
  49415. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49416. if (this.customProjectionMatrixBuilder) {
  49417. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49418. }
  49419. else {
  49420. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49421. }
  49422. return this;
  49423. };
  49424. __decorate([
  49425. BABYLON.serializeAsVector3()
  49426. ], ShadowLight.prototype, "position", null);
  49427. __decorate([
  49428. BABYLON.serializeAsVector3()
  49429. ], ShadowLight.prototype, "direction", null);
  49430. __decorate([
  49431. BABYLON.serialize()
  49432. ], ShadowLight.prototype, "shadowMinZ", null);
  49433. __decorate([
  49434. BABYLON.serialize()
  49435. ], ShadowLight.prototype, "shadowMaxZ", null);
  49436. return ShadowLight;
  49437. }(BABYLON.Light));
  49438. BABYLON.ShadowLight = ShadowLight;
  49439. })(BABYLON || (BABYLON = {}));
  49440. //# sourceMappingURL=babylon.shadowLight.js.map
  49441. var BABYLON;
  49442. (function (BABYLON) {
  49443. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49444. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49445. });
  49446. /**
  49447. * A point light is a light defined by an unique point in world space.
  49448. * The light is emitted in every direction from this point.
  49449. * A good example of a point light is a standard light bulb.
  49450. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49451. */
  49452. var PointLight = /** @class */ (function (_super) {
  49453. __extends(PointLight, _super);
  49454. /**
  49455. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49456. * A PointLight emits the light in every direction.
  49457. * It can cast shadows.
  49458. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49459. * ```javascript
  49460. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49461. * ```
  49462. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49463. * @param name The light friendly name
  49464. * @param position The position of the point light in the scene
  49465. * @param scene The scene the lights belongs to
  49466. */
  49467. function PointLight(name, position, scene) {
  49468. var _this = _super.call(this, name, scene) || this;
  49469. _this._shadowAngle = Math.PI / 2;
  49470. _this.position = position;
  49471. return _this;
  49472. }
  49473. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49474. /**
  49475. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49476. * This specifies what angle the shadow will use to be created.
  49477. *
  49478. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49479. */
  49480. get: function () {
  49481. return this._shadowAngle;
  49482. },
  49483. /**
  49484. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49485. * This specifies what angle the shadow will use to be created.
  49486. *
  49487. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49488. */
  49489. set: function (value) {
  49490. this._shadowAngle = value;
  49491. this.forceProjectionMatrixCompute();
  49492. },
  49493. enumerable: true,
  49494. configurable: true
  49495. });
  49496. Object.defineProperty(PointLight.prototype, "direction", {
  49497. /**
  49498. * Gets the direction if it has been set.
  49499. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49500. */
  49501. get: function () {
  49502. return this._direction;
  49503. },
  49504. /**
  49505. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49506. */
  49507. set: function (value) {
  49508. var previousNeedCube = this.needCube();
  49509. this._direction = value;
  49510. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49511. this._shadowGenerator.recreateShadowMap();
  49512. }
  49513. },
  49514. enumerable: true,
  49515. configurable: true
  49516. });
  49517. /**
  49518. * Returns the string "PointLight"
  49519. * @returns the class name
  49520. */
  49521. PointLight.prototype.getClassName = function () {
  49522. return "PointLight";
  49523. };
  49524. /**
  49525. * Returns the integer 0.
  49526. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49527. */
  49528. PointLight.prototype.getTypeID = function () {
  49529. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49530. };
  49531. /**
  49532. * Specifies wether or not the shadowmap should be a cube texture.
  49533. * @returns true if the shadowmap needs to be a cube texture.
  49534. */
  49535. PointLight.prototype.needCube = function () {
  49536. return !this.direction;
  49537. };
  49538. /**
  49539. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49540. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49541. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49542. */
  49543. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49544. if (this.direction) {
  49545. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49546. }
  49547. else {
  49548. switch (faceIndex) {
  49549. case 0:
  49550. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49551. case 1:
  49552. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49553. case 2:
  49554. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49555. case 3:
  49556. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49557. case 4:
  49558. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49559. case 5:
  49560. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49561. }
  49562. }
  49563. return BABYLON.Vector3.Zero();
  49564. };
  49565. /**
  49566. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49567. * - fov = PI / 2
  49568. * - aspect ratio : 1.0
  49569. * - z-near and far equal to the active camera minZ and maxZ.
  49570. * Returns the PointLight.
  49571. */
  49572. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49573. var activeCamera = this.getScene().activeCamera;
  49574. if (!activeCamera) {
  49575. return;
  49576. }
  49577. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49578. };
  49579. PointLight.prototype._buildUniformLayout = function () {
  49580. this._uniformBuffer.addUniform("vLightData", 4);
  49581. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49582. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49583. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49584. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49585. this._uniformBuffer.addUniform("depthValues", 2);
  49586. this._uniformBuffer.create();
  49587. };
  49588. /**
  49589. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49590. * @param effect The effect to update
  49591. * @param lightIndex The index of the light in the effect to update
  49592. * @returns The point light
  49593. */
  49594. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49595. if (this.computeTransformedInformation()) {
  49596. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49597. }
  49598. else {
  49599. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49600. }
  49601. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49602. return this;
  49603. };
  49604. /**
  49605. * Prepares the list of defines specific to the light type.
  49606. * @param defines the list of defines
  49607. * @param lightIndex defines the index of the light for the effect
  49608. */
  49609. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49610. defines["POINTLIGHT" + lightIndex] = true;
  49611. };
  49612. __decorate([
  49613. BABYLON.serialize()
  49614. ], PointLight.prototype, "shadowAngle", null);
  49615. return PointLight;
  49616. }(BABYLON.ShadowLight));
  49617. BABYLON.PointLight = PointLight;
  49618. })(BABYLON || (BABYLON = {}));
  49619. //# sourceMappingURL=babylon.pointLight.js.map
  49620. var BABYLON;
  49621. (function (BABYLON) {
  49622. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49623. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49624. });
  49625. /**
  49626. * A directional light is defined by a direction (what a surprise!).
  49627. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49628. * 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.
  49629. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49630. */
  49631. var DirectionalLight = /** @class */ (function (_super) {
  49632. __extends(DirectionalLight, _super);
  49633. /**
  49634. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49635. * The directional light is emitted from everywhere in the given direction.
  49636. * It can cast shadows.
  49637. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49638. * @param name The friendly name of the light
  49639. * @param direction The direction of the light
  49640. * @param scene The scene the light belongs to
  49641. */
  49642. function DirectionalLight(name, direction, scene) {
  49643. var _this = _super.call(this, name, scene) || this;
  49644. _this._shadowFrustumSize = 0;
  49645. _this._shadowOrthoScale = 0.1;
  49646. /**
  49647. * Automatically compute the projection matrix to best fit (including all the casters)
  49648. * on each frame.
  49649. */
  49650. _this.autoUpdateExtends = true;
  49651. // Cache
  49652. _this._orthoLeft = Number.MAX_VALUE;
  49653. _this._orthoRight = Number.MIN_VALUE;
  49654. _this._orthoTop = Number.MIN_VALUE;
  49655. _this._orthoBottom = Number.MAX_VALUE;
  49656. _this.position = direction.scale(-1.0);
  49657. _this.direction = direction;
  49658. return _this;
  49659. }
  49660. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49661. /**
  49662. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49663. */
  49664. get: function () {
  49665. return this._shadowFrustumSize;
  49666. },
  49667. /**
  49668. * Specifies a fix frustum size for the shadow generation.
  49669. */
  49670. set: function (value) {
  49671. this._shadowFrustumSize = value;
  49672. this.forceProjectionMatrixCompute();
  49673. },
  49674. enumerable: true,
  49675. configurable: true
  49676. });
  49677. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49678. /**
  49679. * Gets the shadow projection scale against the optimal computed one.
  49680. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49681. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49682. */
  49683. get: function () {
  49684. return this._shadowOrthoScale;
  49685. },
  49686. /**
  49687. * Sets the shadow projection scale against the optimal computed one.
  49688. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49689. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49690. */
  49691. set: function (value) {
  49692. this._shadowOrthoScale = value;
  49693. this.forceProjectionMatrixCompute();
  49694. },
  49695. enumerable: true,
  49696. configurable: true
  49697. });
  49698. /**
  49699. * Returns the string "DirectionalLight".
  49700. * @return The class name
  49701. */
  49702. DirectionalLight.prototype.getClassName = function () {
  49703. return "DirectionalLight";
  49704. };
  49705. /**
  49706. * Returns the integer 1.
  49707. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49708. */
  49709. DirectionalLight.prototype.getTypeID = function () {
  49710. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49711. };
  49712. /**
  49713. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49714. * Returns the DirectionalLight Shadow projection matrix.
  49715. */
  49716. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49717. if (this.shadowFrustumSize > 0) {
  49718. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49719. }
  49720. else {
  49721. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49722. }
  49723. };
  49724. /**
  49725. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49726. * Returns the DirectionalLight Shadow projection matrix.
  49727. */
  49728. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49729. var activeCamera = this.getScene().activeCamera;
  49730. if (!activeCamera) {
  49731. return;
  49732. }
  49733. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49734. };
  49735. /**
  49736. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49737. * Returns the DirectionalLight Shadow projection matrix.
  49738. */
  49739. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49740. var activeCamera = this.getScene().activeCamera;
  49741. if (!activeCamera) {
  49742. return;
  49743. }
  49744. // Check extends
  49745. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49746. var tempVector3 = BABYLON.Vector3.Zero();
  49747. this._orthoLeft = Number.MAX_VALUE;
  49748. this._orthoRight = Number.MIN_VALUE;
  49749. this._orthoTop = Number.MIN_VALUE;
  49750. this._orthoBottom = Number.MAX_VALUE;
  49751. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49752. var mesh = renderList[meshIndex];
  49753. if (!mesh) {
  49754. continue;
  49755. }
  49756. var boundingInfo = mesh.getBoundingInfo();
  49757. var boundingBox = boundingInfo.boundingBox;
  49758. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49759. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49760. if (tempVector3.x < this._orthoLeft)
  49761. this._orthoLeft = tempVector3.x;
  49762. if (tempVector3.y < this._orthoBottom)
  49763. this._orthoBottom = tempVector3.y;
  49764. if (tempVector3.x > this._orthoRight)
  49765. this._orthoRight = tempVector3.x;
  49766. if (tempVector3.y > this._orthoTop)
  49767. this._orthoTop = tempVector3.y;
  49768. }
  49769. }
  49770. }
  49771. var xOffset = this._orthoRight - this._orthoLeft;
  49772. var yOffset = this._orthoTop - this._orthoBottom;
  49773. 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);
  49774. };
  49775. DirectionalLight.prototype._buildUniformLayout = function () {
  49776. this._uniformBuffer.addUniform("vLightData", 4);
  49777. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49778. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49779. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49780. this._uniformBuffer.addUniform("depthValues", 2);
  49781. this._uniformBuffer.create();
  49782. };
  49783. /**
  49784. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49785. * @param effect The effect to update
  49786. * @param lightIndex The index of the light in the effect to update
  49787. * @returns The directional light
  49788. */
  49789. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49790. if (this.computeTransformedInformation()) {
  49791. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49792. return this;
  49793. }
  49794. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49795. return this;
  49796. };
  49797. /**
  49798. * Gets the minZ used for shadow according to both the scene and the light.
  49799. *
  49800. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49801. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49802. * @param activeCamera The camera we are returning the min for
  49803. * @returns the depth min z
  49804. */
  49805. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49806. return 1;
  49807. };
  49808. /**
  49809. * Gets the maxZ used for shadow according to both the scene and the light.
  49810. *
  49811. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49812. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49813. * @param activeCamera The camera we are returning the max for
  49814. * @returns the depth max z
  49815. */
  49816. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49817. return 1;
  49818. };
  49819. /**
  49820. * Prepares the list of defines specific to the light type.
  49821. * @param defines the list of defines
  49822. * @param lightIndex defines the index of the light for the effect
  49823. */
  49824. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49825. defines["DIRLIGHT" + lightIndex] = true;
  49826. };
  49827. __decorate([
  49828. BABYLON.serialize()
  49829. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49830. __decorate([
  49831. BABYLON.serialize()
  49832. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49833. __decorate([
  49834. BABYLON.serialize()
  49835. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49836. return DirectionalLight;
  49837. }(BABYLON.ShadowLight));
  49838. BABYLON.DirectionalLight = DirectionalLight;
  49839. })(BABYLON || (BABYLON = {}));
  49840. //# sourceMappingURL=babylon.directionalLight.js.map
  49841. var BABYLON;
  49842. (function (BABYLON) {
  49843. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49844. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49845. });
  49846. /**
  49847. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49848. * These values define a cone of light starting from the position, emitting toward the direction.
  49849. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49850. * and the exponent defines the speed of the decay of the light with distance (reach).
  49851. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49852. */
  49853. var SpotLight = /** @class */ (function (_super) {
  49854. __extends(SpotLight, _super);
  49855. /**
  49856. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49857. * It can cast shadows.
  49858. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49859. * @param name The light friendly name
  49860. * @param position The position of the spot light in the scene
  49861. * @param direction The direction of the light in the scene
  49862. * @param angle The cone angle of the light in Radians
  49863. * @param exponent The light decay speed with the distance from the emission spot
  49864. * @param scene The scene the lights belongs to
  49865. */
  49866. function SpotLight(name, position, direction, angle, exponent, scene) {
  49867. var _this = _super.call(this, name, scene) || this;
  49868. _this._innerAngle = 0;
  49869. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49870. _this._projectionTextureLightNear = 1e-6;
  49871. _this._projectionTextureLightFar = 1000.0;
  49872. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49873. _this._projectionTextureViewLightDirty = true;
  49874. _this._projectionTextureProjectionLightDirty = true;
  49875. _this._projectionTextureDirty = true;
  49876. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49877. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49878. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49879. _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);
  49880. _this.position = position;
  49881. _this.direction = direction;
  49882. _this.angle = angle;
  49883. _this.exponent = exponent;
  49884. return _this;
  49885. }
  49886. Object.defineProperty(SpotLight.prototype, "angle", {
  49887. /**
  49888. * Gets the cone angle of the spot light in Radians.
  49889. */
  49890. get: function () {
  49891. return this._angle;
  49892. },
  49893. /**
  49894. * Sets the cone angle of the spot light in Radians.
  49895. */
  49896. set: function (value) {
  49897. this._angle = value;
  49898. this._cosHalfAngle = Math.cos(value * 0.5);
  49899. this._projectionTextureProjectionLightDirty = true;
  49900. this.forceProjectionMatrixCompute();
  49901. this._computeAngleValues();
  49902. },
  49903. enumerable: true,
  49904. configurable: true
  49905. });
  49906. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49907. /**
  49908. * Only used in gltf falloff mode, this defines the angle where
  49909. * the directional falloff will start before cutting at angle which could be seen
  49910. * as outer angle.
  49911. */
  49912. get: function () {
  49913. return this._innerAngle;
  49914. },
  49915. /**
  49916. * Only used in gltf falloff mode, this defines the angle where
  49917. * the directional falloff will start before cutting at angle which could be seen
  49918. * as outer angle.
  49919. */
  49920. set: function (value) {
  49921. this._innerAngle = value;
  49922. this._computeAngleValues();
  49923. },
  49924. enumerable: true,
  49925. configurable: true
  49926. });
  49927. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49928. /**
  49929. * Allows scaling the angle of the light for shadow generation only.
  49930. */
  49931. get: function () {
  49932. return this._shadowAngleScale;
  49933. },
  49934. /**
  49935. * Allows scaling the angle of the light for shadow generation only.
  49936. */
  49937. set: function (value) {
  49938. this._shadowAngleScale = value;
  49939. this.forceProjectionMatrixCompute();
  49940. },
  49941. enumerable: true,
  49942. configurable: true
  49943. });
  49944. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49945. /**
  49946. * Allows reading the projecton texture
  49947. */
  49948. get: function () {
  49949. return this._projectionTextureMatrix;
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49955. /**
  49956. * Gets the near clip of the Spotlight for texture projection.
  49957. */
  49958. get: function () {
  49959. return this._projectionTextureLightNear;
  49960. },
  49961. /**
  49962. * Sets the near clip of the Spotlight for texture projection.
  49963. */
  49964. set: function (value) {
  49965. this._projectionTextureLightNear = value;
  49966. this._projectionTextureProjectionLightDirty = true;
  49967. },
  49968. enumerable: true,
  49969. configurable: true
  49970. });
  49971. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49972. /**
  49973. * Gets the far clip of the Spotlight for texture projection.
  49974. */
  49975. get: function () {
  49976. return this._projectionTextureLightFar;
  49977. },
  49978. /**
  49979. * Sets the far clip of the Spotlight for texture projection.
  49980. */
  49981. set: function (value) {
  49982. this._projectionTextureLightFar = value;
  49983. this._projectionTextureProjectionLightDirty = true;
  49984. },
  49985. enumerable: true,
  49986. configurable: true
  49987. });
  49988. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49989. /**
  49990. * Gets the Up vector of the Spotlight for texture projection.
  49991. */
  49992. get: function () {
  49993. return this._projectionTextureUpDirection;
  49994. },
  49995. /**
  49996. * Sets the Up vector of the Spotlight for texture projection.
  49997. */
  49998. set: function (value) {
  49999. this._projectionTextureUpDirection = value;
  50000. this._projectionTextureProjectionLightDirty = true;
  50001. },
  50002. enumerable: true,
  50003. configurable: true
  50004. });
  50005. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50006. /**
  50007. * Gets the projection texture of the light.
  50008. */
  50009. get: function () {
  50010. return this._projectionTexture;
  50011. },
  50012. /**
  50013. * Sets the projection texture of the light.
  50014. */
  50015. set: function (value) {
  50016. this._projectionTexture = value;
  50017. this._projectionTextureDirty = true;
  50018. },
  50019. enumerable: true,
  50020. configurable: true
  50021. });
  50022. /**
  50023. * Returns the string "SpotLight".
  50024. * @returns the class name
  50025. */
  50026. SpotLight.prototype.getClassName = function () {
  50027. return "SpotLight";
  50028. };
  50029. /**
  50030. * Returns the integer 2.
  50031. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50032. */
  50033. SpotLight.prototype.getTypeID = function () {
  50034. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50035. };
  50036. /**
  50037. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50038. */
  50039. SpotLight.prototype._setDirection = function (value) {
  50040. _super.prototype._setDirection.call(this, value);
  50041. this._projectionTextureViewLightDirty = true;
  50042. };
  50043. /**
  50044. * Overrides the position setter to recompute the projection texture view light Matrix.
  50045. */
  50046. SpotLight.prototype._setPosition = function (value) {
  50047. _super.prototype._setPosition.call(this, value);
  50048. this._projectionTextureViewLightDirty = true;
  50049. };
  50050. /**
  50051. * 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.
  50052. * Returns the SpotLight.
  50053. */
  50054. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50055. var activeCamera = this.getScene().activeCamera;
  50056. if (!activeCamera) {
  50057. return;
  50058. }
  50059. this._shadowAngleScale = this._shadowAngleScale || 1;
  50060. var angle = this._shadowAngleScale * this._angle;
  50061. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50062. };
  50063. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50064. this._projectionTextureViewLightDirty = false;
  50065. this._projectionTextureDirty = true;
  50066. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50067. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50068. };
  50069. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50070. this._projectionTextureProjectionLightDirty = false;
  50071. this._projectionTextureDirty = true;
  50072. var light_far = this.projectionTextureLightFar;
  50073. var light_near = this.projectionTextureLightNear;
  50074. var P = light_far / (light_far - light_near);
  50075. var Q = -P * light_near;
  50076. var S = 1.0 / Math.tan(this._angle / 2.0);
  50077. var A = 1.0;
  50078. 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);
  50079. };
  50080. /**
  50081. * Main function for light texture projection matrix computing.
  50082. */
  50083. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50084. this._projectionTextureDirty = false;
  50085. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50086. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50087. };
  50088. SpotLight.prototype._buildUniformLayout = function () {
  50089. this._uniformBuffer.addUniform("vLightData", 4);
  50090. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50091. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50092. this._uniformBuffer.addUniform("vLightDirection", 3);
  50093. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50094. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50095. this._uniformBuffer.addUniform("depthValues", 2);
  50096. this._uniformBuffer.create();
  50097. };
  50098. SpotLight.prototype._computeAngleValues = function () {
  50099. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50100. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50101. };
  50102. /**
  50103. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50104. * @param effect The effect to update
  50105. * @param lightIndex The index of the light in the effect to update
  50106. * @returns The spot light
  50107. */
  50108. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50109. var normalizeDirection;
  50110. if (this.computeTransformedInformation()) {
  50111. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50112. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50113. }
  50114. else {
  50115. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50116. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50117. }
  50118. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50119. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50120. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50121. if (this._projectionTextureViewLightDirty) {
  50122. this._computeProjectionTextureViewLightMatrix();
  50123. }
  50124. if (this._projectionTextureProjectionLightDirty) {
  50125. this._computeProjectionTextureProjectionLightMatrix();
  50126. }
  50127. if (this._projectionTextureDirty) {
  50128. this._computeProjectionTextureMatrix();
  50129. }
  50130. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50131. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50132. }
  50133. return this;
  50134. };
  50135. /**
  50136. * Disposes the light and the associated resources.
  50137. */
  50138. SpotLight.prototype.dispose = function () {
  50139. _super.prototype.dispose.call(this);
  50140. if (this._projectionTexture) {
  50141. this._projectionTexture.dispose();
  50142. }
  50143. };
  50144. /**
  50145. * Prepares the list of defines specific to the light type.
  50146. * @param defines the list of defines
  50147. * @param lightIndex defines the index of the light for the effect
  50148. */
  50149. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50150. defines["SPOTLIGHT" + lightIndex] = true;
  50151. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50152. };
  50153. __decorate([
  50154. BABYLON.serialize()
  50155. ], SpotLight.prototype, "angle", null);
  50156. __decorate([
  50157. BABYLON.serialize()
  50158. ], SpotLight.prototype, "innerAngle", null);
  50159. __decorate([
  50160. BABYLON.serialize()
  50161. ], SpotLight.prototype, "shadowAngleScale", null);
  50162. __decorate([
  50163. BABYLON.serialize()
  50164. ], SpotLight.prototype, "exponent", void 0);
  50165. __decorate([
  50166. BABYLON.serialize()
  50167. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50168. __decorate([
  50169. BABYLON.serialize()
  50170. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50171. __decorate([
  50172. BABYLON.serialize()
  50173. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50174. __decorate([
  50175. BABYLON.serializeAsTexture("projectedLightTexture")
  50176. ], SpotLight.prototype, "_projectionTexture", void 0);
  50177. return SpotLight;
  50178. }(BABYLON.ShadowLight));
  50179. BABYLON.SpotLight = SpotLight;
  50180. })(BABYLON || (BABYLON = {}));
  50181. //# sourceMappingURL=babylon.spotLight.js.map
  50182. var BABYLON;
  50183. (function (BABYLON) {
  50184. /**
  50185. * Class used to override all child animations of a given target
  50186. */
  50187. var AnimationPropertiesOverride = /** @class */ (function () {
  50188. function AnimationPropertiesOverride() {
  50189. /**
  50190. * Gets or sets a value indicating if animation blending must be used
  50191. */
  50192. this.enableBlending = false;
  50193. /**
  50194. * Gets or sets the blending speed to use when enableBlending is true
  50195. */
  50196. this.blendingSpeed = 0.01;
  50197. /**
  50198. * Gets or sets the default loop mode to use
  50199. */
  50200. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50201. }
  50202. return AnimationPropertiesOverride;
  50203. }());
  50204. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50205. })(BABYLON || (BABYLON = {}));
  50206. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50207. var BABYLON;
  50208. (function (BABYLON) {
  50209. /**
  50210. * Represents the range of an animation
  50211. */
  50212. var AnimationRange = /** @class */ (function () {
  50213. /**
  50214. * Initializes the range of an animation
  50215. * @param name The name of the animation range
  50216. * @param from The starting frame of the animation
  50217. * @param to The ending frame of the animation
  50218. */
  50219. function AnimationRange(
  50220. /**The name of the animation range**/
  50221. name,
  50222. /**The starting frame of the animation */
  50223. from,
  50224. /**The ending frame of the animation*/
  50225. to) {
  50226. this.name = name;
  50227. this.from = from;
  50228. this.to = to;
  50229. }
  50230. /**
  50231. * Makes a copy of the animation range
  50232. * @returns A copy of the animation range
  50233. */
  50234. AnimationRange.prototype.clone = function () {
  50235. return new AnimationRange(this.name, this.from, this.to);
  50236. };
  50237. return AnimationRange;
  50238. }());
  50239. BABYLON.AnimationRange = AnimationRange;
  50240. /**
  50241. * Composed of a frame, and an action function
  50242. */
  50243. var AnimationEvent = /** @class */ (function () {
  50244. /**
  50245. * Initializes the animation event
  50246. * @param frame The frame for which the event is triggered
  50247. * @param action The event to perform when triggered
  50248. * @param onlyOnce Specifies if the event should be triggered only once
  50249. */
  50250. function AnimationEvent(
  50251. /** The frame for which the event is triggered **/
  50252. frame,
  50253. /** The event to perform when triggered **/
  50254. action,
  50255. /** Specifies if the event should be triggered only once**/
  50256. onlyOnce) {
  50257. this.frame = frame;
  50258. this.action = action;
  50259. this.onlyOnce = onlyOnce;
  50260. /**
  50261. * Specifies if the animation event is done
  50262. */
  50263. this.isDone = false;
  50264. }
  50265. /** @hidden */
  50266. AnimationEvent.prototype._clone = function () {
  50267. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50268. };
  50269. return AnimationEvent;
  50270. }());
  50271. BABYLON.AnimationEvent = AnimationEvent;
  50272. /**
  50273. * A cursor which tracks a point on a path
  50274. */
  50275. var PathCursor = /** @class */ (function () {
  50276. /**
  50277. * Initializes the path cursor
  50278. * @param path The path to track
  50279. */
  50280. function PathCursor(path) {
  50281. this.path = path;
  50282. /**
  50283. * Stores path cursor callbacks for when an onchange event is triggered
  50284. */
  50285. this._onchange = new Array();
  50286. /**
  50287. * The value of the path cursor
  50288. */
  50289. this.value = 0;
  50290. /**
  50291. * The animation array of the path cursor
  50292. */
  50293. this.animations = new Array();
  50294. }
  50295. /**
  50296. * Gets the cursor point on the path
  50297. * @returns A point on the path cursor at the cursor location
  50298. */
  50299. PathCursor.prototype.getPoint = function () {
  50300. var point = this.path.getPointAtLengthPosition(this.value);
  50301. return new BABYLON.Vector3(point.x, 0, point.y);
  50302. };
  50303. /**
  50304. * Moves the cursor ahead by the step amount
  50305. * @param step The amount to move the cursor forward
  50306. * @returns This path cursor
  50307. */
  50308. PathCursor.prototype.moveAhead = function (step) {
  50309. if (step === void 0) { step = 0.002; }
  50310. this.move(step);
  50311. return this;
  50312. };
  50313. /**
  50314. * Moves the cursor behind by the step amount
  50315. * @param step The amount to move the cursor back
  50316. * @returns This path cursor
  50317. */
  50318. PathCursor.prototype.moveBack = function (step) {
  50319. if (step === void 0) { step = 0.002; }
  50320. this.move(-step);
  50321. return this;
  50322. };
  50323. /**
  50324. * Moves the cursor by the step amount
  50325. * If the step amount is greater than one, an exception is thrown
  50326. * @param step The amount to move the cursor
  50327. * @returns This path cursor
  50328. */
  50329. PathCursor.prototype.move = function (step) {
  50330. if (Math.abs(step) > 1) {
  50331. throw "step size should be less than 1.";
  50332. }
  50333. this.value += step;
  50334. this.ensureLimits();
  50335. this.raiseOnChange();
  50336. return this;
  50337. };
  50338. /**
  50339. * Ensures that the value is limited between zero and one
  50340. * @returns This path cursor
  50341. */
  50342. PathCursor.prototype.ensureLimits = function () {
  50343. while (this.value > 1) {
  50344. this.value -= 1;
  50345. }
  50346. while (this.value < 0) {
  50347. this.value += 1;
  50348. }
  50349. return this;
  50350. };
  50351. /**
  50352. * Runs onchange callbacks on change (used by the animation engine)
  50353. * @returns This path cursor
  50354. */
  50355. PathCursor.prototype.raiseOnChange = function () {
  50356. var _this = this;
  50357. this._onchange.forEach(function (f) { return f(_this); });
  50358. return this;
  50359. };
  50360. /**
  50361. * Executes a function on change
  50362. * @param f A path cursor onchange callback
  50363. * @returns This path cursor
  50364. */
  50365. PathCursor.prototype.onchange = function (f) {
  50366. this._onchange.push(f);
  50367. return this;
  50368. };
  50369. return PathCursor;
  50370. }());
  50371. BABYLON.PathCursor = PathCursor;
  50372. /**
  50373. * Enum for the animation key frame interpolation type
  50374. */
  50375. var AnimationKeyInterpolation;
  50376. (function (AnimationKeyInterpolation) {
  50377. /**
  50378. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50379. */
  50380. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50381. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50382. /**
  50383. * Class used to store any kind of animation
  50384. */
  50385. var Animation = /** @class */ (function () {
  50386. /**
  50387. * Initializes the animation
  50388. * @param name Name of the animation
  50389. * @param targetProperty Property to animate
  50390. * @param framePerSecond The frames per second of the animation
  50391. * @param dataType The data type of the animation
  50392. * @param loopMode The loop mode of the animation
  50393. * @param enableBlendings Specifies if blending should be enabled
  50394. */
  50395. function Animation(
  50396. /**Name of the animation */
  50397. name,
  50398. /**Property to animate */
  50399. targetProperty,
  50400. /**The frames per second of the animation */
  50401. framePerSecond,
  50402. /**The data type of the animation */
  50403. dataType,
  50404. /**The loop mode of the animation */
  50405. loopMode,
  50406. /**Specifies if blending should be enabled */
  50407. enableBlending) {
  50408. this.name = name;
  50409. this.targetProperty = targetProperty;
  50410. this.framePerSecond = framePerSecond;
  50411. this.dataType = dataType;
  50412. this.loopMode = loopMode;
  50413. this.enableBlending = enableBlending;
  50414. /**
  50415. * @hidden Internal use only
  50416. */
  50417. this._runtimeAnimations = new Array();
  50418. /**
  50419. * The set of event that will be linked to this animation
  50420. */
  50421. this._events = new Array();
  50422. /**
  50423. * Stores the blending speed of the animation
  50424. */
  50425. this.blendingSpeed = 0.01;
  50426. /**
  50427. * Stores the animation ranges for the animation
  50428. */
  50429. this._ranges = {};
  50430. this.targetPropertyPath = targetProperty.split(".");
  50431. this.dataType = dataType;
  50432. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50433. }
  50434. /**
  50435. * @hidden Internal use
  50436. */
  50437. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50438. var dataType = undefined;
  50439. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50440. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50441. }
  50442. else if (from instanceof BABYLON.Quaternion) {
  50443. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50444. }
  50445. else if (from instanceof BABYLON.Vector3) {
  50446. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50447. }
  50448. else if (from instanceof BABYLON.Vector2) {
  50449. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50450. }
  50451. else if (from instanceof BABYLON.Color3) {
  50452. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50453. }
  50454. else if (from instanceof BABYLON.Size) {
  50455. dataType = Animation.ANIMATIONTYPE_SIZE;
  50456. }
  50457. if (dataType == undefined) {
  50458. return null;
  50459. }
  50460. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50461. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50462. animation.setKeys(keys);
  50463. if (easingFunction !== undefined) {
  50464. animation.setEasingFunction(easingFunction);
  50465. }
  50466. return animation;
  50467. };
  50468. /**
  50469. * Sets up an animation
  50470. * @param property The property to animate
  50471. * @param animationType The animation type to apply
  50472. * @param framePerSecond The frames per second of the animation
  50473. * @param easingFunction The easing function used in the animation
  50474. * @returns The created animation
  50475. */
  50476. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50477. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50478. animation.setEasingFunction(easingFunction);
  50479. return animation;
  50480. };
  50481. /**
  50482. * Create and start an animation on a node
  50483. * @param name defines the name of the global animation that will be run on all nodes
  50484. * @param node defines the root node where the animation will take place
  50485. * @param targetProperty defines property to animate
  50486. * @param framePerSecond defines the number of frame per second yo use
  50487. * @param totalFrame defines the number of frames in total
  50488. * @param from defines the initial value
  50489. * @param to defines the final value
  50490. * @param loopMode defines which loop mode you want to use (off by default)
  50491. * @param easingFunction defines the easing function to use (linear by default)
  50492. * @param onAnimationEnd defines the callback to call when animation end
  50493. * @returns the animatable created for this animation
  50494. */
  50495. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50496. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50497. if (!animation) {
  50498. return null;
  50499. }
  50500. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50501. };
  50502. /**
  50503. * Create and start an animation on a node and its descendants
  50504. * @param name defines the name of the global animation that will be run on all nodes
  50505. * @param node defines the root node where the animation will take place
  50506. * @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
  50507. * @param targetProperty defines property to animate
  50508. * @param framePerSecond defines the number of frame per second to use
  50509. * @param totalFrame defines the number of frames in total
  50510. * @param from defines the initial value
  50511. * @param to defines the final value
  50512. * @param loopMode defines which loop mode you want to use (off by default)
  50513. * @param easingFunction defines the easing function to use (linear by default)
  50514. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50515. * @returns the list of animatables created for all nodes
  50516. * @example https://www.babylonjs-playground.com/#MH0VLI
  50517. */
  50518. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50519. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50520. if (!animation) {
  50521. return null;
  50522. }
  50523. var scene = node.getScene();
  50524. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50525. };
  50526. /**
  50527. * Creates a new animation, merges it with the existing animations and starts it
  50528. * @param name Name of the animation
  50529. * @param node Node which contains the scene that begins the animations
  50530. * @param targetProperty Specifies which property to animate
  50531. * @param framePerSecond The frames per second of the animation
  50532. * @param totalFrame The total number of frames
  50533. * @param from The frame at the beginning of the animation
  50534. * @param to The frame at the end of the animation
  50535. * @param loopMode Specifies the loop mode of the animation
  50536. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50537. * @param onAnimationEnd Callback to run once the animation is complete
  50538. * @returns Nullable animation
  50539. */
  50540. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50541. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50542. if (!animation) {
  50543. return null;
  50544. }
  50545. node.animations.push(animation);
  50546. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50547. };
  50548. /**
  50549. * Transition property of an host to the target Value
  50550. * @param property The property to transition
  50551. * @param targetValue The target Value of the property
  50552. * @param host The object where the property to animate belongs
  50553. * @param scene Scene used to run the animation
  50554. * @param frameRate Framerate (in frame/s) to use
  50555. * @param transition The transition type we want to use
  50556. * @param duration The duration of the animation, in milliseconds
  50557. * @param onAnimationEnd Callback trigger at the end of the animation
  50558. * @returns Nullable animation
  50559. */
  50560. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50561. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50562. if (duration <= 0) {
  50563. host[property] = targetValue;
  50564. if (onAnimationEnd) {
  50565. onAnimationEnd();
  50566. }
  50567. return null;
  50568. }
  50569. var endFrame = frameRate * (duration / 1000);
  50570. transition.setKeys([{
  50571. frame: 0,
  50572. value: host[property].clone ? host[property].clone() : host[property]
  50573. },
  50574. {
  50575. frame: endFrame,
  50576. value: targetValue
  50577. }]);
  50578. if (!host.animations) {
  50579. host.animations = [];
  50580. }
  50581. host.animations.push(transition);
  50582. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50583. animation.onAnimationEnd = onAnimationEnd;
  50584. return animation;
  50585. };
  50586. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50587. /**
  50588. * Return the array of runtime animations currently using this animation
  50589. */
  50590. get: function () {
  50591. return this._runtimeAnimations;
  50592. },
  50593. enumerable: true,
  50594. configurable: true
  50595. });
  50596. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50597. /**
  50598. * Specifies if any of the runtime animations are currently running
  50599. */
  50600. get: function () {
  50601. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50602. var runtimeAnimation = _a[_i];
  50603. if (!runtimeAnimation.isStopped) {
  50604. return true;
  50605. }
  50606. }
  50607. return false;
  50608. },
  50609. enumerable: true,
  50610. configurable: true
  50611. });
  50612. // Methods
  50613. /**
  50614. * Converts the animation to a string
  50615. * @param fullDetails support for multiple levels of logging within scene loading
  50616. * @returns String form of the animation
  50617. */
  50618. Animation.prototype.toString = function (fullDetails) {
  50619. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50620. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50621. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50622. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50623. if (fullDetails) {
  50624. ret += ", Ranges: {";
  50625. var first = true;
  50626. for (var name in this._ranges) {
  50627. if (first) {
  50628. ret += ", ";
  50629. first = false;
  50630. }
  50631. ret += name;
  50632. }
  50633. ret += "}";
  50634. }
  50635. return ret;
  50636. };
  50637. /**
  50638. * Add an event to this animation
  50639. * @param event Event to add
  50640. */
  50641. Animation.prototype.addEvent = function (event) {
  50642. this._events.push(event);
  50643. };
  50644. /**
  50645. * Remove all events found at the given frame
  50646. * @param frame The frame to remove events from
  50647. */
  50648. Animation.prototype.removeEvents = function (frame) {
  50649. for (var index = 0; index < this._events.length; index++) {
  50650. if (this._events[index].frame === frame) {
  50651. this._events.splice(index, 1);
  50652. index--;
  50653. }
  50654. }
  50655. };
  50656. /**
  50657. * Retrieves all the events from the animation
  50658. * @returns Events from the animation
  50659. */
  50660. Animation.prototype.getEvents = function () {
  50661. return this._events;
  50662. };
  50663. /**
  50664. * Creates an animation range
  50665. * @param name Name of the animation range
  50666. * @param from Starting frame of the animation range
  50667. * @param to Ending frame of the animation
  50668. */
  50669. Animation.prototype.createRange = function (name, from, to) {
  50670. // check name not already in use; could happen for bones after serialized
  50671. if (!this._ranges[name]) {
  50672. this._ranges[name] = new AnimationRange(name, from, to);
  50673. }
  50674. };
  50675. /**
  50676. * Deletes an animation range by name
  50677. * @param name Name of the animation range to delete
  50678. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50679. */
  50680. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50681. if (deleteFrames === void 0) { deleteFrames = true; }
  50682. var range = this._ranges[name];
  50683. if (!range) {
  50684. return;
  50685. }
  50686. if (deleteFrames) {
  50687. var from = range.from;
  50688. var to = range.to;
  50689. // this loop MUST go high to low for multiple splices to work
  50690. for (var key = this._keys.length - 1; key >= 0; key--) {
  50691. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50692. this._keys.splice(key, 1);
  50693. }
  50694. }
  50695. }
  50696. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50697. };
  50698. /**
  50699. * Gets the animation range by name, or null if not defined
  50700. * @param name Name of the animation range
  50701. * @returns Nullable animation range
  50702. */
  50703. Animation.prototype.getRange = function (name) {
  50704. return this._ranges[name];
  50705. };
  50706. /**
  50707. * Gets the key frames from the animation
  50708. * @returns The key frames of the animation
  50709. */
  50710. Animation.prototype.getKeys = function () {
  50711. return this._keys;
  50712. };
  50713. /**
  50714. * Gets the highest frame rate of the animation
  50715. * @returns Highest frame rate of the animation
  50716. */
  50717. Animation.prototype.getHighestFrame = function () {
  50718. var ret = 0;
  50719. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50720. if (ret < this._keys[key].frame) {
  50721. ret = this._keys[key].frame;
  50722. }
  50723. }
  50724. return ret;
  50725. };
  50726. /**
  50727. * Gets the easing function of the animation
  50728. * @returns Easing function of the animation
  50729. */
  50730. Animation.prototype.getEasingFunction = function () {
  50731. return this._easingFunction;
  50732. };
  50733. /**
  50734. * Sets the easing function of the animation
  50735. * @param easingFunction A custom mathematical formula for animation
  50736. */
  50737. Animation.prototype.setEasingFunction = function (easingFunction) {
  50738. this._easingFunction = easingFunction;
  50739. };
  50740. /**
  50741. * Interpolates a scalar linearly
  50742. * @param startValue Start value of the animation curve
  50743. * @param endValue End value of the animation curve
  50744. * @param gradient Scalar amount to interpolate
  50745. * @returns Interpolated scalar value
  50746. */
  50747. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50748. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50749. };
  50750. /**
  50751. * Interpolates a scalar cubically
  50752. * @param startValue Start value of the animation curve
  50753. * @param outTangent End tangent of the animation
  50754. * @param endValue End value of the animation curve
  50755. * @param inTangent Start tangent of the animation curve
  50756. * @param gradient Scalar amount to interpolate
  50757. * @returns Interpolated scalar value
  50758. */
  50759. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50760. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50761. };
  50762. /**
  50763. * Interpolates a quaternion using a spherical linear interpolation
  50764. * @param startValue Start value of the animation curve
  50765. * @param endValue End value of the animation curve
  50766. * @param gradient Scalar amount to interpolate
  50767. * @returns Interpolated quaternion value
  50768. */
  50769. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50770. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50771. };
  50772. /**
  50773. * Interpolates a quaternion cubically
  50774. * @param startValue Start value of the animation curve
  50775. * @param outTangent End tangent of the animation curve
  50776. * @param endValue End value of the animation curve
  50777. * @param inTangent Start tangent of the animation curve
  50778. * @param gradient Scalar amount to interpolate
  50779. * @returns Interpolated quaternion value
  50780. */
  50781. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50782. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50783. };
  50784. /**
  50785. * Interpolates a Vector3 linearl
  50786. * @param startValue Start value of the animation curve
  50787. * @param endValue End value of the animation curve
  50788. * @param gradient Scalar amount to interpolate
  50789. * @returns Interpolated scalar value
  50790. */
  50791. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50792. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50793. };
  50794. /**
  50795. * Interpolates a Vector3 cubically
  50796. * @param startValue Start value of the animation curve
  50797. * @param outTangent End tangent of the animation
  50798. * @param endValue End value of the animation curve
  50799. * @param inTangent Start tangent of the animation curve
  50800. * @param gradient Scalar amount to interpolate
  50801. * @returns InterpolatedVector3 value
  50802. */
  50803. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50804. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50805. };
  50806. /**
  50807. * Interpolates a Vector2 linearly
  50808. * @param startValue Start value of the animation curve
  50809. * @param endValue End value of the animation curve
  50810. * @param gradient Scalar amount to interpolate
  50811. * @returns Interpolated Vector2 value
  50812. */
  50813. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50814. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50815. };
  50816. /**
  50817. * Interpolates a Vector2 cubically
  50818. * @param startValue Start value of the animation curve
  50819. * @param outTangent End tangent of the animation
  50820. * @param endValue End value of the animation curve
  50821. * @param inTangent Start tangent of the animation curve
  50822. * @param gradient Scalar amount to interpolate
  50823. * @returns Interpolated Vector2 value
  50824. */
  50825. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50826. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50827. };
  50828. /**
  50829. * Interpolates a size linearly
  50830. * @param startValue Start value of the animation curve
  50831. * @param endValue End value of the animation curve
  50832. * @param gradient Scalar amount to interpolate
  50833. * @returns Interpolated Size value
  50834. */
  50835. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50836. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50837. };
  50838. /**
  50839. * Interpolates a Color3 linearly
  50840. * @param startValue Start value of the animation curve
  50841. * @param endValue End value of the animation curve
  50842. * @param gradient Scalar amount to interpolate
  50843. * @returns Interpolated Color3 value
  50844. */
  50845. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50846. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50847. };
  50848. /**
  50849. * @hidden Internal use only
  50850. */
  50851. Animation.prototype._getKeyValue = function (value) {
  50852. if (typeof value === "function") {
  50853. return value();
  50854. }
  50855. return value;
  50856. };
  50857. /**
  50858. * @hidden Internal use only
  50859. */
  50860. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50861. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50862. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50863. }
  50864. var keys = this.getKeys();
  50865. // Try to get a hash to find the right key
  50866. 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));
  50867. if (keys[startKeyIndex].frame >= currentFrame) {
  50868. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50869. startKeyIndex--;
  50870. }
  50871. }
  50872. for (var key = startKeyIndex; key < keys.length; key++) {
  50873. var endKey = keys[key + 1];
  50874. if (endKey.frame >= currentFrame) {
  50875. var startKey = keys[key];
  50876. var startValue = this._getKeyValue(startKey.value);
  50877. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50878. return startValue;
  50879. }
  50880. var endValue = this._getKeyValue(endKey.value);
  50881. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50882. var frameDelta = endKey.frame - startKey.frame;
  50883. // gradient : percent of currentFrame between the frame inf and the frame sup
  50884. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50885. // check for easingFunction and correction of gradient
  50886. var easingFunction = this.getEasingFunction();
  50887. if (easingFunction != null) {
  50888. gradient = easingFunction.ease(gradient);
  50889. }
  50890. switch (this.dataType) {
  50891. // Float
  50892. case Animation.ANIMATIONTYPE_FLOAT:
  50893. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50894. switch (loopMode) {
  50895. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50896. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50897. return floatValue;
  50898. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50899. return offsetValue * repeatCount + floatValue;
  50900. }
  50901. break;
  50902. // Quaternion
  50903. case Animation.ANIMATIONTYPE_QUATERNION:
  50904. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50905. switch (loopMode) {
  50906. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50907. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50908. return quatValue;
  50909. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50910. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50911. }
  50912. return quatValue;
  50913. // Vector3
  50914. case Animation.ANIMATIONTYPE_VECTOR3:
  50915. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50916. switch (loopMode) {
  50917. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50918. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50919. return vec3Value;
  50920. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50921. return vec3Value.add(offsetValue.scale(repeatCount));
  50922. }
  50923. // Vector2
  50924. case Animation.ANIMATIONTYPE_VECTOR2:
  50925. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50926. switch (loopMode) {
  50927. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50928. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50929. return vec2Value;
  50930. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50931. return vec2Value.add(offsetValue.scale(repeatCount));
  50932. }
  50933. // Size
  50934. case Animation.ANIMATIONTYPE_SIZE:
  50935. switch (loopMode) {
  50936. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50937. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50938. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50939. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50940. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50941. }
  50942. // Color3
  50943. case Animation.ANIMATIONTYPE_COLOR3:
  50944. switch (loopMode) {
  50945. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50946. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50947. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50948. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50949. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50950. }
  50951. // Matrix
  50952. case Animation.ANIMATIONTYPE_MATRIX:
  50953. switch (loopMode) {
  50954. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50955. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50956. if (Animation.AllowMatricesInterpolation) {
  50957. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50958. }
  50959. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50960. return startValue;
  50961. }
  50962. default:
  50963. break;
  50964. }
  50965. break;
  50966. }
  50967. }
  50968. return this._getKeyValue(keys[keys.length - 1].value);
  50969. };
  50970. /**
  50971. * Defines the function to use to interpolate matrices
  50972. * @param startValue defines the start matrix
  50973. * @param endValue defines the end matrix
  50974. * @param gradient defines the gradient between both matrices
  50975. * @param result defines an optional target matrix where to store the interpolation
  50976. * @returns the interpolated matrix
  50977. */
  50978. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50979. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50980. if (result) {
  50981. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50982. return result;
  50983. }
  50984. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50985. }
  50986. if (result) {
  50987. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50988. return result;
  50989. }
  50990. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50991. };
  50992. /**
  50993. * Makes a copy of the animation
  50994. * @returns Cloned animation
  50995. */
  50996. Animation.prototype.clone = function () {
  50997. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50998. clone.enableBlending = this.enableBlending;
  50999. clone.blendingSpeed = this.blendingSpeed;
  51000. if (this._keys) {
  51001. clone.setKeys(this._keys);
  51002. }
  51003. if (this._ranges) {
  51004. clone._ranges = {};
  51005. for (var name in this._ranges) {
  51006. var range = this._ranges[name];
  51007. if (!range) {
  51008. continue;
  51009. }
  51010. clone._ranges[name] = range.clone();
  51011. }
  51012. }
  51013. return clone;
  51014. };
  51015. /**
  51016. * Sets the key frames of the animation
  51017. * @param values The animation key frames to set
  51018. */
  51019. Animation.prototype.setKeys = function (values) {
  51020. this._keys = values.slice(0);
  51021. };
  51022. /**
  51023. * Serializes the animation to an object
  51024. * @returns Serialized object
  51025. */
  51026. Animation.prototype.serialize = function () {
  51027. var serializationObject = {};
  51028. serializationObject.name = this.name;
  51029. serializationObject.property = this.targetProperty;
  51030. serializationObject.framePerSecond = this.framePerSecond;
  51031. serializationObject.dataType = this.dataType;
  51032. serializationObject.loopBehavior = this.loopMode;
  51033. serializationObject.enableBlending = this.enableBlending;
  51034. serializationObject.blendingSpeed = this.blendingSpeed;
  51035. var dataType = this.dataType;
  51036. serializationObject.keys = [];
  51037. var keys = this.getKeys();
  51038. for (var index = 0; index < keys.length; index++) {
  51039. var animationKey = keys[index];
  51040. var key = {};
  51041. key.frame = animationKey.frame;
  51042. switch (dataType) {
  51043. case Animation.ANIMATIONTYPE_FLOAT:
  51044. key.values = [animationKey.value];
  51045. break;
  51046. case Animation.ANIMATIONTYPE_QUATERNION:
  51047. case Animation.ANIMATIONTYPE_MATRIX:
  51048. case Animation.ANIMATIONTYPE_VECTOR3:
  51049. case Animation.ANIMATIONTYPE_COLOR3:
  51050. key.values = animationKey.value.asArray();
  51051. break;
  51052. }
  51053. serializationObject.keys.push(key);
  51054. }
  51055. serializationObject.ranges = [];
  51056. for (var name in this._ranges) {
  51057. var source = this._ranges[name];
  51058. if (!source) {
  51059. continue;
  51060. }
  51061. var range = {};
  51062. range.name = name;
  51063. range.from = source.from;
  51064. range.to = source.to;
  51065. serializationObject.ranges.push(range);
  51066. }
  51067. return serializationObject;
  51068. };
  51069. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51070. /**
  51071. * Get the float animation type
  51072. */
  51073. get: function () {
  51074. return Animation._ANIMATIONTYPE_FLOAT;
  51075. },
  51076. enumerable: true,
  51077. configurable: true
  51078. });
  51079. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51080. /**
  51081. * Get the Vector3 animation type
  51082. */
  51083. get: function () {
  51084. return Animation._ANIMATIONTYPE_VECTOR3;
  51085. },
  51086. enumerable: true,
  51087. configurable: true
  51088. });
  51089. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51090. /**
  51091. * Get the Vector2 animation type
  51092. */
  51093. get: function () {
  51094. return Animation._ANIMATIONTYPE_VECTOR2;
  51095. },
  51096. enumerable: true,
  51097. configurable: true
  51098. });
  51099. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51100. /**
  51101. * Get the Size animation type
  51102. */
  51103. get: function () {
  51104. return Animation._ANIMATIONTYPE_SIZE;
  51105. },
  51106. enumerable: true,
  51107. configurable: true
  51108. });
  51109. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51110. /**
  51111. * Get the Quaternion animation type
  51112. */
  51113. get: function () {
  51114. return Animation._ANIMATIONTYPE_QUATERNION;
  51115. },
  51116. enumerable: true,
  51117. configurable: true
  51118. });
  51119. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51120. /**
  51121. * Get the Matrix animation type
  51122. */
  51123. get: function () {
  51124. return Animation._ANIMATIONTYPE_MATRIX;
  51125. },
  51126. enumerable: true,
  51127. configurable: true
  51128. });
  51129. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51130. /**
  51131. * Get the Color3 animation type
  51132. */
  51133. get: function () {
  51134. return Animation._ANIMATIONTYPE_COLOR3;
  51135. },
  51136. enumerable: true,
  51137. configurable: true
  51138. });
  51139. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51140. /**
  51141. * Get the Relative Loop Mode
  51142. */
  51143. get: function () {
  51144. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51150. /**
  51151. * Get the Cycle Loop Mode
  51152. */
  51153. get: function () {
  51154. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51155. },
  51156. enumerable: true,
  51157. configurable: true
  51158. });
  51159. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51160. /**
  51161. * Get the Constant Loop Mode
  51162. */
  51163. get: function () {
  51164. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51165. },
  51166. enumerable: true,
  51167. configurable: true
  51168. });
  51169. /** @hidden */
  51170. Animation._UniversalLerp = function (left, right, amount) {
  51171. var constructor = left.constructor;
  51172. if (constructor.Lerp) { // Lerp supported
  51173. return constructor.Lerp(left, right, amount);
  51174. }
  51175. else if (constructor.Slerp) { // Slerp supported
  51176. return constructor.Slerp(left, right, amount);
  51177. }
  51178. else if (left.toFixed) { // Number
  51179. return left * (1.0 - amount) + amount * right;
  51180. }
  51181. else { // Blending not supported
  51182. return right;
  51183. }
  51184. };
  51185. /**
  51186. * Parses an animation object and creates an animation
  51187. * @param parsedAnimation Parsed animation object
  51188. * @returns Animation object
  51189. */
  51190. Animation.Parse = function (parsedAnimation) {
  51191. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51192. var dataType = parsedAnimation.dataType;
  51193. var keys = [];
  51194. var data;
  51195. var index;
  51196. if (parsedAnimation.enableBlending) {
  51197. animation.enableBlending = parsedAnimation.enableBlending;
  51198. }
  51199. if (parsedAnimation.blendingSpeed) {
  51200. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51201. }
  51202. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51203. var key = parsedAnimation.keys[index];
  51204. var inTangent;
  51205. var outTangent;
  51206. switch (dataType) {
  51207. case Animation.ANIMATIONTYPE_FLOAT:
  51208. data = key.values[0];
  51209. if (key.values.length >= 1) {
  51210. inTangent = key.values[1];
  51211. }
  51212. if (key.values.length >= 2) {
  51213. outTangent = key.values[2];
  51214. }
  51215. break;
  51216. case Animation.ANIMATIONTYPE_QUATERNION:
  51217. data = BABYLON.Quaternion.FromArray(key.values);
  51218. if (key.values.length >= 8) {
  51219. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51220. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51221. inTangent = _inTangent;
  51222. }
  51223. }
  51224. if (key.values.length >= 12) {
  51225. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51226. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51227. outTangent = _outTangent;
  51228. }
  51229. }
  51230. break;
  51231. case Animation.ANIMATIONTYPE_MATRIX:
  51232. data = BABYLON.Matrix.FromArray(key.values);
  51233. break;
  51234. case Animation.ANIMATIONTYPE_COLOR3:
  51235. data = BABYLON.Color3.FromArray(key.values);
  51236. break;
  51237. case Animation.ANIMATIONTYPE_VECTOR3:
  51238. default:
  51239. data = BABYLON.Vector3.FromArray(key.values);
  51240. break;
  51241. }
  51242. var keyData = {};
  51243. keyData.frame = key.frame;
  51244. keyData.value = data;
  51245. if (inTangent != undefined) {
  51246. keyData.inTangent = inTangent;
  51247. }
  51248. if (outTangent != undefined) {
  51249. keyData.outTangent = outTangent;
  51250. }
  51251. keys.push(keyData);
  51252. }
  51253. animation.setKeys(keys);
  51254. if (parsedAnimation.ranges) {
  51255. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51256. data = parsedAnimation.ranges[index];
  51257. animation.createRange(data.name, data.from, data.to);
  51258. }
  51259. }
  51260. return animation;
  51261. };
  51262. /**
  51263. * Appends the serialized animations from the source animations
  51264. * @param source Source containing the animations
  51265. * @param destination Target to store the animations
  51266. */
  51267. Animation.AppendSerializedAnimations = function (source, destination) {
  51268. if (source.animations) {
  51269. destination.animations = [];
  51270. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51271. var animation = source.animations[animationIndex];
  51272. destination.animations.push(animation.serialize());
  51273. }
  51274. }
  51275. };
  51276. /**
  51277. * Use matrix interpolation instead of using direct key value when animating matrices
  51278. */
  51279. Animation.AllowMatricesInterpolation = false;
  51280. /**
  51281. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51282. */
  51283. Animation.AllowMatrixDecomposeForInterpolation = true;
  51284. // Statics
  51285. /**
  51286. * Float animation type
  51287. */
  51288. Animation._ANIMATIONTYPE_FLOAT = 0;
  51289. /**
  51290. * Vector3 animation type
  51291. */
  51292. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51293. /**
  51294. * Quaternion animation type
  51295. */
  51296. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51297. /**
  51298. * Matrix animation type
  51299. */
  51300. Animation._ANIMATIONTYPE_MATRIX = 3;
  51301. /**
  51302. * Color3 animation type
  51303. */
  51304. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51305. /**
  51306. * Vector2 animation type
  51307. */
  51308. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51309. /**
  51310. * Size animation type
  51311. */
  51312. Animation._ANIMATIONTYPE_SIZE = 6;
  51313. /**
  51314. * Relative Loop Mode
  51315. */
  51316. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51317. /**
  51318. * Cycle Loop Mode
  51319. */
  51320. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51321. /**
  51322. * Constant Loop Mode
  51323. */
  51324. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51325. return Animation;
  51326. }());
  51327. BABYLON.Animation = Animation;
  51328. })(BABYLON || (BABYLON = {}));
  51329. //# sourceMappingURL=babylon.animation.js.map
  51330. var BABYLON;
  51331. (function (BABYLON) {
  51332. /**
  51333. * This class defines the direct association between an animation and a target
  51334. */
  51335. var TargetedAnimation = /** @class */ (function () {
  51336. function TargetedAnimation() {
  51337. }
  51338. return TargetedAnimation;
  51339. }());
  51340. BABYLON.TargetedAnimation = TargetedAnimation;
  51341. /**
  51342. * Use this class to create coordinated animations on multiple targets
  51343. */
  51344. var AnimationGroup = /** @class */ (function () {
  51345. /**
  51346. * Instantiates a new Animation Group.
  51347. * This helps managing several animations at once.
  51348. * @see http://doc.babylonjs.com/how_to/group
  51349. * @param name Defines the name of the group
  51350. * @param scene Defines the scene the group belongs to
  51351. */
  51352. function AnimationGroup(
  51353. /** The name of the animation group */
  51354. name, scene) {
  51355. if (scene === void 0) { scene = null; }
  51356. this.name = name;
  51357. this._targetedAnimations = new Array();
  51358. this._animatables = new Array();
  51359. this._from = Number.MAX_VALUE;
  51360. this._to = -Number.MAX_VALUE;
  51361. this._speedRatio = 1;
  51362. /**
  51363. * This observable will notify when one animation have ended.
  51364. */
  51365. this.onAnimationEndObservable = new BABYLON.Observable();
  51366. /**
  51367. * This observable will notify when all animations have ended.
  51368. */
  51369. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51370. /**
  51371. * This observable will notify when all animations have paused.
  51372. */
  51373. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51374. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51375. this._scene.animationGroups.push(this);
  51376. }
  51377. Object.defineProperty(AnimationGroup.prototype, "from", {
  51378. /**
  51379. * Gets the first frame
  51380. */
  51381. get: function () {
  51382. return this._from;
  51383. },
  51384. enumerable: true,
  51385. configurable: true
  51386. });
  51387. Object.defineProperty(AnimationGroup.prototype, "to", {
  51388. /**
  51389. * Gets the last frame
  51390. */
  51391. get: function () {
  51392. return this._to;
  51393. },
  51394. enumerable: true,
  51395. configurable: true
  51396. });
  51397. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51398. /**
  51399. * Define if the animations are started
  51400. */
  51401. get: function () {
  51402. return this._isStarted;
  51403. },
  51404. enumerable: true,
  51405. configurable: true
  51406. });
  51407. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51408. /**
  51409. * Gets or sets the speed ratio to use for all animations
  51410. */
  51411. get: function () {
  51412. return this._speedRatio;
  51413. },
  51414. /**
  51415. * Gets or sets the speed ratio to use for all animations
  51416. */
  51417. set: function (value) {
  51418. if (this._speedRatio === value) {
  51419. return;
  51420. }
  51421. this._speedRatio = value;
  51422. for (var index = 0; index < this._animatables.length; index++) {
  51423. var animatable = this._animatables[index];
  51424. animatable.speedRatio = this._speedRatio;
  51425. }
  51426. },
  51427. enumerable: true,
  51428. configurable: true
  51429. });
  51430. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51431. /**
  51432. * Gets the targeted animations for this animation group
  51433. */
  51434. get: function () {
  51435. return this._targetedAnimations;
  51436. },
  51437. enumerable: true,
  51438. configurable: true
  51439. });
  51440. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51441. /**
  51442. * returning the list of animatables controlled by this animation group.
  51443. */
  51444. get: function () {
  51445. return this._animatables;
  51446. },
  51447. enumerable: true,
  51448. configurable: true
  51449. });
  51450. /**
  51451. * Add an animation (with its target) in the group
  51452. * @param animation defines the animation we want to add
  51453. * @param target defines the target of the animation
  51454. * @returns the {BABYLON.TargetedAnimation} object
  51455. */
  51456. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51457. var targetedAnimation = {
  51458. animation: animation,
  51459. target: target
  51460. };
  51461. var keys = animation.getKeys();
  51462. if (this._from > keys[0].frame) {
  51463. this._from = keys[0].frame;
  51464. }
  51465. if (this._to < keys[keys.length - 1].frame) {
  51466. this._to = keys[keys.length - 1].frame;
  51467. }
  51468. this._targetedAnimations.push(targetedAnimation);
  51469. return targetedAnimation;
  51470. };
  51471. /**
  51472. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51473. * It can add constant keys at begin or end
  51474. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51475. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51476. * @returns the animation group
  51477. */
  51478. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51479. if (beginFrame === void 0) { beginFrame = null; }
  51480. if (endFrame === void 0) { endFrame = null; }
  51481. if (beginFrame == null)
  51482. beginFrame = this._from;
  51483. if (endFrame == null)
  51484. endFrame = this._to;
  51485. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51486. var targetedAnimation = this._targetedAnimations[index];
  51487. var keys = targetedAnimation.animation.getKeys();
  51488. var startKey = keys[0];
  51489. var endKey = keys[keys.length - 1];
  51490. if (startKey.frame > beginFrame) {
  51491. var newKey = {
  51492. frame: beginFrame,
  51493. value: startKey.value,
  51494. inTangent: startKey.inTangent,
  51495. outTangent: startKey.outTangent,
  51496. interpolation: startKey.interpolation
  51497. };
  51498. keys.splice(0, 0, newKey);
  51499. }
  51500. if (endKey.frame < endFrame) {
  51501. var newKey = {
  51502. frame: endFrame,
  51503. value: endKey.value,
  51504. inTangent: endKey.outTangent,
  51505. outTangent: endKey.outTangent,
  51506. interpolation: endKey.interpolation
  51507. };
  51508. keys.push(newKey);
  51509. }
  51510. }
  51511. this._from = beginFrame;
  51512. this._to = endFrame;
  51513. return this;
  51514. };
  51515. /**
  51516. * Start all animations on given targets
  51517. * @param loop defines if animations must loop
  51518. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51519. * @param from defines the from key (optional)
  51520. * @param to defines the to key (optional)
  51521. * @returns the current animation group
  51522. */
  51523. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51524. var _this = this;
  51525. if (loop === void 0) { loop = false; }
  51526. if (speedRatio === void 0) { speedRatio = 1; }
  51527. if (this._isStarted || this._targetedAnimations.length === 0) {
  51528. return this;
  51529. }
  51530. var _loop_1 = function (targetedAnimation) {
  51531. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51532. animatable.onAnimationEnd = function () {
  51533. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51534. _this._checkAnimationGroupEnded(animatable);
  51535. };
  51536. this_1._animatables.push(animatable);
  51537. };
  51538. var this_1 = this;
  51539. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51540. var targetedAnimation = _a[_i];
  51541. _loop_1(targetedAnimation);
  51542. }
  51543. this._speedRatio = speedRatio;
  51544. this._isStarted = true;
  51545. return this;
  51546. };
  51547. /**
  51548. * Pause all animations
  51549. * @returns the animation group
  51550. */
  51551. AnimationGroup.prototype.pause = function () {
  51552. if (!this._isStarted) {
  51553. return this;
  51554. }
  51555. for (var index = 0; index < this._animatables.length; index++) {
  51556. var animatable = this._animatables[index];
  51557. animatable.pause();
  51558. }
  51559. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51560. return this;
  51561. };
  51562. /**
  51563. * Play all animations to initial state
  51564. * This function will start() the animations if they were not started or will restart() them if they were paused
  51565. * @param loop defines if animations must loop
  51566. * @returns the animation group
  51567. */
  51568. AnimationGroup.prototype.play = function (loop) {
  51569. // only if all animatables are ready and exist
  51570. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51571. if (loop !== undefined) {
  51572. for (var index = 0; index < this._animatables.length; index++) {
  51573. var animatable = this._animatables[index];
  51574. animatable.loopAnimation = loop;
  51575. }
  51576. }
  51577. this.restart();
  51578. }
  51579. else {
  51580. this.stop();
  51581. this.start(loop, this._speedRatio);
  51582. }
  51583. return this;
  51584. };
  51585. /**
  51586. * Reset all animations to initial state
  51587. * @returns the animation group
  51588. */
  51589. AnimationGroup.prototype.reset = function () {
  51590. if (!this._isStarted) {
  51591. return this;
  51592. }
  51593. for (var index = 0; index < this._animatables.length; index++) {
  51594. var animatable = this._animatables[index];
  51595. animatable.reset();
  51596. }
  51597. return this;
  51598. };
  51599. /**
  51600. * Restart animations from key 0
  51601. * @returns the animation group
  51602. */
  51603. AnimationGroup.prototype.restart = function () {
  51604. if (!this._isStarted) {
  51605. return this;
  51606. }
  51607. for (var index = 0; index < this._animatables.length; index++) {
  51608. var animatable = this._animatables[index];
  51609. animatable.restart();
  51610. }
  51611. return this;
  51612. };
  51613. /**
  51614. * Stop all animations
  51615. * @returns the animation group
  51616. */
  51617. AnimationGroup.prototype.stop = function () {
  51618. if (!this._isStarted) {
  51619. return this;
  51620. }
  51621. var list = this._animatables.slice();
  51622. for (var index = 0; index < list.length; index++) {
  51623. list[index].stop();
  51624. }
  51625. this._isStarted = false;
  51626. return this;
  51627. };
  51628. /**
  51629. * Set animation weight for all animatables
  51630. * @param weight defines the weight to use
  51631. * @return the animationGroup
  51632. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51633. */
  51634. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51635. for (var index = 0; index < this._animatables.length; index++) {
  51636. var animatable = this._animatables[index];
  51637. animatable.weight = weight;
  51638. }
  51639. return this;
  51640. };
  51641. /**
  51642. * Synchronize and normalize all animatables with a source animatable
  51643. * @param root defines the root animatable to synchronize with
  51644. * @return the animationGroup
  51645. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51646. */
  51647. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51648. for (var index = 0; index < this._animatables.length; index++) {
  51649. var animatable = this._animatables[index];
  51650. animatable.syncWith(root);
  51651. }
  51652. return this;
  51653. };
  51654. /**
  51655. * Goes to a specific frame in this animation group
  51656. * @param frame the frame number to go to
  51657. * @return the animationGroup
  51658. */
  51659. AnimationGroup.prototype.goToFrame = function (frame) {
  51660. if (!this._isStarted) {
  51661. return this;
  51662. }
  51663. for (var index = 0; index < this._animatables.length; index++) {
  51664. var animatable = this._animatables[index];
  51665. animatable.goToFrame(frame);
  51666. }
  51667. return this;
  51668. };
  51669. /**
  51670. * Dispose all associated resources
  51671. */
  51672. AnimationGroup.prototype.dispose = function () {
  51673. this._targetedAnimations = [];
  51674. this._animatables = [];
  51675. var index = this._scene.animationGroups.indexOf(this);
  51676. if (index > -1) {
  51677. this._scene.animationGroups.splice(index, 1);
  51678. }
  51679. };
  51680. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51681. // animatable should be taken out of the array
  51682. var idx = this._animatables.indexOf(animatable);
  51683. if (idx > -1) {
  51684. this._animatables.splice(idx, 1);
  51685. }
  51686. // all animatables were removed? animation group ended!
  51687. if (this._animatables.length === 0) {
  51688. this._isStarted = false;
  51689. this.onAnimationGroupEndObservable.notifyObservers(this);
  51690. }
  51691. };
  51692. // Statics
  51693. /**
  51694. * Returns a new AnimationGroup object parsed from the source provided.
  51695. * @param parsedAnimationGroup defines the source
  51696. * @param scene defines the scene that will receive the animationGroup
  51697. * @returns a new AnimationGroup
  51698. */
  51699. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51700. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51701. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51702. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51703. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51704. var id = targetedAnimation.targetId;
  51705. var targetNode = scene.getNodeByID(id);
  51706. if (targetNode != null)
  51707. animationGroup.addTargetedAnimation(animation, targetNode);
  51708. }
  51709. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51710. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51711. return animationGroup;
  51712. };
  51713. /**
  51714. * Returns the string "AnimationGroup"
  51715. * @returns "AnimationGroup"
  51716. */
  51717. AnimationGroup.prototype.getClassName = function () {
  51718. return "AnimationGroup";
  51719. };
  51720. /**
  51721. * Creates a detailled string about the object
  51722. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51723. * @returns a string representing the object
  51724. */
  51725. AnimationGroup.prototype.toString = function (fullDetails) {
  51726. var ret = "Name: " + this.name;
  51727. ret += ", type: " + this.getClassName();
  51728. if (fullDetails) {
  51729. ret += ", from: " + this._from;
  51730. ret += ", to: " + this._to;
  51731. ret += ", isStarted: " + this._isStarted;
  51732. ret += ", speedRatio: " + this._speedRatio;
  51733. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51734. ret += ", animatables length: " + this._animatables;
  51735. }
  51736. return ret;
  51737. };
  51738. return AnimationGroup;
  51739. }());
  51740. BABYLON.AnimationGroup = AnimationGroup;
  51741. })(BABYLON || (BABYLON = {}));
  51742. //# sourceMappingURL=babylon.animationGroup.js.map
  51743. var BABYLON;
  51744. (function (BABYLON) {
  51745. // Static values to help the garbage collector
  51746. // Quaternion
  51747. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51748. // Vector3
  51749. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51750. // Vector2
  51751. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51752. // Size
  51753. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51754. // Color3
  51755. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51756. /**
  51757. * Defines a runtime animation
  51758. */
  51759. var RuntimeAnimation = /** @class */ (function () {
  51760. /**
  51761. * Create a new RuntimeAnimation object
  51762. * @param target defines the target of the animation
  51763. * @param animation defines the source animation object
  51764. * @param scene defines the hosting scene
  51765. * @param host defines the initiating Animatable
  51766. */
  51767. function RuntimeAnimation(target, animation, scene, host) {
  51768. var _this = this;
  51769. this._events = new Array();
  51770. /**
  51771. * The current frame of the runtime animation
  51772. */
  51773. this._currentFrame = 0;
  51774. /**
  51775. * The original value of the runtime animation
  51776. */
  51777. this._originalValue = new Array();
  51778. /**
  51779. * The offsets cache of the runtime animation
  51780. */
  51781. this._offsetsCache = {};
  51782. /**
  51783. * The high limits cache of the runtime animation
  51784. */
  51785. this._highLimitsCache = {};
  51786. /**
  51787. * Specifies if the runtime animation has been stopped
  51788. */
  51789. this._stopped = false;
  51790. /**
  51791. * The blending factor of the runtime animation
  51792. */
  51793. this._blendingFactor = 0;
  51794. /**
  51795. * The target path of the runtime animation
  51796. */
  51797. this._targetPath = "";
  51798. /**
  51799. * The weight of the runtime animation
  51800. */
  51801. this._weight = 1.0;
  51802. /**
  51803. * The ratio offset of the runtime animation
  51804. */
  51805. this._ratioOffset = 0;
  51806. /**
  51807. * The previous delay of the runtime animation
  51808. */
  51809. this._previousDelay = 0;
  51810. /**
  51811. * The previous ratio of the runtime animation
  51812. */
  51813. this._previousRatio = 0;
  51814. this._animation = animation;
  51815. this._target = target;
  51816. this._scene = scene;
  51817. this._host = host;
  51818. animation._runtimeAnimations.push(this);
  51819. // Cloning events locally
  51820. var events = animation.getEvents();
  51821. if (events && events.length > 0) {
  51822. events.forEach(function (e) {
  51823. _this._events.push(e._clone());
  51824. });
  51825. }
  51826. }
  51827. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51828. /**
  51829. * Gets the current frame of the runtime animation
  51830. */
  51831. get: function () {
  51832. return this._currentFrame;
  51833. },
  51834. enumerable: true,
  51835. configurable: true
  51836. });
  51837. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51838. /**
  51839. * Gets the weight of the runtime animation
  51840. */
  51841. get: function () {
  51842. return this._weight;
  51843. },
  51844. enumerable: true,
  51845. configurable: true
  51846. });
  51847. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51848. /**
  51849. * Gets the current value of the runtime animation
  51850. */
  51851. get: function () {
  51852. return this._currentValue;
  51853. },
  51854. enumerable: true,
  51855. configurable: true
  51856. });
  51857. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51858. /**
  51859. * Gets the target path of the runtime animation
  51860. */
  51861. get: function () {
  51862. return this._targetPath;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51868. /**
  51869. * Gets the actual target of the runtime animation
  51870. */
  51871. get: function () {
  51872. return this._activeTarget;
  51873. },
  51874. enumerable: true,
  51875. configurable: true
  51876. });
  51877. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51878. /**
  51879. * Gets the animation from the runtime animation
  51880. */
  51881. get: function () {
  51882. return this._animation;
  51883. },
  51884. enumerable: true,
  51885. configurable: true
  51886. });
  51887. /**
  51888. * Resets the runtime animation to the beginning
  51889. * @param restoreOriginal defines whether to restore the target property to the original value
  51890. */
  51891. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51892. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51893. if (restoreOriginal) {
  51894. if (this._target instanceof Array) {
  51895. var index = 0;
  51896. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51897. var target = _a[_i];
  51898. if (this._originalValue[index] !== undefined) {
  51899. this._setValue(target, this._originalValue[index], -1);
  51900. }
  51901. index++;
  51902. }
  51903. }
  51904. else {
  51905. if (this._originalValue[0] !== undefined) {
  51906. this._setValue(this._target, this._originalValue[0], -1);
  51907. }
  51908. }
  51909. }
  51910. this._offsetsCache = {};
  51911. this._highLimitsCache = {};
  51912. this._currentFrame = 0;
  51913. this._blendingFactor = 0;
  51914. this._originalValue = new Array();
  51915. // Events
  51916. for (var index = 0; index < this._events.length; index++) {
  51917. this._events[index].isDone = false;
  51918. }
  51919. };
  51920. /**
  51921. * Specifies if the runtime animation is stopped
  51922. * @returns Boolean specifying if the runtime animation is stopped
  51923. */
  51924. RuntimeAnimation.prototype.isStopped = function () {
  51925. return this._stopped;
  51926. };
  51927. /**
  51928. * Disposes of the runtime animation
  51929. */
  51930. RuntimeAnimation.prototype.dispose = function () {
  51931. var index = this._animation.runtimeAnimations.indexOf(this);
  51932. if (index > -1) {
  51933. this._animation.runtimeAnimations.splice(index, 1);
  51934. }
  51935. };
  51936. /**
  51937. * Interpolates the animation from the current frame
  51938. * @param currentFrame The frame to interpolate the animation to
  51939. * @param repeatCount The number of times that the animation should loop
  51940. * @param loopMode The type of looping mode to use
  51941. * @param offsetValue Animation offset value
  51942. * @param highLimitValue The high limit value
  51943. * @returns The interpolated value
  51944. */
  51945. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51946. this._currentFrame = currentFrame;
  51947. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51948. this._workValue = BABYLON.Matrix.Zero();
  51949. }
  51950. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51951. };
  51952. /**
  51953. * Apply the interpolated value to the target
  51954. * @param currentValue defines the value computed by the animation
  51955. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51956. */
  51957. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51958. if (weight === void 0) { weight = 1.0; }
  51959. if (this._target instanceof Array) {
  51960. var index = 0;
  51961. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51962. var target = _a[_i];
  51963. this._setValue(target, currentValue, weight, index);
  51964. index++;
  51965. }
  51966. }
  51967. else {
  51968. this._setValue(this._target, currentValue, weight);
  51969. }
  51970. };
  51971. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51972. if (targetIndex === void 0) { targetIndex = 0; }
  51973. // Set value
  51974. var path;
  51975. var destination;
  51976. var targetPropertyPath = this._animation.targetPropertyPath;
  51977. if (targetPropertyPath.length > 1) {
  51978. var property = target[targetPropertyPath[0]];
  51979. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51980. property = property[targetPropertyPath[index]];
  51981. }
  51982. path = targetPropertyPath[targetPropertyPath.length - 1];
  51983. destination = property;
  51984. }
  51985. else {
  51986. path = targetPropertyPath[0];
  51987. destination = target;
  51988. }
  51989. this._targetPath = path;
  51990. this._activeTarget = destination;
  51991. this._weight = weight;
  51992. if (this._originalValue[targetIndex] === undefined) {
  51993. var originalValue = void 0;
  51994. if (destination.getRestPose && path === "_matrix") { // For bones
  51995. originalValue = destination.getRestPose();
  51996. }
  51997. else {
  51998. originalValue = destination[path];
  51999. }
  52000. if (originalValue && originalValue.clone) {
  52001. this._originalValue[targetIndex] = originalValue.clone();
  52002. }
  52003. else {
  52004. this._originalValue[targetIndex] = originalValue;
  52005. }
  52006. }
  52007. // Blending
  52008. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52009. if (enableBlending && this._blendingFactor <= 1.0) {
  52010. if (!this._originalBlendValue) {
  52011. var originalValue = destination[path];
  52012. if (originalValue.clone) {
  52013. this._originalBlendValue = originalValue.clone();
  52014. }
  52015. else {
  52016. this._originalBlendValue = originalValue;
  52017. }
  52018. }
  52019. if (this._originalBlendValue.m) { // Matrix
  52020. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52021. if (this._currentValue) {
  52022. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52023. }
  52024. else {
  52025. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52026. }
  52027. }
  52028. else {
  52029. if (this._currentValue) {
  52030. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52031. }
  52032. else {
  52033. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52034. }
  52035. }
  52036. }
  52037. else {
  52038. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52039. }
  52040. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52041. this._blendingFactor += blendingSpeed;
  52042. }
  52043. else {
  52044. this._currentValue = currentValue;
  52045. }
  52046. if (weight !== -1.0) {
  52047. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52048. }
  52049. else {
  52050. destination[path] = this._currentValue;
  52051. }
  52052. if (target.markAsDirty) {
  52053. target.markAsDirty(this._animation.targetProperty);
  52054. }
  52055. };
  52056. /**
  52057. * Gets the loop pmode of the runtime animation
  52058. * @returns Loop Mode
  52059. */
  52060. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52061. if (this._target && this._target.animationPropertiesOverride) {
  52062. return this._target.animationPropertiesOverride.loopMode;
  52063. }
  52064. return this._animation.loopMode;
  52065. };
  52066. /**
  52067. * Move the current animation to a given frame
  52068. * @param frame defines the frame to move to
  52069. */
  52070. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52071. var keys = this._animation.getKeys();
  52072. if (frame < keys[0].frame) {
  52073. frame = keys[0].frame;
  52074. }
  52075. else if (frame > keys[keys.length - 1].frame) {
  52076. frame = keys[keys.length - 1].frame;
  52077. }
  52078. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52079. this.setValue(currentValue, -1);
  52080. };
  52081. /**
  52082. * @hidden Internal use only
  52083. */
  52084. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52085. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52086. this._ratioOffset = this._previousRatio - newRatio;
  52087. };
  52088. /**
  52089. * Execute the current animation
  52090. * @param delay defines the delay to add to the current frame
  52091. * @param from defines the lower bound of the animation range
  52092. * @param to defines the upper bound of the animation range
  52093. * @param loop defines if the current animation must loop
  52094. * @param speedRatio defines the current speed ratio
  52095. * @param weight defines the weight of the animation (default is -1 so no weight)
  52096. * @returns a boolean indicating if the animation is running
  52097. */
  52098. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52099. if (weight === void 0) { weight = -1.0; }
  52100. var targetPropertyPath = this._animation.targetPropertyPath;
  52101. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52102. this._stopped = true;
  52103. return false;
  52104. }
  52105. var returnValue = true;
  52106. var keys = this._animation.getKeys();
  52107. // Adding a start key at frame 0 if missing
  52108. if (keys[0].frame !== 0) {
  52109. var newKey = { frame: 0, value: keys[0].value };
  52110. keys.splice(0, 0, newKey);
  52111. }
  52112. // Adding a duplicate key when there is only one key at frame zero
  52113. else if (keys.length === 1) {
  52114. var newKey = { frame: 0.001, value: keys[0].value };
  52115. keys.push(newKey);
  52116. }
  52117. // Check limits
  52118. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52119. from = keys[0].frame;
  52120. }
  52121. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52122. to = keys[keys.length - 1].frame;
  52123. }
  52124. //to and from cannot be the same key
  52125. if (from === to) {
  52126. if (from > keys[0].frame) {
  52127. from--;
  52128. }
  52129. else if (to < keys[keys.length - 1].frame) {
  52130. to++;
  52131. }
  52132. }
  52133. // Compute ratio
  52134. var range = to - from;
  52135. var offsetValue;
  52136. // ratio represents the frame delta between from and to
  52137. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52138. var highLimitValue = 0;
  52139. this._previousDelay = delay;
  52140. this._previousRatio = ratio;
  52141. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52142. returnValue = false;
  52143. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52144. }
  52145. else {
  52146. // Get max value if required
  52147. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52148. var keyOffset = to.toString() + from.toString();
  52149. if (!this._offsetsCache[keyOffset]) {
  52150. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52151. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52152. switch (this._animation.dataType) {
  52153. // Float
  52154. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52155. this._offsetsCache[keyOffset] = toValue - fromValue;
  52156. break;
  52157. // Quaternion
  52158. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52159. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52160. break;
  52161. // Vector3
  52162. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52163. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52164. // Vector2
  52165. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52166. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52167. // Size
  52168. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52169. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52170. // Color3
  52171. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52172. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52173. default:
  52174. break;
  52175. }
  52176. this._highLimitsCache[keyOffset] = toValue;
  52177. }
  52178. highLimitValue = this._highLimitsCache[keyOffset];
  52179. offsetValue = this._offsetsCache[keyOffset];
  52180. }
  52181. }
  52182. if (offsetValue === undefined) {
  52183. switch (this._animation.dataType) {
  52184. // Float
  52185. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52186. offsetValue = 0;
  52187. break;
  52188. // Quaternion
  52189. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52190. offsetValue = _staticOffsetValueQuaternion;
  52191. break;
  52192. // Vector3
  52193. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52194. offsetValue = _staticOffsetValueVector3;
  52195. break;
  52196. // Vector2
  52197. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52198. offsetValue = _staticOffsetValueVector2;
  52199. break;
  52200. // Size
  52201. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52202. offsetValue = _staticOffsetValueSize;
  52203. break;
  52204. // Color3
  52205. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52206. offsetValue = _staticOffsetValueColor3;
  52207. }
  52208. }
  52209. // Compute value
  52210. var repeatCount = (ratio / range) >> 0;
  52211. var currentFrame = returnValue ? from + ratio % range : to;
  52212. // Need to normalize?
  52213. if (this._host && this._host.syncRoot) {
  52214. var syncRoot = this._host.syncRoot;
  52215. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52216. currentFrame = from + (to - from) * hostNormalizedFrame;
  52217. }
  52218. // Reset events if looping
  52219. var events = this._events;
  52220. if (range > 0 && this.currentFrame > currentFrame ||
  52221. range < 0 && this.currentFrame < currentFrame) {
  52222. // Need to reset animation events
  52223. for (var index = 0; index < events.length; index++) {
  52224. if (!events[index].onlyOnce) {
  52225. // reset event, the animation is looping
  52226. events[index].isDone = false;
  52227. }
  52228. }
  52229. }
  52230. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52231. // Set value
  52232. this.setValue(currentValue, weight);
  52233. // Check events
  52234. for (var index = 0; index < events.length; index++) {
  52235. // Make sure current frame has passed event frame and that event frame is within the current range
  52236. // Also, handle both forward and reverse animations
  52237. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52238. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52239. var event = events[index];
  52240. if (!event.isDone) {
  52241. // If event should be done only once, remove it.
  52242. if (event.onlyOnce) {
  52243. events.splice(index, 1);
  52244. index--;
  52245. }
  52246. event.isDone = true;
  52247. event.action(currentFrame);
  52248. } // Don't do anything if the event has already be done.
  52249. }
  52250. }
  52251. if (!returnValue) {
  52252. this._stopped = true;
  52253. }
  52254. return returnValue;
  52255. };
  52256. return RuntimeAnimation;
  52257. }());
  52258. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52259. })(BABYLON || (BABYLON = {}));
  52260. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52261. var BABYLON;
  52262. (function (BABYLON) {
  52263. /**
  52264. * Class used to store an actual running animation
  52265. */
  52266. var Animatable = /** @class */ (function () {
  52267. /**
  52268. * Creates a new Animatable
  52269. * @param scene defines the hosting scene
  52270. * @param target defines the target object
  52271. * @param fromFrame defines the starting frame number (default is 0)
  52272. * @param toFrame defines the ending frame number (default is 100)
  52273. * @param loopAnimation defines if the animation must loop (default is false)
  52274. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52275. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52276. * @param animations defines a group of animation to add to the new Animatable
  52277. */
  52278. function Animatable(scene,
  52279. /** defines the target object */
  52280. target,
  52281. /** defines the starting frame number (default is 0) */
  52282. fromFrame,
  52283. /** defines the ending frame number (default is 100) */
  52284. toFrame,
  52285. /** defines if the animation must loop (default is false) */
  52286. loopAnimation, speedRatio,
  52287. /** defines a callback to call when animation ends if it is not looping */
  52288. onAnimationEnd, animations) {
  52289. if (fromFrame === void 0) { fromFrame = 0; }
  52290. if (toFrame === void 0) { toFrame = 100; }
  52291. if (loopAnimation === void 0) { loopAnimation = false; }
  52292. if (speedRatio === void 0) { speedRatio = 1.0; }
  52293. this.target = target;
  52294. this.fromFrame = fromFrame;
  52295. this.toFrame = toFrame;
  52296. this.loopAnimation = loopAnimation;
  52297. this.onAnimationEnd = onAnimationEnd;
  52298. this._localDelayOffset = null;
  52299. this._pausedDelay = null;
  52300. this._runtimeAnimations = new Array();
  52301. this._paused = false;
  52302. this._speedRatio = 1;
  52303. this._weight = -1.0;
  52304. /**
  52305. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52306. * This will only apply for non looping animation (default is true)
  52307. */
  52308. this.disposeOnEnd = true;
  52309. /**
  52310. * Gets a boolean indicating if the animation has started
  52311. */
  52312. this.animationStarted = false;
  52313. /**
  52314. * Observer raised when the animation ends
  52315. */
  52316. this.onAnimationEndObservable = new BABYLON.Observable();
  52317. this._scene = scene;
  52318. if (animations) {
  52319. this.appendAnimations(target, animations);
  52320. }
  52321. this._speedRatio = speedRatio;
  52322. scene._activeAnimatables.push(this);
  52323. }
  52324. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52325. /**
  52326. * Gets the root Animatable used to synchronize and normalize animations
  52327. */
  52328. get: function () {
  52329. return this._syncRoot;
  52330. },
  52331. enumerable: true,
  52332. configurable: true
  52333. });
  52334. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52335. /**
  52336. * Gets the current frame of the first RuntimeAnimation
  52337. * Used to synchronize Animatables
  52338. */
  52339. get: function () {
  52340. if (this._runtimeAnimations.length === 0) {
  52341. return 0;
  52342. }
  52343. return this._runtimeAnimations[0].currentFrame;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. Object.defineProperty(Animatable.prototype, "weight", {
  52349. /**
  52350. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52351. */
  52352. get: function () {
  52353. return this._weight;
  52354. },
  52355. set: function (value) {
  52356. if (value === -1) { // -1 is ok and means no weight
  52357. this._weight = -1;
  52358. return;
  52359. }
  52360. // Else weight must be in [0, 1] range
  52361. this._weight = Math.min(Math.max(value, 0), 1.0);
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52367. /**
  52368. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52369. */
  52370. get: function () {
  52371. return this._speedRatio;
  52372. },
  52373. set: function (value) {
  52374. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52375. var animation = this._runtimeAnimations[index];
  52376. animation._prepareForSpeedRatioChange(value);
  52377. }
  52378. this._speedRatio = value;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. // Methods
  52384. /**
  52385. * Synchronize and normalize current Animatable with a source Animatable
  52386. * This is useful when using animation weights and when animations are not of the same length
  52387. * @param root defines the root Animatable to synchronize with
  52388. * @returns the current Animatable
  52389. */
  52390. Animatable.prototype.syncWith = function (root) {
  52391. this._syncRoot = root;
  52392. if (root) {
  52393. // Make sure this animatable will animate after the root
  52394. var index = this._scene._activeAnimatables.indexOf(this);
  52395. if (index > -1) {
  52396. this._scene._activeAnimatables.splice(index, 1);
  52397. this._scene._activeAnimatables.push(this);
  52398. }
  52399. }
  52400. return this;
  52401. };
  52402. /**
  52403. * Gets the list of runtime animations
  52404. * @returns an array of RuntimeAnimation
  52405. */
  52406. Animatable.prototype.getAnimations = function () {
  52407. return this._runtimeAnimations;
  52408. };
  52409. /**
  52410. * Adds more animations to the current animatable
  52411. * @param target defines the target of the animations
  52412. * @param animations defines the new animations to add
  52413. */
  52414. Animatable.prototype.appendAnimations = function (target, animations) {
  52415. for (var index = 0; index < animations.length; index++) {
  52416. var animation = animations[index];
  52417. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52418. }
  52419. };
  52420. /**
  52421. * Gets the source animation for a specific property
  52422. * @param property defines the propertyu to look for
  52423. * @returns null or the source animation for the given property
  52424. */
  52425. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52426. var runtimeAnimations = this._runtimeAnimations;
  52427. for (var index = 0; index < runtimeAnimations.length; index++) {
  52428. if (runtimeAnimations[index].animation.targetProperty === property) {
  52429. return runtimeAnimations[index].animation;
  52430. }
  52431. }
  52432. return null;
  52433. };
  52434. /**
  52435. * Gets the runtime animation for a specific property
  52436. * @param property defines the propertyu to look for
  52437. * @returns null or the runtime animation for the given property
  52438. */
  52439. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52440. var runtimeAnimations = this._runtimeAnimations;
  52441. for (var index = 0; index < runtimeAnimations.length; index++) {
  52442. if (runtimeAnimations[index].animation.targetProperty === property) {
  52443. return runtimeAnimations[index];
  52444. }
  52445. }
  52446. return null;
  52447. };
  52448. /**
  52449. * Resets the animatable to its original state
  52450. */
  52451. Animatable.prototype.reset = function () {
  52452. var runtimeAnimations = this._runtimeAnimations;
  52453. for (var index = 0; index < runtimeAnimations.length; index++) {
  52454. runtimeAnimations[index].reset(true);
  52455. }
  52456. this._localDelayOffset = null;
  52457. this._pausedDelay = null;
  52458. };
  52459. /**
  52460. * Allows the animatable to blend with current running animations
  52461. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52462. * @param blendingSpeed defines the blending speed to use
  52463. */
  52464. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52465. var runtimeAnimations = this._runtimeAnimations;
  52466. for (var index = 0; index < runtimeAnimations.length; index++) {
  52467. runtimeAnimations[index].animation.enableBlending = true;
  52468. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52469. }
  52470. };
  52471. /**
  52472. * Disable animation blending
  52473. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52474. */
  52475. Animatable.prototype.disableBlending = function () {
  52476. var runtimeAnimations = this._runtimeAnimations;
  52477. for (var index = 0; index < runtimeAnimations.length; index++) {
  52478. runtimeAnimations[index].animation.enableBlending = false;
  52479. }
  52480. };
  52481. /**
  52482. * Jump directly to a given frame
  52483. * @param frame defines the frame to jump to
  52484. */
  52485. Animatable.prototype.goToFrame = function (frame) {
  52486. var runtimeAnimations = this._runtimeAnimations;
  52487. if (runtimeAnimations[0]) {
  52488. var fps = runtimeAnimations[0].animation.framePerSecond;
  52489. var currentFrame = runtimeAnimations[0].currentFrame;
  52490. var adjustTime = frame - currentFrame;
  52491. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52492. if (this._localDelayOffset === null) {
  52493. this._localDelayOffset = 0;
  52494. }
  52495. this._localDelayOffset -= delay;
  52496. }
  52497. for (var index = 0; index < runtimeAnimations.length; index++) {
  52498. runtimeAnimations[index].goToFrame(frame);
  52499. }
  52500. };
  52501. /**
  52502. * Pause the animation
  52503. */
  52504. Animatable.prototype.pause = function () {
  52505. if (this._paused) {
  52506. return;
  52507. }
  52508. this._paused = true;
  52509. };
  52510. /**
  52511. * Restart the animation
  52512. */
  52513. Animatable.prototype.restart = function () {
  52514. this._paused = false;
  52515. };
  52516. Animatable.prototype._raiseOnAnimationEnd = function () {
  52517. if (this.onAnimationEnd) {
  52518. this.onAnimationEnd();
  52519. }
  52520. this.onAnimationEndObservable.notifyObservers(this);
  52521. };
  52522. /**
  52523. * Stop and delete the current animation
  52524. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52525. * @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)
  52526. */
  52527. Animatable.prototype.stop = function (animationName, targetMask) {
  52528. if (animationName || targetMask) {
  52529. var idx = this._scene._activeAnimatables.indexOf(this);
  52530. if (idx > -1) {
  52531. var runtimeAnimations = this._runtimeAnimations;
  52532. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52533. var runtimeAnimation = runtimeAnimations[index];
  52534. if (animationName && runtimeAnimation.animation.name != animationName) {
  52535. continue;
  52536. }
  52537. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52538. continue;
  52539. }
  52540. runtimeAnimation.dispose();
  52541. runtimeAnimations.splice(index, 1);
  52542. }
  52543. if (runtimeAnimations.length == 0) {
  52544. this._scene._activeAnimatables.splice(idx, 1);
  52545. this._raiseOnAnimationEnd();
  52546. }
  52547. }
  52548. }
  52549. else {
  52550. var index = this._scene._activeAnimatables.indexOf(this);
  52551. if (index > -1) {
  52552. this._scene._activeAnimatables.splice(index, 1);
  52553. var runtimeAnimations = this._runtimeAnimations;
  52554. for (var index = 0; index < runtimeAnimations.length; index++) {
  52555. runtimeAnimations[index].dispose();
  52556. }
  52557. this._raiseOnAnimationEnd();
  52558. }
  52559. }
  52560. };
  52561. /**
  52562. * Wait asynchronously for the animation to end
  52563. * @returns a promise which will be fullfilled when the animation ends
  52564. */
  52565. Animatable.prototype.waitAsync = function () {
  52566. var _this = this;
  52567. return new Promise(function (resolve, reject) {
  52568. _this.onAnimationEndObservable.add(function () {
  52569. resolve(_this);
  52570. }, undefined, undefined, _this, true);
  52571. });
  52572. };
  52573. /** @hidden */
  52574. Animatable.prototype._animate = function (delay) {
  52575. if (this._paused) {
  52576. this.animationStarted = false;
  52577. if (this._pausedDelay === null) {
  52578. this._pausedDelay = delay;
  52579. }
  52580. return true;
  52581. }
  52582. if (this._localDelayOffset === null) {
  52583. this._localDelayOffset = delay;
  52584. this._pausedDelay = null;
  52585. }
  52586. else if (this._pausedDelay !== null) {
  52587. this._localDelayOffset += delay - this._pausedDelay;
  52588. this._pausedDelay = null;
  52589. }
  52590. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52591. return true;
  52592. }
  52593. // Animating
  52594. var running = false;
  52595. var runtimeAnimations = this._runtimeAnimations;
  52596. var index;
  52597. for (index = 0; index < runtimeAnimations.length; index++) {
  52598. var animation = runtimeAnimations[index];
  52599. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52600. running = running || isRunning;
  52601. }
  52602. this.animationStarted = running;
  52603. if (!running) {
  52604. if (this.disposeOnEnd) {
  52605. // Remove from active animatables
  52606. index = this._scene._activeAnimatables.indexOf(this);
  52607. this._scene._activeAnimatables.splice(index, 1);
  52608. // Dispose all runtime animations
  52609. for (index = 0; index < runtimeAnimations.length; index++) {
  52610. runtimeAnimations[index].dispose();
  52611. }
  52612. }
  52613. this._raiseOnAnimationEnd();
  52614. if (this.disposeOnEnd) {
  52615. this.onAnimationEnd = null;
  52616. this.onAnimationEndObservable.clear();
  52617. }
  52618. }
  52619. return running;
  52620. };
  52621. return Animatable;
  52622. }());
  52623. BABYLON.Animatable = Animatable;
  52624. })(BABYLON || (BABYLON = {}));
  52625. //# sourceMappingURL=babylon.animatable.js.map
  52626. var BABYLON;
  52627. (function (BABYLON) {
  52628. /**
  52629. * Base class used for every default easing function.
  52630. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52631. */
  52632. var EasingFunction = /** @class */ (function () {
  52633. function EasingFunction() {
  52634. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52635. }
  52636. /**
  52637. * Sets the easing mode of the current function.
  52638. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52639. */
  52640. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52641. var n = Math.min(Math.max(easingMode, 0), 2);
  52642. this._easingMode = n;
  52643. };
  52644. /**
  52645. * Gets the current easing mode.
  52646. * @returns the easing mode
  52647. */
  52648. EasingFunction.prototype.getEasingMode = function () {
  52649. return this._easingMode;
  52650. };
  52651. /**
  52652. * @hidden
  52653. */
  52654. EasingFunction.prototype.easeInCore = function (gradient) {
  52655. throw new Error('You must implement this method');
  52656. };
  52657. /**
  52658. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52659. * of the easing function.
  52660. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52661. * @returns the corresponding value on the curve defined by the easing function
  52662. */
  52663. EasingFunction.prototype.ease = function (gradient) {
  52664. switch (this._easingMode) {
  52665. case EasingFunction.EASINGMODE_EASEIN:
  52666. return this.easeInCore(gradient);
  52667. case EasingFunction.EASINGMODE_EASEOUT:
  52668. return (1 - this.easeInCore(1 - gradient));
  52669. }
  52670. if (gradient >= 0.5) {
  52671. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52672. }
  52673. return (this.easeInCore(gradient * 2) * 0.5);
  52674. };
  52675. /**
  52676. * Interpolation follows the mathematical formula associated with the easing function.
  52677. */
  52678. EasingFunction.EASINGMODE_EASEIN = 0;
  52679. /**
  52680. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52681. */
  52682. EasingFunction.EASINGMODE_EASEOUT = 1;
  52683. /**
  52684. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52685. */
  52686. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52687. return EasingFunction;
  52688. }());
  52689. BABYLON.EasingFunction = EasingFunction;
  52690. /**
  52691. * Easing function with a circle shape (see link below).
  52692. * @see https://easings.net/#easeInCirc
  52693. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52694. */
  52695. var CircleEase = /** @class */ (function (_super) {
  52696. __extends(CircleEase, _super);
  52697. function CircleEase() {
  52698. return _super !== null && _super.apply(this, arguments) || this;
  52699. }
  52700. /** @hidden */
  52701. CircleEase.prototype.easeInCore = function (gradient) {
  52702. gradient = Math.max(0, Math.min(1, gradient));
  52703. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52704. };
  52705. return CircleEase;
  52706. }(EasingFunction));
  52707. BABYLON.CircleEase = CircleEase;
  52708. /**
  52709. * Easing function with a ease back shape (see link below).
  52710. * @see https://easings.net/#easeInBack
  52711. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52712. */
  52713. var BackEase = /** @class */ (function (_super) {
  52714. __extends(BackEase, _super);
  52715. /**
  52716. * Instantiates a back ease easing
  52717. * @see https://easings.net/#easeInBack
  52718. * @param amplitude Defines the amplitude of the function
  52719. */
  52720. function BackEase(
  52721. /** Defines the amplitude of the function */
  52722. amplitude) {
  52723. if (amplitude === void 0) { amplitude = 1; }
  52724. var _this = _super.call(this) || this;
  52725. _this.amplitude = amplitude;
  52726. return _this;
  52727. }
  52728. /** @hidden */
  52729. BackEase.prototype.easeInCore = function (gradient) {
  52730. var num = Math.max(0, this.amplitude);
  52731. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52732. };
  52733. return BackEase;
  52734. }(EasingFunction));
  52735. BABYLON.BackEase = BackEase;
  52736. /**
  52737. * Easing function with a bouncing shape (see link below).
  52738. * @see https://easings.net/#easeInBounce
  52739. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52740. */
  52741. var BounceEase = /** @class */ (function (_super) {
  52742. __extends(BounceEase, _super);
  52743. /**
  52744. * Instantiates a bounce easing
  52745. * @see https://easings.net/#easeInBounce
  52746. * @param bounces Defines the number of bounces
  52747. * @param bounciness Defines the amplitude of the bounce
  52748. */
  52749. function BounceEase(
  52750. /** Defines the number of bounces */
  52751. bounces,
  52752. /** Defines the amplitude of the bounce */
  52753. bounciness) {
  52754. if (bounces === void 0) { bounces = 3; }
  52755. if (bounciness === void 0) { bounciness = 2; }
  52756. var _this = _super.call(this) || this;
  52757. _this.bounces = bounces;
  52758. _this.bounciness = bounciness;
  52759. return _this;
  52760. }
  52761. /** @hidden */
  52762. BounceEase.prototype.easeInCore = function (gradient) {
  52763. var y = Math.max(0.0, this.bounces);
  52764. var bounciness = this.bounciness;
  52765. if (bounciness <= 1.0) {
  52766. bounciness = 1.001;
  52767. }
  52768. var num9 = Math.pow(bounciness, y);
  52769. var num5 = 1.0 - bounciness;
  52770. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52771. var num15 = gradient * num4;
  52772. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52773. var num3 = Math.floor(num65);
  52774. var num13 = num3 + 1.0;
  52775. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52776. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52777. var num7 = (num8 + num12) * 0.5;
  52778. var num6 = gradient - num7;
  52779. var num2 = num7 - num8;
  52780. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52781. };
  52782. return BounceEase;
  52783. }(EasingFunction));
  52784. BABYLON.BounceEase = BounceEase;
  52785. /**
  52786. * Easing function with a power of 3 shape (see link below).
  52787. * @see https://easings.net/#easeInCubic
  52788. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52789. */
  52790. var CubicEase = /** @class */ (function (_super) {
  52791. __extends(CubicEase, _super);
  52792. function CubicEase() {
  52793. return _super !== null && _super.apply(this, arguments) || this;
  52794. }
  52795. /** @hidden */
  52796. CubicEase.prototype.easeInCore = function (gradient) {
  52797. return (gradient * gradient * gradient);
  52798. };
  52799. return CubicEase;
  52800. }(EasingFunction));
  52801. BABYLON.CubicEase = CubicEase;
  52802. /**
  52803. * Easing function with an elastic shape (see link below).
  52804. * @see https://easings.net/#easeInElastic
  52805. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52806. */
  52807. var ElasticEase = /** @class */ (function (_super) {
  52808. __extends(ElasticEase, _super);
  52809. /**
  52810. * Instantiates an elastic easing function
  52811. * @see https://easings.net/#easeInElastic
  52812. * @param oscillations Defines the number of oscillations
  52813. * @param springiness Defines the amplitude of the oscillations
  52814. */
  52815. function ElasticEase(
  52816. /** Defines the number of oscillations*/
  52817. oscillations,
  52818. /** Defines the amplitude of the oscillations*/
  52819. springiness) {
  52820. if (oscillations === void 0) { oscillations = 3; }
  52821. if (springiness === void 0) { springiness = 3; }
  52822. var _this = _super.call(this) || this;
  52823. _this.oscillations = oscillations;
  52824. _this.springiness = springiness;
  52825. return _this;
  52826. }
  52827. /** @hidden */
  52828. ElasticEase.prototype.easeInCore = function (gradient) {
  52829. var num2;
  52830. var num3 = Math.max(0.0, this.oscillations);
  52831. var num = Math.max(0.0, this.springiness);
  52832. if (num == 0) {
  52833. num2 = gradient;
  52834. }
  52835. else {
  52836. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52837. }
  52838. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52839. };
  52840. return ElasticEase;
  52841. }(EasingFunction));
  52842. BABYLON.ElasticEase = ElasticEase;
  52843. /**
  52844. * Easing function with an exponential shape (see link below).
  52845. * @see https://easings.net/#easeInExpo
  52846. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52847. */
  52848. var ExponentialEase = /** @class */ (function (_super) {
  52849. __extends(ExponentialEase, _super);
  52850. /**
  52851. * Instantiates an exponential easing function
  52852. * @see https://easings.net/#easeInExpo
  52853. * @param exponent Defines the exponent of the function
  52854. */
  52855. function ExponentialEase(
  52856. /** Defines the exponent of the function */
  52857. exponent) {
  52858. if (exponent === void 0) { exponent = 2; }
  52859. var _this = _super.call(this) || this;
  52860. _this.exponent = exponent;
  52861. return _this;
  52862. }
  52863. /** @hidden */
  52864. ExponentialEase.prototype.easeInCore = function (gradient) {
  52865. if (this.exponent <= 0) {
  52866. return gradient;
  52867. }
  52868. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52869. };
  52870. return ExponentialEase;
  52871. }(EasingFunction));
  52872. BABYLON.ExponentialEase = ExponentialEase;
  52873. /**
  52874. * Easing function with a power shape (see link below).
  52875. * @see https://easings.net/#easeInQuad
  52876. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52877. */
  52878. var PowerEase = /** @class */ (function (_super) {
  52879. __extends(PowerEase, _super);
  52880. /**
  52881. * Instantiates an power base easing function
  52882. * @see https://easings.net/#easeInQuad
  52883. * @param power Defines the power of the function
  52884. */
  52885. function PowerEase(
  52886. /** Defines the power of the function */
  52887. power) {
  52888. if (power === void 0) { power = 2; }
  52889. var _this = _super.call(this) || this;
  52890. _this.power = power;
  52891. return _this;
  52892. }
  52893. /** @hidden */
  52894. PowerEase.prototype.easeInCore = function (gradient) {
  52895. var y = Math.max(0.0, this.power);
  52896. return Math.pow(gradient, y);
  52897. };
  52898. return PowerEase;
  52899. }(EasingFunction));
  52900. BABYLON.PowerEase = PowerEase;
  52901. /**
  52902. * Easing function with a power of 2 shape (see link below).
  52903. * @see https://easings.net/#easeInQuad
  52904. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52905. */
  52906. var QuadraticEase = /** @class */ (function (_super) {
  52907. __extends(QuadraticEase, _super);
  52908. function QuadraticEase() {
  52909. return _super !== null && _super.apply(this, arguments) || this;
  52910. }
  52911. /** @hidden */
  52912. QuadraticEase.prototype.easeInCore = function (gradient) {
  52913. return (gradient * gradient);
  52914. };
  52915. return QuadraticEase;
  52916. }(EasingFunction));
  52917. BABYLON.QuadraticEase = QuadraticEase;
  52918. /**
  52919. * Easing function with a power of 4 shape (see link below).
  52920. * @see https://easings.net/#easeInQuart
  52921. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52922. */
  52923. var QuarticEase = /** @class */ (function (_super) {
  52924. __extends(QuarticEase, _super);
  52925. function QuarticEase() {
  52926. return _super !== null && _super.apply(this, arguments) || this;
  52927. }
  52928. /** @hidden */
  52929. QuarticEase.prototype.easeInCore = function (gradient) {
  52930. return (gradient * gradient * gradient * gradient);
  52931. };
  52932. return QuarticEase;
  52933. }(EasingFunction));
  52934. BABYLON.QuarticEase = QuarticEase;
  52935. /**
  52936. * Easing function with a power of 5 shape (see link below).
  52937. * @see https://easings.net/#easeInQuint
  52938. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52939. */
  52940. var QuinticEase = /** @class */ (function (_super) {
  52941. __extends(QuinticEase, _super);
  52942. function QuinticEase() {
  52943. return _super !== null && _super.apply(this, arguments) || this;
  52944. }
  52945. /** @hidden */
  52946. QuinticEase.prototype.easeInCore = function (gradient) {
  52947. return (gradient * gradient * gradient * gradient * gradient);
  52948. };
  52949. return QuinticEase;
  52950. }(EasingFunction));
  52951. BABYLON.QuinticEase = QuinticEase;
  52952. /**
  52953. * Easing function with a sin shape (see link below).
  52954. * @see https://easings.net/#easeInSine
  52955. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52956. */
  52957. var SineEase = /** @class */ (function (_super) {
  52958. __extends(SineEase, _super);
  52959. function SineEase() {
  52960. return _super !== null && _super.apply(this, arguments) || this;
  52961. }
  52962. /** @hidden */
  52963. SineEase.prototype.easeInCore = function (gradient) {
  52964. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52965. };
  52966. return SineEase;
  52967. }(EasingFunction));
  52968. BABYLON.SineEase = SineEase;
  52969. /**
  52970. * Easing function with a bezier shape (see link below).
  52971. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52972. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52973. */
  52974. var BezierCurveEase = /** @class */ (function (_super) {
  52975. __extends(BezierCurveEase, _super);
  52976. /**
  52977. * Instantiates a bezier function
  52978. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52979. * @param x1 Defines the x component of the start tangent in the bezier curve
  52980. * @param y1 Defines the y component of the start tangent in the bezier curve
  52981. * @param x2 Defines the x component of the end tangent in the bezier curve
  52982. * @param y2 Defines the y component of the end tangent in the bezier curve
  52983. */
  52984. function BezierCurveEase(
  52985. /** Defines the x component of the start tangent in the bezier curve */
  52986. x1,
  52987. /** Defines the y component of the start tangent in the bezier curve */
  52988. y1,
  52989. /** Defines the x component of the end tangent in the bezier curve */
  52990. x2,
  52991. /** Defines the y component of the end tangent in the bezier curve */
  52992. y2) {
  52993. if (x1 === void 0) { x1 = 0; }
  52994. if (y1 === void 0) { y1 = 0; }
  52995. if (x2 === void 0) { x2 = 1; }
  52996. if (y2 === void 0) { y2 = 1; }
  52997. var _this = _super.call(this) || this;
  52998. _this.x1 = x1;
  52999. _this.y1 = y1;
  53000. _this.x2 = x2;
  53001. _this.y2 = y2;
  53002. return _this;
  53003. }
  53004. /** @hidden */
  53005. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53006. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53007. };
  53008. return BezierCurveEase;
  53009. }(EasingFunction));
  53010. BABYLON.BezierCurveEase = BezierCurveEase;
  53011. })(BABYLON || (BABYLON = {}));
  53012. //# sourceMappingURL=babylon.easing.js.map
  53013. var BABYLON;
  53014. (function (BABYLON) {
  53015. /**
  53016. * A Condition applied to an Action
  53017. */
  53018. var Condition = /** @class */ (function () {
  53019. /**
  53020. * Creates a new Condition
  53021. * @param actionManager the manager of the action the condition is applied to
  53022. */
  53023. function Condition(actionManager) {
  53024. this._actionManager = actionManager;
  53025. }
  53026. /**
  53027. * Check if the current condition is valid
  53028. * @returns a boolean
  53029. */
  53030. Condition.prototype.isValid = function () {
  53031. return true;
  53032. };
  53033. /**
  53034. * Internal only
  53035. * @hidden
  53036. */
  53037. Condition.prototype._getProperty = function (propertyPath) {
  53038. return this._actionManager._getProperty(propertyPath);
  53039. };
  53040. /**
  53041. * Internal only
  53042. * @hidden
  53043. */
  53044. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53045. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53046. };
  53047. /**
  53048. * Serialize placeholder for child classes
  53049. * @returns the serialized object
  53050. */
  53051. Condition.prototype.serialize = function () {
  53052. };
  53053. /**
  53054. * Internal only
  53055. * @hidden
  53056. */
  53057. Condition.prototype._serialize = function (serializedCondition) {
  53058. return {
  53059. type: 2,
  53060. children: [],
  53061. name: serializedCondition.name,
  53062. properties: serializedCondition.properties
  53063. };
  53064. };
  53065. return Condition;
  53066. }());
  53067. BABYLON.Condition = Condition;
  53068. /**
  53069. * Defines specific conditional operators as extensions of Condition
  53070. */
  53071. var ValueCondition = /** @class */ (function (_super) {
  53072. __extends(ValueCondition, _super);
  53073. /**
  53074. * Creates a new ValueCondition
  53075. * @param actionManager manager for the action the condition applies to
  53076. * @param target for the action
  53077. * @param propertyPath path to specify the property of the target the conditional operator uses
  53078. * @param value the value compared by the conditional operator against the current value of the property
  53079. * @param operator the conditional operator, default ValueCondition.IsEqual
  53080. */
  53081. function ValueCondition(actionManager, target,
  53082. /** path to specify the property of the target the conditional operator uses */
  53083. propertyPath,
  53084. /** the value compared by the conditional operator against the current value of the property */
  53085. value,
  53086. /** the conditional operator, default ValueCondition.IsEqual */
  53087. operator) {
  53088. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53089. var _this = _super.call(this, actionManager) || this;
  53090. _this.propertyPath = propertyPath;
  53091. _this.value = value;
  53092. _this.operator = operator;
  53093. _this._target = target;
  53094. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53095. _this._property = _this._getProperty(_this.propertyPath);
  53096. return _this;
  53097. }
  53098. Object.defineProperty(ValueCondition, "IsEqual", {
  53099. /**
  53100. * returns the number for IsEqual
  53101. */
  53102. get: function () {
  53103. return ValueCondition._IsEqual;
  53104. },
  53105. enumerable: true,
  53106. configurable: true
  53107. });
  53108. Object.defineProperty(ValueCondition, "IsDifferent", {
  53109. /**
  53110. * Returns the number for IsDifferent
  53111. */
  53112. get: function () {
  53113. return ValueCondition._IsDifferent;
  53114. },
  53115. enumerable: true,
  53116. configurable: true
  53117. });
  53118. Object.defineProperty(ValueCondition, "IsGreater", {
  53119. /**
  53120. * Returns the number for IsGreater
  53121. */
  53122. get: function () {
  53123. return ValueCondition._IsGreater;
  53124. },
  53125. enumerable: true,
  53126. configurable: true
  53127. });
  53128. Object.defineProperty(ValueCondition, "IsLesser", {
  53129. /**
  53130. * Returns the number for IsLesser
  53131. */
  53132. get: function () {
  53133. return ValueCondition._IsLesser;
  53134. },
  53135. enumerable: true,
  53136. configurable: true
  53137. });
  53138. /**
  53139. * Compares the given value with the property value for the specified conditional operator
  53140. * @returns the result of the comparison
  53141. */
  53142. ValueCondition.prototype.isValid = function () {
  53143. switch (this.operator) {
  53144. case ValueCondition.IsGreater:
  53145. return this._effectiveTarget[this._property] > this.value;
  53146. case ValueCondition.IsLesser:
  53147. return this._effectiveTarget[this._property] < this.value;
  53148. case ValueCondition.IsEqual:
  53149. case ValueCondition.IsDifferent:
  53150. var check;
  53151. if (this.value.equals) {
  53152. check = this.value.equals(this._effectiveTarget[this._property]);
  53153. }
  53154. else {
  53155. check = this.value === this._effectiveTarget[this._property];
  53156. }
  53157. return this.operator === ValueCondition.IsEqual ? check : !check;
  53158. }
  53159. return false;
  53160. };
  53161. /**
  53162. * Serialize the ValueCondition into a JSON compatible object
  53163. * @returns serialization object
  53164. */
  53165. ValueCondition.prototype.serialize = function () {
  53166. return this._serialize({
  53167. name: "ValueCondition",
  53168. properties: [
  53169. BABYLON.Action._GetTargetProperty(this._target),
  53170. { name: "propertyPath", value: this.propertyPath },
  53171. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53172. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53173. ]
  53174. });
  53175. };
  53176. /**
  53177. * Gets the name of the conditional operator for the ValueCondition
  53178. * @param operator the conditional operator
  53179. * @returns the name
  53180. */
  53181. ValueCondition.GetOperatorName = function (operator) {
  53182. switch (operator) {
  53183. case ValueCondition._IsEqual: return "IsEqual";
  53184. case ValueCondition._IsDifferent: return "IsDifferent";
  53185. case ValueCondition._IsGreater: return "IsGreater";
  53186. case ValueCondition._IsLesser: return "IsLesser";
  53187. default: return "";
  53188. }
  53189. };
  53190. /**
  53191. * Internal only
  53192. * @hidden
  53193. */
  53194. ValueCondition._IsEqual = 0;
  53195. /**
  53196. * Internal only
  53197. * @hidden
  53198. */
  53199. ValueCondition._IsDifferent = 1;
  53200. /**
  53201. * Internal only
  53202. * @hidden
  53203. */
  53204. ValueCondition._IsGreater = 2;
  53205. /**
  53206. * Internal only
  53207. * @hidden
  53208. */
  53209. ValueCondition._IsLesser = 3;
  53210. return ValueCondition;
  53211. }(Condition));
  53212. BABYLON.ValueCondition = ValueCondition;
  53213. /**
  53214. * Defines a predicate condition as an extension of Condition
  53215. */
  53216. var PredicateCondition = /** @class */ (function (_super) {
  53217. __extends(PredicateCondition, _super);
  53218. /**
  53219. * Creates a new PredicateCondition
  53220. * @param actionManager manager for the action the condition applies to
  53221. * @param predicate defines the predicate function used to validate the condition
  53222. */
  53223. function PredicateCondition(actionManager,
  53224. /** defines the predicate function used to validate the condition */
  53225. predicate) {
  53226. var _this = _super.call(this, actionManager) || this;
  53227. _this.predicate = predicate;
  53228. return _this;
  53229. }
  53230. /**
  53231. * @returns the validity of the predicate condition
  53232. */
  53233. PredicateCondition.prototype.isValid = function () {
  53234. return this.predicate();
  53235. };
  53236. return PredicateCondition;
  53237. }(Condition));
  53238. BABYLON.PredicateCondition = PredicateCondition;
  53239. /**
  53240. * Defines a state condition as an extension of Condition
  53241. */
  53242. var StateCondition = /** @class */ (function (_super) {
  53243. __extends(StateCondition, _super);
  53244. /**
  53245. * Creates a new StateCondition
  53246. * @param actionManager manager for the action the condition applies to
  53247. * @param target of the condition
  53248. * @param value to compare with target state
  53249. */
  53250. function StateCondition(actionManager, target, value) {
  53251. var _this = _super.call(this, actionManager) || this;
  53252. _this.value = value;
  53253. _this._target = target;
  53254. return _this;
  53255. }
  53256. /**
  53257. * @returns the validity of the state
  53258. */
  53259. StateCondition.prototype.isValid = function () {
  53260. return this._target.state === this.value;
  53261. };
  53262. /**
  53263. * Serialize the StateCondition into a JSON compatible object
  53264. * @returns serialization object
  53265. */
  53266. StateCondition.prototype.serialize = function () {
  53267. return this._serialize({
  53268. name: "StateCondition",
  53269. properties: [
  53270. BABYLON.Action._GetTargetProperty(this._target),
  53271. { name: "value", value: this.value }
  53272. ]
  53273. });
  53274. };
  53275. return StateCondition;
  53276. }(Condition));
  53277. BABYLON.StateCondition = StateCondition;
  53278. })(BABYLON || (BABYLON = {}));
  53279. //# sourceMappingURL=babylon.condition.js.map
  53280. var BABYLON;
  53281. (function (BABYLON) {
  53282. /**
  53283. * The action to be carried out following a trigger
  53284. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53285. */
  53286. var Action = /** @class */ (function () {
  53287. /**
  53288. * Creates a new Action
  53289. * @param triggerOptions the trigger, with or without parameters, for the action
  53290. * @param condition an optional determinant of action
  53291. */
  53292. function Action(
  53293. /** the trigger, with or without parameters, for the action */
  53294. triggerOptions, condition) {
  53295. this.triggerOptions = triggerOptions;
  53296. /**
  53297. * An event triggered prior to action being executed.
  53298. */
  53299. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53300. if (triggerOptions.parameter) {
  53301. this.trigger = triggerOptions.trigger;
  53302. this._triggerParameter = triggerOptions.parameter;
  53303. }
  53304. else if (triggerOptions.trigger) {
  53305. this.trigger = triggerOptions.trigger;
  53306. }
  53307. else {
  53308. this.trigger = triggerOptions;
  53309. }
  53310. this._nextActiveAction = this;
  53311. this._condition = condition;
  53312. }
  53313. /**
  53314. * Internal only
  53315. * @hidden
  53316. */
  53317. Action.prototype._prepare = function () {
  53318. };
  53319. /**
  53320. * Gets the trigger parameters
  53321. * @returns the trigger parameters
  53322. */
  53323. Action.prototype.getTriggerParameter = function () {
  53324. return this._triggerParameter;
  53325. };
  53326. /**
  53327. * Internal only - executes current action event
  53328. * @hidden
  53329. */
  53330. Action.prototype._executeCurrent = function (evt) {
  53331. if (this._nextActiveAction._condition) {
  53332. var condition = this._nextActiveAction._condition;
  53333. var currentRenderId = this._actionManager.getScene().getRenderId();
  53334. // We cache the current evaluation for the current frame
  53335. if (condition._evaluationId === currentRenderId) {
  53336. if (!condition._currentResult) {
  53337. return;
  53338. }
  53339. }
  53340. else {
  53341. condition._evaluationId = currentRenderId;
  53342. if (!condition.isValid()) {
  53343. condition._currentResult = false;
  53344. return;
  53345. }
  53346. condition._currentResult = true;
  53347. }
  53348. }
  53349. this.onBeforeExecuteObservable.notifyObservers(this);
  53350. this._nextActiveAction.execute(evt);
  53351. this.skipToNextActiveAction();
  53352. };
  53353. /**
  53354. * Execute placeholder for child classes
  53355. * @param evt optional action event
  53356. */
  53357. Action.prototype.execute = function (evt) {
  53358. };
  53359. /**
  53360. * Skips to next active action
  53361. */
  53362. Action.prototype.skipToNextActiveAction = function () {
  53363. if (this._nextActiveAction._child) {
  53364. if (!this._nextActiveAction._child._actionManager) {
  53365. this._nextActiveAction._child._actionManager = this._actionManager;
  53366. }
  53367. this._nextActiveAction = this._nextActiveAction._child;
  53368. }
  53369. else {
  53370. this._nextActiveAction = this;
  53371. }
  53372. };
  53373. /**
  53374. * Adds action to chain of actions, may be a DoNothingAction
  53375. * @param action defines the next action to execute
  53376. * @returns The action passed in
  53377. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53378. */
  53379. Action.prototype.then = function (action) {
  53380. this._child = action;
  53381. action._actionManager = this._actionManager;
  53382. action._prepare();
  53383. return action;
  53384. };
  53385. /**
  53386. * Internal only
  53387. * @hidden
  53388. */
  53389. Action.prototype._getProperty = function (propertyPath) {
  53390. return this._actionManager._getProperty(propertyPath);
  53391. };
  53392. /**
  53393. * Internal only
  53394. * @hidden
  53395. */
  53396. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53397. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53398. };
  53399. /**
  53400. * Serialize placeholder for child classes
  53401. * @param parent of child
  53402. * @returns the serialized object
  53403. */
  53404. Action.prototype.serialize = function (parent) {
  53405. };
  53406. /**
  53407. * Internal only called by serialize
  53408. * @hidden
  53409. */
  53410. Action.prototype._serialize = function (serializedAction, parent) {
  53411. var serializationObject = {
  53412. type: 1,
  53413. children: [],
  53414. name: serializedAction.name,
  53415. properties: serializedAction.properties || []
  53416. };
  53417. // Serialize child
  53418. if (this._child) {
  53419. this._child.serialize(serializationObject);
  53420. }
  53421. // Check if "this" has a condition
  53422. if (this._condition) {
  53423. var serializedCondition = this._condition.serialize();
  53424. serializedCondition.children.push(serializationObject);
  53425. if (parent) {
  53426. parent.children.push(serializedCondition);
  53427. }
  53428. return serializedCondition;
  53429. }
  53430. if (parent) {
  53431. parent.children.push(serializationObject);
  53432. }
  53433. return serializationObject;
  53434. };
  53435. /**
  53436. * Internal only
  53437. * @hidden
  53438. */
  53439. Action._SerializeValueAsString = function (value) {
  53440. if (typeof value === "number") {
  53441. return value.toString();
  53442. }
  53443. if (typeof value === "boolean") {
  53444. return value ? "true" : "false";
  53445. }
  53446. if (value instanceof BABYLON.Vector2) {
  53447. return value.x + ", " + value.y;
  53448. }
  53449. if (value instanceof BABYLON.Vector3) {
  53450. return value.x + ", " + value.y + ", " + value.z;
  53451. }
  53452. if (value instanceof BABYLON.Color3) {
  53453. return value.r + ", " + value.g + ", " + value.b;
  53454. }
  53455. if (value instanceof BABYLON.Color4) {
  53456. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53457. }
  53458. return value; // string
  53459. };
  53460. /**
  53461. * Internal only
  53462. * @hidden
  53463. */
  53464. Action._GetTargetProperty = function (target) {
  53465. return {
  53466. name: "target",
  53467. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53468. : target instanceof BABYLON.Light ? "LightProperties"
  53469. : target instanceof BABYLON.Camera ? "CameraProperties"
  53470. : "SceneProperties",
  53471. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53472. };
  53473. };
  53474. return Action;
  53475. }());
  53476. BABYLON.Action = Action;
  53477. })(BABYLON || (BABYLON = {}));
  53478. //# sourceMappingURL=babylon.action.js.map
  53479. var BABYLON;
  53480. (function (BABYLON) {
  53481. /**
  53482. * ActionEvent is the event being sent when an action is triggered.
  53483. */
  53484. var ActionEvent = /** @class */ (function () {
  53485. /**
  53486. * Creates a new ActionEvent
  53487. * @param source The mesh or sprite that triggered the action
  53488. * @param pointerX The X mouse cursor position at the time of the event
  53489. * @param pointerY The Y mouse cursor position at the time of the event
  53490. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53491. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53492. * @param additionalData additional data for the event
  53493. */
  53494. function ActionEvent(
  53495. /** The mesh or sprite that triggered the action */
  53496. source,
  53497. /** The X mouse cursor position at the time of the event */
  53498. pointerX,
  53499. /** The Y mouse cursor position at the time of the event */
  53500. pointerY,
  53501. /** The mesh that is currently pointed at (can be null) */
  53502. meshUnderPointer,
  53503. /** the original (browser) event that triggered the ActionEvent */
  53504. sourceEvent,
  53505. /** additional data for the event */
  53506. additionalData) {
  53507. this.source = source;
  53508. this.pointerX = pointerX;
  53509. this.pointerY = pointerY;
  53510. this.meshUnderPointer = meshUnderPointer;
  53511. this.sourceEvent = sourceEvent;
  53512. this.additionalData = additionalData;
  53513. }
  53514. /**
  53515. * Helper function to auto-create an ActionEvent from a source mesh.
  53516. * @param source The source mesh that triggered the event
  53517. * @param evt The original (browser) event
  53518. * @param additionalData additional data for the event
  53519. * @returns the new ActionEvent
  53520. */
  53521. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53522. var scene = source.getScene();
  53523. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53524. };
  53525. /**
  53526. * Helper function to auto-create an ActionEvent from a source sprite
  53527. * @param source The source sprite that triggered the event
  53528. * @param scene Scene associated with the sprite
  53529. * @param evt The original (browser) event
  53530. * @param additionalData additional data for the event
  53531. * @returns the new ActionEvent
  53532. */
  53533. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53534. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53535. };
  53536. /**
  53537. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53538. * @param scene the scene where the event occurred
  53539. * @param evt The original (browser) event
  53540. * @returns the new ActionEvent
  53541. */
  53542. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53543. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53544. };
  53545. /**
  53546. * Helper function to auto-create an ActionEvent from a primitive
  53547. * @param prim defines the target primitive
  53548. * @param pointerPos defines the pointer position
  53549. * @param evt The original (browser) event
  53550. * @param additionalData additional data for the event
  53551. * @returns the new ActionEvent
  53552. */
  53553. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53554. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53555. };
  53556. return ActionEvent;
  53557. }());
  53558. BABYLON.ActionEvent = ActionEvent;
  53559. /**
  53560. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53561. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53563. */
  53564. var ActionManager = /** @class */ (function () {
  53565. /**
  53566. * Creates a new action manager
  53567. * @param scene defines the hosting scene
  53568. */
  53569. function ActionManager(scene) {
  53570. // Members
  53571. /** Gets the list of actions */
  53572. this.actions = new Array();
  53573. /** Gets the cursor to use when hovering items */
  53574. this.hoverCursor = '';
  53575. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53576. scene.actionManagers.push(this);
  53577. }
  53578. // Methods
  53579. /**
  53580. * Releases all associated resources
  53581. */
  53582. ActionManager.prototype.dispose = function () {
  53583. var index = this._scene.actionManagers.indexOf(this);
  53584. for (var i = 0; i < this.actions.length; i++) {
  53585. var action = this.actions[i];
  53586. ActionManager.Triggers[action.trigger]--;
  53587. if (ActionManager.Triggers[action.trigger] === 0) {
  53588. delete ActionManager.Triggers[action.trigger];
  53589. }
  53590. }
  53591. if (index > -1) {
  53592. this._scene.actionManagers.splice(index, 1);
  53593. }
  53594. };
  53595. /**
  53596. * Gets hosting scene
  53597. * @returns the hosting scene
  53598. */
  53599. ActionManager.prototype.getScene = function () {
  53600. return this._scene;
  53601. };
  53602. /**
  53603. * Does this action manager handles actions of any of the given triggers
  53604. * @param triggers defines the triggers to be tested
  53605. * @return a boolean indicating whether one (or more) of the triggers is handled
  53606. */
  53607. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53608. for (var index = 0; index < this.actions.length; index++) {
  53609. var action = this.actions[index];
  53610. if (triggers.indexOf(action.trigger) > -1) {
  53611. return true;
  53612. }
  53613. }
  53614. return false;
  53615. };
  53616. /**
  53617. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53618. * speed.
  53619. * @param triggerA defines the trigger to be tested
  53620. * @param triggerB defines the trigger to be tested
  53621. * @return a boolean indicating whether one (or more) of the triggers is handled
  53622. */
  53623. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53624. for (var index = 0; index < this.actions.length; index++) {
  53625. var action = this.actions[index];
  53626. if (triggerA == action.trigger || triggerB == action.trigger) {
  53627. return true;
  53628. }
  53629. }
  53630. return false;
  53631. };
  53632. /**
  53633. * Does this action manager handles actions of a given trigger
  53634. * @param trigger defines the trigger to be tested
  53635. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53636. * @return whether the trigger is handled
  53637. */
  53638. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53639. for (var index = 0; index < this.actions.length; index++) {
  53640. var action = this.actions[index];
  53641. if (action.trigger === trigger) {
  53642. if (parameterPredicate) {
  53643. if (parameterPredicate(action.getTriggerParameter())) {
  53644. return true;
  53645. }
  53646. }
  53647. else {
  53648. return true;
  53649. }
  53650. }
  53651. }
  53652. return false;
  53653. };
  53654. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53655. /**
  53656. * Does this action manager has pointer triggers
  53657. */
  53658. get: function () {
  53659. for (var index = 0; index < this.actions.length; index++) {
  53660. var action = this.actions[index];
  53661. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53662. return true;
  53663. }
  53664. }
  53665. return false;
  53666. },
  53667. enumerable: true,
  53668. configurable: true
  53669. });
  53670. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53671. /**
  53672. * Does this action manager has pick triggers
  53673. */
  53674. get: function () {
  53675. for (var index = 0; index < this.actions.length; index++) {
  53676. var action = this.actions[index];
  53677. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53678. return true;
  53679. }
  53680. }
  53681. return false;
  53682. },
  53683. enumerable: true,
  53684. configurable: true
  53685. });
  53686. Object.defineProperty(ActionManager, "HasTriggers", {
  53687. /**
  53688. * Does exist one action manager with at least one trigger
  53689. **/
  53690. get: function () {
  53691. for (var t in ActionManager.Triggers) {
  53692. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53693. return true;
  53694. }
  53695. }
  53696. return false;
  53697. },
  53698. enumerable: true,
  53699. configurable: true
  53700. });
  53701. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53702. /**
  53703. * Does exist one action manager with at least one pick trigger
  53704. **/
  53705. get: function () {
  53706. for (var t in ActionManager.Triggers) {
  53707. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53708. var t_int = parseInt(t);
  53709. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53710. return true;
  53711. }
  53712. }
  53713. }
  53714. return false;
  53715. },
  53716. enumerable: true,
  53717. configurable: true
  53718. });
  53719. /**
  53720. * Does exist one action manager that handles actions of a given trigger
  53721. * @param trigger defines the trigger to be tested
  53722. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53723. **/
  53724. ActionManager.HasSpecificTrigger = function (trigger) {
  53725. for (var t in ActionManager.Triggers) {
  53726. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53727. var t_int = parseInt(t);
  53728. if (t_int === trigger) {
  53729. return true;
  53730. }
  53731. }
  53732. }
  53733. return false;
  53734. };
  53735. /**
  53736. * Registers an action to this action manager
  53737. * @param action defines the action to be registered
  53738. * @return the action amended (prepared) after registration
  53739. */
  53740. ActionManager.prototype.registerAction = function (action) {
  53741. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53742. if (this.getScene().actionManager !== this) {
  53743. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53744. return null;
  53745. }
  53746. }
  53747. this.actions.push(action);
  53748. if (ActionManager.Triggers[action.trigger]) {
  53749. ActionManager.Triggers[action.trigger]++;
  53750. }
  53751. else {
  53752. ActionManager.Triggers[action.trigger] = 1;
  53753. }
  53754. action._actionManager = this;
  53755. action._prepare();
  53756. return action;
  53757. };
  53758. /**
  53759. * Unregisters an action to this action manager
  53760. * @param action defines the action to be unregistered
  53761. * @return a boolean indicating whether the action has been unregistered
  53762. */
  53763. ActionManager.prototype.unregisterAction = function (action) {
  53764. var index = this.actions.indexOf(action);
  53765. if (index !== -1) {
  53766. this.actions.splice(index, 1);
  53767. ActionManager.Triggers[action.trigger] -= 1;
  53768. if (ActionManager.Triggers[action.trigger] === 0) {
  53769. delete ActionManager.Triggers[action.trigger];
  53770. }
  53771. delete action._actionManager;
  53772. return true;
  53773. }
  53774. return false;
  53775. };
  53776. /**
  53777. * Process a specific trigger
  53778. * @param trigger defines the trigger to process
  53779. * @param evt defines the event details to be processed
  53780. */
  53781. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53782. for (var index = 0; index < this.actions.length; index++) {
  53783. var action = this.actions[index];
  53784. if (action.trigger === trigger) {
  53785. if (evt) {
  53786. if (trigger === ActionManager.OnKeyUpTrigger
  53787. || trigger === ActionManager.OnKeyDownTrigger) {
  53788. var parameter = action.getTriggerParameter();
  53789. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53790. if (!parameter.toLowerCase) {
  53791. continue;
  53792. }
  53793. var lowerCase = parameter.toLowerCase();
  53794. if (lowerCase !== evt.sourceEvent.key) {
  53795. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53796. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53797. if (actualkey !== lowerCase) {
  53798. continue;
  53799. }
  53800. }
  53801. }
  53802. }
  53803. }
  53804. action._executeCurrent(evt);
  53805. }
  53806. }
  53807. };
  53808. /** @hidden */
  53809. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53810. var properties = propertyPath.split(".");
  53811. for (var index = 0; index < properties.length - 1; index++) {
  53812. target = target[properties[index]];
  53813. }
  53814. return target;
  53815. };
  53816. /** @hidden */
  53817. ActionManager.prototype._getProperty = function (propertyPath) {
  53818. var properties = propertyPath.split(".");
  53819. return properties[properties.length - 1];
  53820. };
  53821. /**
  53822. * Serialize this manager to a JSON object
  53823. * @param name defines the property name to store this manager
  53824. * @returns a JSON representation of this manager
  53825. */
  53826. ActionManager.prototype.serialize = function (name) {
  53827. var root = {
  53828. children: new Array(),
  53829. name: name,
  53830. type: 3,
  53831. properties: new Array() // Empty for root but required
  53832. };
  53833. for (var i = 0; i < this.actions.length; i++) {
  53834. var triggerObject = {
  53835. type: 0,
  53836. children: new Array(),
  53837. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53838. properties: new Array()
  53839. };
  53840. var triggerOptions = this.actions[i].triggerOptions;
  53841. if (triggerOptions && typeof triggerOptions !== "number") {
  53842. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53843. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53844. }
  53845. else {
  53846. var parameter = {};
  53847. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53848. if (triggerOptions.parameter.mesh) {
  53849. parameter._meshId = triggerOptions.parameter.mesh.id;
  53850. }
  53851. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53852. }
  53853. }
  53854. // Serialize child action, recursively
  53855. this.actions[i].serialize(triggerObject);
  53856. // Add serialized trigger
  53857. root.children.push(triggerObject);
  53858. }
  53859. return root;
  53860. };
  53861. /**
  53862. * Creates a new ActionManager from a JSON data
  53863. * @param parsedActions defines the JSON data to read from
  53864. * @param object defines the hosting mesh
  53865. * @param scene defines the hosting scene
  53866. */
  53867. ActionManager.Parse = function (parsedActions, object, scene) {
  53868. var actionManager = new ActionManager(scene);
  53869. if (object === null)
  53870. scene.actionManager = actionManager;
  53871. else
  53872. object.actionManager = actionManager;
  53873. // instanciate a new object
  53874. var instanciate = function (name, params) {
  53875. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53876. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53877. newInstance.constructor.apply(newInstance, params);
  53878. return newInstance;
  53879. };
  53880. var parseParameter = function (name, value, target, propertyPath) {
  53881. if (propertyPath === null) {
  53882. // String, boolean or float
  53883. var floatValue = parseFloat(value);
  53884. if (value === "true" || value === "false")
  53885. return value === "true";
  53886. else
  53887. return isNaN(floatValue) ? value : floatValue;
  53888. }
  53889. var effectiveTarget = propertyPath.split(".");
  53890. var values = value.split(",");
  53891. // Get effective Target
  53892. for (var i = 0; i < effectiveTarget.length; i++) {
  53893. target = target[effectiveTarget[i]];
  53894. }
  53895. // Return appropriate value with its type
  53896. if (typeof (target) === "boolean")
  53897. return values[0] === "true";
  53898. if (typeof (target) === "string")
  53899. return values[0];
  53900. // Parameters with multiple values such as Vector3 etc.
  53901. var split = new Array();
  53902. for (var i = 0; i < values.length; i++)
  53903. split.push(parseFloat(values[i]));
  53904. if (target instanceof BABYLON.Vector3)
  53905. return BABYLON.Vector3.FromArray(split);
  53906. if (target instanceof BABYLON.Vector4)
  53907. return BABYLON.Vector4.FromArray(split);
  53908. if (target instanceof BABYLON.Color3)
  53909. return BABYLON.Color3.FromArray(split);
  53910. if (target instanceof BABYLON.Color4)
  53911. return BABYLON.Color4.FromArray(split);
  53912. return parseFloat(values[0]);
  53913. };
  53914. // traverse graph per trigger
  53915. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53916. if (combineArray === void 0) { combineArray = null; }
  53917. if (parsedAction.detached)
  53918. return;
  53919. var parameters = new Array();
  53920. var target = null;
  53921. var propertyPath = null;
  53922. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53923. // Parameters
  53924. if (parsedAction.type === 2)
  53925. parameters.push(actionManager);
  53926. else
  53927. parameters.push(trigger);
  53928. if (combine) {
  53929. var actions = new Array();
  53930. for (var j = 0; j < parsedAction.combine.length; j++) {
  53931. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53932. }
  53933. parameters.push(actions);
  53934. }
  53935. else {
  53936. for (var i = 0; i < parsedAction.properties.length; i++) {
  53937. var value = parsedAction.properties[i].value;
  53938. var name = parsedAction.properties[i].name;
  53939. var targetType = parsedAction.properties[i].targetType;
  53940. if (name === "target")
  53941. if (targetType !== null && targetType === "SceneProperties")
  53942. value = target = scene;
  53943. else
  53944. value = target = scene.getNodeByName(value);
  53945. else if (name === "parent")
  53946. value = scene.getNodeByName(value);
  53947. else if (name === "sound") {
  53948. // Can not externalize to component, so only checks for the presence off the API.
  53949. if (scene.getSoundByName) {
  53950. value = scene.getSoundByName(value);
  53951. }
  53952. }
  53953. else if (name !== "propertyPath") {
  53954. if (parsedAction.type === 2 && name === "operator")
  53955. value = BABYLON.ValueCondition[value];
  53956. else
  53957. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53958. }
  53959. else {
  53960. propertyPath = value;
  53961. }
  53962. parameters.push(value);
  53963. }
  53964. }
  53965. if (combineArray === null) {
  53966. parameters.push(condition);
  53967. }
  53968. else {
  53969. parameters.push(null);
  53970. }
  53971. // If interpolate value action
  53972. if (parsedAction.name === "InterpolateValueAction") {
  53973. var param = parameters[parameters.length - 2];
  53974. parameters[parameters.length - 1] = param;
  53975. parameters[parameters.length - 2] = condition;
  53976. }
  53977. // Action or condition(s) and not CombineAction
  53978. var newAction = instanciate(parsedAction.name, parameters);
  53979. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53980. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53981. if (action)
  53982. action.then(nothing);
  53983. else
  53984. actionManager.registerAction(nothing);
  53985. action = nothing;
  53986. }
  53987. if (combineArray === null) {
  53988. if (newAction instanceof BABYLON.Condition) {
  53989. condition = newAction;
  53990. newAction = action;
  53991. }
  53992. else {
  53993. condition = null;
  53994. if (action)
  53995. action.then(newAction);
  53996. else
  53997. actionManager.registerAction(newAction);
  53998. }
  53999. }
  54000. else {
  54001. combineArray.push(newAction);
  54002. }
  54003. for (var i = 0; i < parsedAction.children.length; i++)
  54004. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54005. };
  54006. // triggers
  54007. for (var i = 0; i < parsedActions.children.length; i++) {
  54008. var triggerParams;
  54009. var trigger = parsedActions.children[i];
  54010. if (trigger.properties.length > 0) {
  54011. var param = trigger.properties[0].value;
  54012. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54013. if (value._meshId) {
  54014. value.mesh = scene.getMeshByID(value._meshId);
  54015. }
  54016. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54017. }
  54018. else
  54019. triggerParams = ActionManager[trigger.name];
  54020. for (var j = 0; j < trigger.children.length; j++) {
  54021. if (!trigger.detached)
  54022. traverse(trigger.children[j], triggerParams, null, null);
  54023. }
  54024. }
  54025. };
  54026. /**
  54027. * Get a trigger name by index
  54028. * @param trigger defines the trigger index
  54029. * @returns a trigger name
  54030. */
  54031. ActionManager.GetTriggerName = function (trigger) {
  54032. switch (trigger) {
  54033. case 0: return "NothingTrigger";
  54034. case 1: return "OnPickTrigger";
  54035. case 2: return "OnLeftPickTrigger";
  54036. case 3: return "OnRightPickTrigger";
  54037. case 4: return "OnCenterPickTrigger";
  54038. case 5: return "OnPickDownTrigger";
  54039. case 6: return "OnPickUpTrigger";
  54040. case 7: return "OnLongPressTrigger";
  54041. case 8: return "OnPointerOverTrigger";
  54042. case 9: return "OnPointerOutTrigger";
  54043. case 10: return "OnEveryFrameTrigger";
  54044. case 11: return "OnIntersectionEnterTrigger";
  54045. case 12: return "OnIntersectionExitTrigger";
  54046. case 13: return "OnKeyDownTrigger";
  54047. case 14: return "OnKeyUpTrigger";
  54048. case 15: return "OnPickOutTrigger";
  54049. default: return "";
  54050. }
  54051. };
  54052. /**
  54053. * Nothing
  54054. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54055. */
  54056. ActionManager.NothingTrigger = 0;
  54057. /**
  54058. * On pick
  54059. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54060. */
  54061. ActionManager.OnPickTrigger = 1;
  54062. /**
  54063. * On left pick
  54064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54065. */
  54066. ActionManager.OnLeftPickTrigger = 2;
  54067. /**
  54068. * On right pick
  54069. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54070. */
  54071. ActionManager.OnRightPickTrigger = 3;
  54072. /**
  54073. * On center pick
  54074. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54075. */
  54076. ActionManager.OnCenterPickTrigger = 4;
  54077. /**
  54078. * On pick down
  54079. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54080. */
  54081. ActionManager.OnPickDownTrigger = 5;
  54082. /**
  54083. * On double pick
  54084. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54085. */
  54086. ActionManager.OnDoublePickTrigger = 6;
  54087. /**
  54088. * On pick up
  54089. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54090. */
  54091. ActionManager.OnPickUpTrigger = 7;
  54092. /**
  54093. * On pick out.
  54094. * This trigger will only be raised if you also declared a OnPickDown
  54095. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54096. */
  54097. ActionManager.OnPickOutTrigger = 16;
  54098. /**
  54099. * On long press
  54100. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54101. */
  54102. ActionManager.OnLongPressTrigger = 8;
  54103. /**
  54104. * On pointer over
  54105. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54106. */
  54107. ActionManager.OnPointerOverTrigger = 9;
  54108. /**
  54109. * On pointer out
  54110. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54111. */
  54112. ActionManager.OnPointerOutTrigger = 10;
  54113. /**
  54114. * On every frame
  54115. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54116. */
  54117. ActionManager.OnEveryFrameTrigger = 11;
  54118. /**
  54119. * On intersection enter
  54120. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54121. */
  54122. ActionManager.OnIntersectionEnterTrigger = 12;
  54123. /**
  54124. * On intersection exit
  54125. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54126. */
  54127. ActionManager.OnIntersectionExitTrigger = 13;
  54128. /**
  54129. * On key down
  54130. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54131. */
  54132. ActionManager.OnKeyDownTrigger = 14;
  54133. /**
  54134. * On key up
  54135. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54136. */
  54137. ActionManager.OnKeyUpTrigger = 15;
  54138. /** Gets the list of active triggers */
  54139. ActionManager.Triggers = {};
  54140. return ActionManager;
  54141. }());
  54142. BABYLON.ActionManager = ActionManager;
  54143. })(BABYLON || (BABYLON = {}));
  54144. //# sourceMappingURL=babylon.actionManager.js.map
  54145. var BABYLON;
  54146. (function (BABYLON) {
  54147. /**
  54148. * This defines an action responsible to change the value of a property
  54149. * by interpolating between its current value and the newly set one once triggered.
  54150. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54151. */
  54152. var InterpolateValueAction = /** @class */ (function (_super) {
  54153. __extends(InterpolateValueAction, _super);
  54154. /**
  54155. * Instantiate the action
  54156. * @param triggerOptions defines the trigger options
  54157. * @param target defines the object containing the value to interpolate
  54158. * @param propertyPath defines the path to the property in the target object
  54159. * @param value defines the target value at the end of the interpolation
  54160. * @param duration deines the time it will take for the property to interpolate to the value.
  54161. * @param condition defines the trigger related conditions
  54162. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54163. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54164. */
  54165. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54166. if (duration === void 0) { duration = 1000; }
  54167. var _this = _super.call(this, triggerOptions, condition) || this;
  54168. /**
  54169. * Defines the time it will take for the property to interpolate to the value.
  54170. */
  54171. _this.duration = 1000;
  54172. /**
  54173. * Observable triggered once the interpolation animation has been done.
  54174. */
  54175. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54176. _this.propertyPath = propertyPath;
  54177. _this.value = value;
  54178. _this.duration = duration;
  54179. _this.stopOtherAnimations = stopOtherAnimations;
  54180. _this.onInterpolationDone = onInterpolationDone;
  54181. _this._target = _this._effectiveTarget = target;
  54182. return _this;
  54183. }
  54184. /** @hidden */
  54185. InterpolateValueAction.prototype._prepare = function () {
  54186. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54187. this._property = this._getProperty(this.propertyPath);
  54188. };
  54189. /**
  54190. * Execute the action starts the value interpolation.
  54191. */
  54192. InterpolateValueAction.prototype.execute = function () {
  54193. var _this = this;
  54194. var scene = this._actionManager.getScene();
  54195. var keys = [
  54196. {
  54197. frame: 0,
  54198. value: this._effectiveTarget[this._property]
  54199. }, {
  54200. frame: 100,
  54201. value: this.value
  54202. }
  54203. ];
  54204. var dataType;
  54205. if (typeof this.value === "number") {
  54206. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54207. }
  54208. else if (this.value instanceof BABYLON.Color3) {
  54209. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54210. }
  54211. else if (this.value instanceof BABYLON.Vector3) {
  54212. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54213. }
  54214. else if (this.value instanceof BABYLON.Matrix) {
  54215. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54216. }
  54217. else if (this.value instanceof BABYLON.Quaternion) {
  54218. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54219. }
  54220. else {
  54221. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54222. return;
  54223. }
  54224. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54225. animation.setKeys(keys);
  54226. if (this.stopOtherAnimations) {
  54227. scene.stopAnimation(this._effectiveTarget);
  54228. }
  54229. var wrapper = function () {
  54230. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54231. if (_this.onInterpolationDone) {
  54232. _this.onInterpolationDone();
  54233. }
  54234. };
  54235. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54236. };
  54237. /**
  54238. * Serializes the actions and its related information.
  54239. * @param parent defines the object to serialize in
  54240. * @returns the serialized object
  54241. */
  54242. InterpolateValueAction.prototype.serialize = function (parent) {
  54243. return _super.prototype._serialize.call(this, {
  54244. name: "InterpolateValueAction",
  54245. properties: [
  54246. BABYLON.Action._GetTargetProperty(this._target),
  54247. { name: "propertyPath", value: this.propertyPath },
  54248. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54249. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54250. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54251. ]
  54252. }, parent);
  54253. };
  54254. return InterpolateValueAction;
  54255. }(BABYLON.Action));
  54256. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54257. })(BABYLON || (BABYLON = {}));
  54258. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54259. var BABYLON;
  54260. (function (BABYLON) {
  54261. /**
  54262. * This defines an action responsible to toggle a boolean once triggered.
  54263. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54264. */
  54265. var SwitchBooleanAction = /** @class */ (function (_super) {
  54266. __extends(SwitchBooleanAction, _super);
  54267. /**
  54268. * Instantiate the action
  54269. * @param triggerOptions defines the trigger options
  54270. * @param target defines the object containing the boolean
  54271. * @param propertyPath defines the path to the boolean property in the target object
  54272. * @param condition defines the trigger related conditions
  54273. */
  54274. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54275. var _this = _super.call(this, triggerOptions, condition) || this;
  54276. _this.propertyPath = propertyPath;
  54277. _this._target = _this._effectiveTarget = target;
  54278. return _this;
  54279. }
  54280. /** @hidden */
  54281. SwitchBooleanAction.prototype._prepare = function () {
  54282. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54283. this._property = this._getProperty(this.propertyPath);
  54284. };
  54285. /**
  54286. * Execute the action toggle the boolean value.
  54287. */
  54288. SwitchBooleanAction.prototype.execute = function () {
  54289. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54290. };
  54291. /**
  54292. * Serializes the actions and its related information.
  54293. * @param parent defines the object to serialize in
  54294. * @returns the serialized object
  54295. */
  54296. SwitchBooleanAction.prototype.serialize = function (parent) {
  54297. return _super.prototype._serialize.call(this, {
  54298. name: "SwitchBooleanAction",
  54299. properties: [
  54300. BABYLON.Action._GetTargetProperty(this._target),
  54301. { name: "propertyPath", value: this.propertyPath }
  54302. ]
  54303. }, parent);
  54304. };
  54305. return SwitchBooleanAction;
  54306. }(BABYLON.Action));
  54307. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54308. /**
  54309. * This defines an action responsible to set a the state field of the target
  54310. * to a desired value once triggered.
  54311. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54312. */
  54313. var SetStateAction = /** @class */ (function (_super) {
  54314. __extends(SetStateAction, _super);
  54315. /**
  54316. * Instantiate the action
  54317. * @param triggerOptions defines the trigger options
  54318. * @param target defines the object containing the state property
  54319. * @param value defines the value to store in the state field
  54320. * @param condition defines the trigger related conditions
  54321. */
  54322. function SetStateAction(triggerOptions, target, value, condition) {
  54323. var _this = _super.call(this, triggerOptions, condition) || this;
  54324. _this.value = value;
  54325. _this._target = target;
  54326. return _this;
  54327. }
  54328. /**
  54329. * Execute the action and store the value on the target state property.
  54330. */
  54331. SetStateAction.prototype.execute = function () {
  54332. this._target.state = this.value;
  54333. };
  54334. /**
  54335. * Serializes the actions and its related information.
  54336. * @param parent defines the object to serialize in
  54337. * @returns the serialized object
  54338. */
  54339. SetStateAction.prototype.serialize = function (parent) {
  54340. return _super.prototype._serialize.call(this, {
  54341. name: "SetStateAction",
  54342. properties: [
  54343. BABYLON.Action._GetTargetProperty(this._target),
  54344. { name: "value", value: this.value }
  54345. ]
  54346. }, parent);
  54347. };
  54348. return SetStateAction;
  54349. }(BABYLON.Action));
  54350. BABYLON.SetStateAction = SetStateAction;
  54351. /**
  54352. * This defines an action responsible to set a property of the target
  54353. * to a desired value once triggered.
  54354. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54355. */
  54356. var SetValueAction = /** @class */ (function (_super) {
  54357. __extends(SetValueAction, _super);
  54358. /**
  54359. * Instantiate the action
  54360. * @param triggerOptions defines the trigger options
  54361. * @param target defines the object containing the property
  54362. * @param propertyPath defines the path of the property to set in the target
  54363. * @param value defines the value to set in the property
  54364. * @param condition defines the trigger related conditions
  54365. */
  54366. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54367. var _this = _super.call(this, triggerOptions, condition) || this;
  54368. _this.propertyPath = propertyPath;
  54369. _this.value = value;
  54370. _this._target = _this._effectiveTarget = target;
  54371. return _this;
  54372. }
  54373. /** @hidden */
  54374. SetValueAction.prototype._prepare = function () {
  54375. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54376. this._property = this._getProperty(this.propertyPath);
  54377. };
  54378. /**
  54379. * Execute the action and set the targetted property to the desired value.
  54380. */
  54381. SetValueAction.prototype.execute = function () {
  54382. this._effectiveTarget[this._property] = this.value;
  54383. if (this._target.markAsDirty) {
  54384. this._target.markAsDirty(this._property);
  54385. }
  54386. };
  54387. /**
  54388. * Serializes the actions and its related information.
  54389. * @param parent defines the object to serialize in
  54390. * @returns the serialized object
  54391. */
  54392. SetValueAction.prototype.serialize = function (parent) {
  54393. return _super.prototype._serialize.call(this, {
  54394. name: "SetValueAction",
  54395. properties: [
  54396. BABYLON.Action._GetTargetProperty(this._target),
  54397. { name: "propertyPath", value: this.propertyPath },
  54398. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54399. ]
  54400. }, parent);
  54401. };
  54402. return SetValueAction;
  54403. }(BABYLON.Action));
  54404. BABYLON.SetValueAction = SetValueAction;
  54405. /**
  54406. * This defines an action responsible to increment the target value
  54407. * to a desired value once triggered.
  54408. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54409. */
  54410. var IncrementValueAction = /** @class */ (function (_super) {
  54411. __extends(IncrementValueAction, _super);
  54412. /**
  54413. * Instantiate the action
  54414. * @param triggerOptions defines the trigger options
  54415. * @param target defines the object containing the property
  54416. * @param propertyPath defines the path of the property to increment in the target
  54417. * @param value defines the value value we should increment the property by
  54418. * @param condition defines the trigger related conditions
  54419. */
  54420. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54421. var _this = _super.call(this, triggerOptions, condition) || this;
  54422. _this.propertyPath = propertyPath;
  54423. _this.value = value;
  54424. _this._target = _this._effectiveTarget = target;
  54425. return _this;
  54426. }
  54427. /** @hidden */
  54428. IncrementValueAction.prototype._prepare = function () {
  54429. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54430. this._property = this._getProperty(this.propertyPath);
  54431. if (typeof this._effectiveTarget[this._property] !== "number") {
  54432. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54433. }
  54434. };
  54435. /**
  54436. * Execute the action and increment the target of the value amount.
  54437. */
  54438. IncrementValueAction.prototype.execute = function () {
  54439. this._effectiveTarget[this._property] += this.value;
  54440. if (this._target.markAsDirty) {
  54441. this._target.markAsDirty(this._property);
  54442. }
  54443. };
  54444. /**
  54445. * Serializes the actions and its related information.
  54446. * @param parent defines the object to serialize in
  54447. * @returns the serialized object
  54448. */
  54449. IncrementValueAction.prototype.serialize = function (parent) {
  54450. return _super.prototype._serialize.call(this, {
  54451. name: "IncrementValueAction",
  54452. properties: [
  54453. BABYLON.Action._GetTargetProperty(this._target),
  54454. { name: "propertyPath", value: this.propertyPath },
  54455. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54456. ]
  54457. }, parent);
  54458. };
  54459. return IncrementValueAction;
  54460. }(BABYLON.Action));
  54461. BABYLON.IncrementValueAction = IncrementValueAction;
  54462. /**
  54463. * This defines an action responsible to start an animation once triggered.
  54464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54465. */
  54466. var PlayAnimationAction = /** @class */ (function (_super) {
  54467. __extends(PlayAnimationAction, _super);
  54468. /**
  54469. * Instantiate the action
  54470. * @param triggerOptions defines the trigger options
  54471. * @param target defines the target animation or animation name
  54472. * @param from defines from where the animation should start (animation frame)
  54473. * @param end defines where the animation should stop (animation frame)
  54474. * @param loop defines if the animation should loop or stop after the first play
  54475. * @param condition defines the trigger related conditions
  54476. */
  54477. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54478. var _this = _super.call(this, triggerOptions, condition) || this;
  54479. _this.from = from;
  54480. _this.to = to;
  54481. _this.loop = loop;
  54482. _this._target = target;
  54483. return _this;
  54484. }
  54485. /** @hidden */
  54486. PlayAnimationAction.prototype._prepare = function () {
  54487. };
  54488. /**
  54489. * Execute the action and play the animation.
  54490. */
  54491. PlayAnimationAction.prototype.execute = function () {
  54492. var scene = this._actionManager.getScene();
  54493. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54494. };
  54495. /**
  54496. * Serializes the actions and its related information.
  54497. * @param parent defines the object to serialize in
  54498. * @returns the serialized object
  54499. */
  54500. PlayAnimationAction.prototype.serialize = function (parent) {
  54501. return _super.prototype._serialize.call(this, {
  54502. name: "PlayAnimationAction",
  54503. properties: [
  54504. BABYLON.Action._GetTargetProperty(this._target),
  54505. { name: "from", value: String(this.from) },
  54506. { name: "to", value: String(this.to) },
  54507. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54508. ]
  54509. }, parent);
  54510. };
  54511. return PlayAnimationAction;
  54512. }(BABYLON.Action));
  54513. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54514. /**
  54515. * This defines an action responsible to stop an animation once triggered.
  54516. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54517. */
  54518. var StopAnimationAction = /** @class */ (function (_super) {
  54519. __extends(StopAnimationAction, _super);
  54520. /**
  54521. * Instantiate the action
  54522. * @param triggerOptions defines the trigger options
  54523. * @param target defines the target animation or animation name
  54524. * @param condition defines the trigger related conditions
  54525. */
  54526. function StopAnimationAction(triggerOptions, target, condition) {
  54527. var _this = _super.call(this, triggerOptions, condition) || this;
  54528. _this._target = target;
  54529. return _this;
  54530. }
  54531. /** @hidden */
  54532. StopAnimationAction.prototype._prepare = function () {
  54533. };
  54534. /**
  54535. * Execute the action and stop the animation.
  54536. */
  54537. StopAnimationAction.prototype.execute = function () {
  54538. var scene = this._actionManager.getScene();
  54539. scene.stopAnimation(this._target);
  54540. };
  54541. /**
  54542. * Serializes the actions and its related information.
  54543. * @param parent defines the object to serialize in
  54544. * @returns the serialized object
  54545. */
  54546. StopAnimationAction.prototype.serialize = function (parent) {
  54547. return _super.prototype._serialize.call(this, {
  54548. name: "StopAnimationAction",
  54549. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54550. }, parent);
  54551. };
  54552. return StopAnimationAction;
  54553. }(BABYLON.Action));
  54554. BABYLON.StopAnimationAction = StopAnimationAction;
  54555. /**
  54556. * This defines an action responsible that does nothing once triggered.
  54557. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54558. */
  54559. var DoNothingAction = /** @class */ (function (_super) {
  54560. __extends(DoNothingAction, _super);
  54561. /**
  54562. * Instantiate the action
  54563. * @param triggerOptions defines the trigger options
  54564. * @param condition defines the trigger related conditions
  54565. */
  54566. function DoNothingAction(triggerOptions, condition) {
  54567. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54568. return _super.call(this, triggerOptions, condition) || this;
  54569. }
  54570. /**
  54571. * Execute the action and do nothing.
  54572. */
  54573. DoNothingAction.prototype.execute = function () {
  54574. };
  54575. /**
  54576. * Serializes the actions and its related information.
  54577. * @param parent defines the object to serialize in
  54578. * @returns the serialized object
  54579. */
  54580. DoNothingAction.prototype.serialize = function (parent) {
  54581. return _super.prototype._serialize.call(this, {
  54582. name: "DoNothingAction",
  54583. properties: []
  54584. }, parent);
  54585. };
  54586. return DoNothingAction;
  54587. }(BABYLON.Action));
  54588. BABYLON.DoNothingAction = DoNothingAction;
  54589. /**
  54590. * This defines an action responsible to trigger several actions once triggered.
  54591. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54592. */
  54593. var CombineAction = /** @class */ (function (_super) {
  54594. __extends(CombineAction, _super);
  54595. /**
  54596. * Instantiate the action
  54597. * @param triggerOptions defines the trigger options
  54598. * @param children defines the list of aggregated animations to run
  54599. * @param condition defines the trigger related conditions
  54600. */
  54601. function CombineAction(triggerOptions, children, condition) {
  54602. var _this = _super.call(this, triggerOptions, condition) || this;
  54603. _this.children = children;
  54604. return _this;
  54605. }
  54606. /** @hidden */
  54607. CombineAction.prototype._prepare = function () {
  54608. for (var index = 0; index < this.children.length; index++) {
  54609. this.children[index]._actionManager = this._actionManager;
  54610. this.children[index]._prepare();
  54611. }
  54612. };
  54613. /**
  54614. * Execute the action and executes all the aggregated actions.
  54615. */
  54616. CombineAction.prototype.execute = function (evt) {
  54617. for (var index = 0; index < this.children.length; index++) {
  54618. this.children[index].execute(evt);
  54619. }
  54620. };
  54621. /**
  54622. * Serializes the actions and its related information.
  54623. * @param parent defines the object to serialize in
  54624. * @returns the serialized object
  54625. */
  54626. CombineAction.prototype.serialize = function (parent) {
  54627. var serializationObject = _super.prototype._serialize.call(this, {
  54628. name: "CombineAction",
  54629. properties: [],
  54630. combine: []
  54631. }, parent);
  54632. for (var i = 0; i < this.children.length; i++) {
  54633. serializationObject.combine.push(this.children[i].serialize(null));
  54634. }
  54635. return serializationObject;
  54636. };
  54637. return CombineAction;
  54638. }(BABYLON.Action));
  54639. BABYLON.CombineAction = CombineAction;
  54640. /**
  54641. * This defines an action responsible to run code (external event) once triggered.
  54642. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54643. */
  54644. var ExecuteCodeAction = /** @class */ (function (_super) {
  54645. __extends(ExecuteCodeAction, _super);
  54646. /**
  54647. * Instantiate the action
  54648. * @param triggerOptions defines the trigger options
  54649. * @param func defines the callback function to run
  54650. * @param condition defines the trigger related conditions
  54651. */
  54652. function ExecuteCodeAction(triggerOptions, func, condition) {
  54653. var _this = _super.call(this, triggerOptions, condition) || this;
  54654. _this.func = func;
  54655. return _this;
  54656. }
  54657. /**
  54658. * Execute the action and run the attached code.
  54659. */
  54660. ExecuteCodeAction.prototype.execute = function (evt) {
  54661. this.func(evt);
  54662. };
  54663. return ExecuteCodeAction;
  54664. }(BABYLON.Action));
  54665. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54666. /**
  54667. * This defines an action responsible to set the parent property of the target once triggered.
  54668. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54669. */
  54670. var SetParentAction = /** @class */ (function (_super) {
  54671. __extends(SetParentAction, _super);
  54672. /**
  54673. * Instantiate the action
  54674. * @param triggerOptions defines the trigger options
  54675. * @param target defines the target containing the parent property
  54676. * @param parent defines from where the animation should start (animation frame)
  54677. * @param condition defines the trigger related conditions
  54678. */
  54679. function SetParentAction(triggerOptions, target, parent, condition) {
  54680. var _this = _super.call(this, triggerOptions, condition) || this;
  54681. _this._target = target;
  54682. _this._parent = parent;
  54683. return _this;
  54684. }
  54685. /** @hidden */
  54686. SetParentAction.prototype._prepare = function () {
  54687. };
  54688. /**
  54689. * Execute the action and set the parent property.
  54690. */
  54691. SetParentAction.prototype.execute = function () {
  54692. if (this._target.parent === this._parent) {
  54693. return;
  54694. }
  54695. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54696. invertParentWorldMatrix.invert();
  54697. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54698. this._target.parent = this._parent;
  54699. };
  54700. /**
  54701. * Serializes the actions and its related information.
  54702. * @param parent defines the object to serialize in
  54703. * @returns the serialized object
  54704. */
  54705. SetParentAction.prototype.serialize = function (parent) {
  54706. return _super.prototype._serialize.call(this, {
  54707. name: "SetParentAction",
  54708. properties: [
  54709. BABYLON.Action._GetTargetProperty(this._target),
  54710. BABYLON.Action._GetTargetProperty(this._parent),
  54711. ]
  54712. }, parent);
  54713. };
  54714. return SetParentAction;
  54715. }(BABYLON.Action));
  54716. BABYLON.SetParentAction = SetParentAction;
  54717. })(BABYLON || (BABYLON = {}));
  54718. //# sourceMappingURL=babylon.directActions.js.map
  54719. var BABYLON;
  54720. (function (BABYLON) {
  54721. var SpriteManager = /** @class */ (function () {
  54722. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54723. if (epsilon === void 0) { epsilon = 0.01; }
  54724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54725. this.name = name;
  54726. this.sprites = new Array();
  54727. this.renderingGroupId = 0;
  54728. this.layerMask = 0x0FFFFFFF;
  54729. this.fogEnabled = true;
  54730. this.isPickable = false;
  54731. /**
  54732. * An event triggered when the manager is disposed.
  54733. */
  54734. this.onDisposeObservable = new BABYLON.Observable();
  54735. this._vertexBuffers = {};
  54736. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54737. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54738. }
  54739. this._capacity = capacity;
  54740. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54741. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54742. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54743. if (cellSize.width && cellSize.height) {
  54744. this.cellWidth = cellSize.width;
  54745. this.cellHeight = cellSize.height;
  54746. }
  54747. else if (cellSize !== undefined) {
  54748. this.cellWidth = cellSize;
  54749. this.cellHeight = cellSize;
  54750. }
  54751. else {
  54752. return;
  54753. }
  54754. this._epsilon = epsilon;
  54755. this._scene = scene;
  54756. this._scene.spriteManagers.push(this);
  54757. var indices = [];
  54758. var index = 0;
  54759. for (var count = 0; count < capacity; count++) {
  54760. indices.push(index);
  54761. indices.push(index + 1);
  54762. indices.push(index + 2);
  54763. indices.push(index);
  54764. indices.push(index + 2);
  54765. indices.push(index + 3);
  54766. index += 4;
  54767. }
  54768. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54769. // VBO
  54770. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54771. this._vertexData = new Float32Array(capacity * 16 * 4);
  54772. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54773. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54774. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54775. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54776. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54778. this._vertexBuffers["options"] = options;
  54779. this._vertexBuffers["cellInfo"] = cellInfo;
  54780. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54781. // Effects
  54782. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54783. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54784. }
  54785. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54786. set: function (callback) {
  54787. if (this._onDisposeObserver) {
  54788. this.onDisposeObservable.remove(this._onDisposeObserver);
  54789. }
  54790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54791. },
  54792. enumerable: true,
  54793. configurable: true
  54794. });
  54795. Object.defineProperty(SpriteManager.prototype, "texture", {
  54796. get: function () {
  54797. return this._spriteTexture;
  54798. },
  54799. set: function (value) {
  54800. this._spriteTexture = value;
  54801. },
  54802. enumerable: true,
  54803. configurable: true
  54804. });
  54805. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54806. var arrayOffset = index * 16;
  54807. if (offsetX === 0)
  54808. offsetX = this._epsilon;
  54809. else if (offsetX === 1)
  54810. offsetX = 1 - this._epsilon;
  54811. if (offsetY === 0)
  54812. offsetY = this._epsilon;
  54813. else if (offsetY === 1)
  54814. offsetY = 1 - this._epsilon;
  54815. this._vertexData[arrayOffset] = sprite.position.x;
  54816. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54817. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54818. this._vertexData[arrayOffset + 3] = sprite.angle;
  54819. this._vertexData[arrayOffset + 4] = sprite.width;
  54820. this._vertexData[arrayOffset + 5] = sprite.height;
  54821. this._vertexData[arrayOffset + 6] = offsetX;
  54822. this._vertexData[arrayOffset + 7] = offsetY;
  54823. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54824. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54825. var offset = (sprite.cellIndex / rowSize) >> 0;
  54826. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54827. this._vertexData[arrayOffset + 11] = offset;
  54828. // Color
  54829. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54830. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54831. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54832. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54833. };
  54834. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54835. var count = Math.min(this._capacity, this.sprites.length);
  54836. var min = BABYLON.Vector3.Zero();
  54837. var max = BABYLON.Vector3.Zero();
  54838. var distance = Number.MAX_VALUE;
  54839. var currentSprite = null;
  54840. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54841. var cameraView = camera.getViewMatrix();
  54842. for (var index = 0; index < count; index++) {
  54843. var sprite = this.sprites[index];
  54844. if (!sprite) {
  54845. continue;
  54846. }
  54847. if (predicate) {
  54848. if (!predicate(sprite)) {
  54849. continue;
  54850. }
  54851. }
  54852. else if (!sprite.isPickable) {
  54853. continue;
  54854. }
  54855. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54856. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54857. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54858. if (ray.intersectsBoxMinMax(min, max)) {
  54859. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54860. if (distance > currentDistance) {
  54861. distance = currentDistance;
  54862. currentSprite = sprite;
  54863. if (fastCheck) {
  54864. break;
  54865. }
  54866. }
  54867. }
  54868. }
  54869. if (currentSprite) {
  54870. var result = new BABYLON.PickingInfo();
  54871. result.hit = true;
  54872. result.pickedSprite = currentSprite;
  54873. result.distance = distance;
  54874. return result;
  54875. }
  54876. return null;
  54877. };
  54878. SpriteManager.prototype.render = function () {
  54879. // Check
  54880. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54881. return;
  54882. var engine = this._scene.getEngine();
  54883. var baseSize = this._spriteTexture.getBaseSize();
  54884. // Sprites
  54885. var deltaTime = engine.getDeltaTime();
  54886. var max = Math.min(this._capacity, this.sprites.length);
  54887. var rowSize = baseSize.width / this.cellWidth;
  54888. var offset = 0;
  54889. for (var index = 0; index < max; index++) {
  54890. var sprite = this.sprites[index];
  54891. if (!sprite || !sprite.isVisible) {
  54892. continue;
  54893. }
  54894. sprite._animate(deltaTime);
  54895. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54896. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54897. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54898. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54899. }
  54900. this._buffer.update(this._vertexData);
  54901. // Render
  54902. var effect = this._effectBase;
  54903. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54904. effect = this._effectFog;
  54905. }
  54906. engine.enableEffect(effect);
  54907. var viewMatrix = this._scene.getViewMatrix();
  54908. effect.setTexture("diffuseSampler", this._spriteTexture);
  54909. effect.setMatrix("view", viewMatrix);
  54910. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54911. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54912. // Fog
  54913. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54914. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54915. effect.setColor3("vFogColor", this._scene.fogColor);
  54916. }
  54917. // VBOs
  54918. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54919. // Draw order
  54920. engine.setDepthFunctionToLessOrEqual();
  54921. effect.setBool("alphaTest", true);
  54922. engine.setColorWrite(false);
  54923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54924. engine.setColorWrite(true);
  54925. effect.setBool("alphaTest", false);
  54926. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54927. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54929. };
  54930. SpriteManager.prototype.dispose = function () {
  54931. if (this._buffer) {
  54932. this._buffer.dispose();
  54933. this._buffer = null;
  54934. }
  54935. if (this._indexBuffer) {
  54936. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54937. this._indexBuffer = null;
  54938. }
  54939. if (this._spriteTexture) {
  54940. this._spriteTexture.dispose();
  54941. this._spriteTexture = null;
  54942. }
  54943. // Remove from scene
  54944. var index = this._scene.spriteManagers.indexOf(this);
  54945. this._scene.spriteManagers.splice(index, 1);
  54946. // Callback
  54947. this.onDisposeObservable.notifyObservers(this);
  54948. this.onDisposeObservable.clear();
  54949. };
  54950. return SpriteManager;
  54951. }());
  54952. BABYLON.SpriteManager = SpriteManager;
  54953. })(BABYLON || (BABYLON = {}));
  54954. //# sourceMappingURL=babylon.spriteManager.js.map
  54955. var BABYLON;
  54956. (function (BABYLON) {
  54957. var Sprite = /** @class */ (function () {
  54958. function Sprite(name, manager) {
  54959. this.name = name;
  54960. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54961. this.width = 1.0;
  54962. this.height = 1.0;
  54963. this.angle = 0;
  54964. this.cellIndex = 0;
  54965. this.invertU = 0;
  54966. this.invertV = 0;
  54967. this.animations = new Array();
  54968. this.isPickable = false;
  54969. this._animationStarted = false;
  54970. this._loopAnimation = false;
  54971. this._fromIndex = 0;
  54972. this._toIndex = 0;
  54973. this._delay = 0;
  54974. this._direction = 1;
  54975. this._time = 0;
  54976. /**
  54977. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54978. */
  54979. this.isVisible = true;
  54980. this._manager = manager;
  54981. this._manager.sprites.push(this);
  54982. this.position = BABYLON.Vector3.Zero();
  54983. }
  54984. Object.defineProperty(Sprite.prototype, "size", {
  54985. get: function () {
  54986. return this.width;
  54987. },
  54988. set: function (value) {
  54989. this.width = value;
  54990. this.height = value;
  54991. },
  54992. enumerable: true,
  54993. configurable: true
  54994. });
  54995. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54996. this._fromIndex = from;
  54997. this._toIndex = to;
  54998. this._loopAnimation = loop;
  54999. this._delay = delay;
  55000. this._animationStarted = true;
  55001. this._direction = from < to ? 1 : -1;
  55002. this.cellIndex = from;
  55003. this._time = 0;
  55004. this._onAnimationEnd = onAnimationEnd;
  55005. };
  55006. Sprite.prototype.stopAnimation = function () {
  55007. this._animationStarted = false;
  55008. };
  55009. /** @hidden */
  55010. Sprite.prototype._animate = function (deltaTime) {
  55011. if (!this._animationStarted)
  55012. return;
  55013. this._time += deltaTime;
  55014. if (this._time > this._delay) {
  55015. this._time = this._time % this._delay;
  55016. this.cellIndex += this._direction;
  55017. if (this.cellIndex > this._toIndex) {
  55018. if (this._loopAnimation) {
  55019. this.cellIndex = this._fromIndex;
  55020. }
  55021. else {
  55022. this.cellIndex = this._toIndex;
  55023. this._animationStarted = false;
  55024. if (this._onAnimationEnd) {
  55025. this._onAnimationEnd();
  55026. }
  55027. if (this.disposeWhenFinishedAnimating) {
  55028. this.dispose();
  55029. }
  55030. }
  55031. }
  55032. }
  55033. };
  55034. Sprite.prototype.dispose = function () {
  55035. for (var i = 0; i < this._manager.sprites.length; i++) {
  55036. if (this._manager.sprites[i] == this) {
  55037. this._manager.sprites.splice(i, 1);
  55038. }
  55039. }
  55040. };
  55041. return Sprite;
  55042. }());
  55043. BABYLON.Sprite = Sprite;
  55044. })(BABYLON || (BABYLON = {}));
  55045. //# sourceMappingURL=babylon.sprite.js.map
  55046. var BABYLON;
  55047. (function (BABYLON) {
  55048. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55049. if (!BABYLON.PickingInfo) {
  55050. return null;
  55051. }
  55052. var pickingInfo = null;
  55053. if (!camera) {
  55054. if (!this.activeCamera) {
  55055. return null;
  55056. }
  55057. camera = this.activeCamera;
  55058. }
  55059. if (this.spriteManagers.length > 0) {
  55060. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55061. var spriteManager = this.spriteManagers[spriteIndex];
  55062. if (!spriteManager.isPickable) {
  55063. continue;
  55064. }
  55065. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55066. if (!result || !result.hit)
  55067. continue;
  55068. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55069. continue;
  55070. pickingInfo = result;
  55071. if (fastCheck) {
  55072. break;
  55073. }
  55074. }
  55075. }
  55076. return pickingInfo || new BABYLON.PickingInfo();
  55077. };
  55078. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55079. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55080. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55081. };
  55082. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55083. if (!this._tempSpritePickingRay) {
  55084. return null;
  55085. }
  55086. if (!camera) {
  55087. if (!this.activeCamera) {
  55088. return null;
  55089. }
  55090. camera = this.activeCamera;
  55091. }
  55092. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55093. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55094. };
  55095. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55096. if (this._pointerOverSprite === sprite) {
  55097. return;
  55098. }
  55099. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55100. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55101. }
  55102. this._pointerOverSprite = sprite;
  55103. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55104. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55105. }
  55106. };
  55107. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55108. return this._pointerOverSprite;
  55109. };
  55110. /**
  55111. * Defines the sprite scene component responsible to manage sprites
  55112. * in a given scene.
  55113. */
  55114. var SpriteSceneComponent = /** @class */ (function () {
  55115. /**
  55116. * Creates a new instance of the component for the given scene
  55117. * @param scene Defines the scene to register the component in
  55118. */
  55119. function SpriteSceneComponent(scene) {
  55120. /**
  55121. * The component name helpfull to identify the component in the list of scene components.
  55122. */
  55123. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55124. this.scene = scene;
  55125. this.scene.spriteManagers = new Array();
  55126. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55127. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55128. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55129. this._spritePredicate = function (sprite) {
  55130. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55131. };
  55132. }
  55133. /**
  55134. * Registers the component in a given scene
  55135. */
  55136. SpriteSceneComponent.prototype.register = function () {
  55137. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55138. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55139. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55140. };
  55141. /**
  55142. * Rebuilds the elements related to this component in case of
  55143. * context lost for instance.
  55144. */
  55145. SpriteSceneComponent.prototype.rebuild = function () {
  55146. /** Nothing to do for sprites */
  55147. };
  55148. /**
  55149. * Disposes the component and the associated ressources.
  55150. */
  55151. SpriteSceneComponent.prototype.dispose = function () {
  55152. this.scene.onBeforeSpritesRenderingObservable.clear();
  55153. this.scene.onAfterSpritesRenderingObservable.clear();
  55154. var spriteManagers = this.scene.spriteManagers;
  55155. while (spriteManagers.length) {
  55156. spriteManagers[0].dispose();
  55157. }
  55158. };
  55159. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55160. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55161. if (result) {
  55162. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55163. }
  55164. return result;
  55165. };
  55166. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55167. var scene = this.scene;
  55168. if (isMeshPicked) {
  55169. scene.setPointerOverSprite(null);
  55170. }
  55171. else {
  55172. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55173. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55174. scene.setPointerOverSprite(pickResult.pickedSprite);
  55175. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55176. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55177. }
  55178. else {
  55179. canvas.style.cursor = scene.hoverCursor;
  55180. }
  55181. }
  55182. else {
  55183. scene.setPointerOverSprite(null);
  55184. }
  55185. }
  55186. return pickResult;
  55187. };
  55188. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55189. var scene = this.scene;
  55190. scene._pickedDownSprite = null;
  55191. if (scene.spriteManagers.length > 0) {
  55192. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55193. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55194. if (pickResult.pickedSprite.actionManager) {
  55195. scene._pickedDownSprite = pickResult.pickedSprite;
  55196. switch (evt.button) {
  55197. case 0:
  55198. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55199. break;
  55200. case 1:
  55201. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55202. break;
  55203. case 2:
  55204. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55205. break;
  55206. }
  55207. if (pickResult.pickedSprite.actionManager) {
  55208. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55209. }
  55210. }
  55211. }
  55212. }
  55213. return pickResult;
  55214. };
  55215. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55216. var scene = this.scene;
  55217. if (scene.spriteManagers.length > 0) {
  55218. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55219. if (spritePickResult) {
  55220. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55221. if (spritePickResult.pickedSprite.actionManager) {
  55222. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55223. if (spritePickResult.pickedSprite.actionManager) {
  55224. if (!this.scene._isPointerSwiping()) {
  55225. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55226. }
  55227. }
  55228. }
  55229. }
  55230. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55231. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55232. }
  55233. }
  55234. }
  55235. return pickResult;
  55236. };
  55237. return SpriteSceneComponent;
  55238. }());
  55239. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55240. })(BABYLON || (BABYLON = {}));
  55241. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55242. var BABYLON;
  55243. (function (BABYLON) {
  55244. var IntersectionInfo = /** @class */ (function () {
  55245. function IntersectionInfo(bu, bv, distance) {
  55246. this.bu = bu;
  55247. this.bv = bv;
  55248. this.distance = distance;
  55249. this.faceId = 0;
  55250. this.subMeshId = 0;
  55251. }
  55252. return IntersectionInfo;
  55253. }());
  55254. BABYLON.IntersectionInfo = IntersectionInfo;
  55255. /**
  55256. * Information about the result of picking within a scene
  55257. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55258. */
  55259. var PickingInfo = /** @class */ (function () {
  55260. function PickingInfo() {
  55261. /**
  55262. * If the pick collided with an object
  55263. */
  55264. this.hit = false;
  55265. /**
  55266. * Distance away where the pick collided
  55267. */
  55268. this.distance = 0;
  55269. /**
  55270. * The location of pick collision
  55271. */
  55272. this.pickedPoint = null;
  55273. /**
  55274. * The mesh corresponding the the pick collision
  55275. */
  55276. this.pickedMesh = null;
  55277. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55278. this.bu = 0;
  55279. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55280. this.bv = 0;
  55281. /** The id of the face on the mesh that was picked */
  55282. this.faceId = -1;
  55283. /** Id of the the submesh that was picked */
  55284. this.subMeshId = 0;
  55285. /** If a sprite was picked, this will be the sprite the pick collided with */
  55286. this.pickedSprite = null;
  55287. /**
  55288. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55289. */
  55290. this.originMesh = null;
  55291. /**
  55292. * The ray that was used to perform the picking.
  55293. */
  55294. this.ray = null;
  55295. }
  55296. /**
  55297. * Gets the normal correspodning to the face the pick collided with
  55298. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55299. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55300. * @returns The normal correspodning to the face the pick collided with
  55301. */
  55302. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55303. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55304. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55305. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55306. return null;
  55307. }
  55308. var indices = this.pickedMesh.getIndices();
  55309. if (!indices) {
  55310. return null;
  55311. }
  55312. var result;
  55313. if (useVerticesNormals) {
  55314. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55315. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55316. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55317. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55318. normal0 = normal0.scale(this.bu);
  55319. normal1 = normal1.scale(this.bv);
  55320. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55321. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55322. }
  55323. else {
  55324. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55325. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55326. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55327. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55328. var p1p2 = vertex1.subtract(vertex2);
  55329. var p3p2 = vertex3.subtract(vertex2);
  55330. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55331. }
  55332. if (useWorldCoordinates) {
  55333. var wm = this.pickedMesh.getWorldMatrix();
  55334. if (this.pickedMesh.nonUniformScaling) {
  55335. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55336. wm = BABYLON.Tmp.Matrix[0];
  55337. wm.setTranslationFromFloats(0, 0, 0);
  55338. wm.invert();
  55339. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55340. wm = BABYLON.Tmp.Matrix[1];
  55341. }
  55342. result = BABYLON.Vector3.TransformNormal(result, wm);
  55343. }
  55344. result.normalize();
  55345. return result;
  55346. };
  55347. /**
  55348. * Gets the texture coordinates of where the pick occured
  55349. * @returns the vector containing the coordnates of the texture
  55350. */
  55351. PickingInfo.prototype.getTextureCoordinates = function () {
  55352. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55353. return null;
  55354. }
  55355. var indices = this.pickedMesh.getIndices();
  55356. if (!indices) {
  55357. return null;
  55358. }
  55359. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55360. if (!uvs) {
  55361. return null;
  55362. }
  55363. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55364. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55365. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55366. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55367. uv1 = uv1.scale(this.bu);
  55368. uv2 = uv2.scale(this.bv);
  55369. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55370. };
  55371. return PickingInfo;
  55372. }());
  55373. BABYLON.PickingInfo = PickingInfo;
  55374. })(BABYLON || (BABYLON = {}));
  55375. //# sourceMappingURL=babylon.pickingInfo.js.map
  55376. var BABYLON;
  55377. (function (BABYLON) {
  55378. var Ray = /** @class */ (function () {
  55379. function Ray(origin, direction, length) {
  55380. if (length === void 0) { length = Number.MAX_VALUE; }
  55381. this.origin = origin;
  55382. this.direction = direction;
  55383. this.length = length;
  55384. }
  55385. // Methods
  55386. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55387. var d = 0.0;
  55388. var maxValue = Number.MAX_VALUE;
  55389. var inv;
  55390. var min;
  55391. var max;
  55392. var temp;
  55393. if (Math.abs(this.direction.x) < 0.0000001) {
  55394. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55395. return false;
  55396. }
  55397. }
  55398. else {
  55399. inv = 1.0 / this.direction.x;
  55400. min = (minimum.x - this.origin.x) * inv;
  55401. max = (maximum.x - this.origin.x) * inv;
  55402. if (max === -Infinity) {
  55403. max = Infinity;
  55404. }
  55405. if (min > max) {
  55406. temp = min;
  55407. min = max;
  55408. max = temp;
  55409. }
  55410. d = Math.max(min, d);
  55411. maxValue = Math.min(max, maxValue);
  55412. if (d > maxValue) {
  55413. return false;
  55414. }
  55415. }
  55416. if (Math.abs(this.direction.y) < 0.0000001) {
  55417. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55418. return false;
  55419. }
  55420. }
  55421. else {
  55422. inv = 1.0 / this.direction.y;
  55423. min = (minimum.y - this.origin.y) * inv;
  55424. max = (maximum.y - this.origin.y) * inv;
  55425. if (max === -Infinity) {
  55426. max = Infinity;
  55427. }
  55428. if (min > max) {
  55429. temp = min;
  55430. min = max;
  55431. max = temp;
  55432. }
  55433. d = Math.max(min, d);
  55434. maxValue = Math.min(max, maxValue);
  55435. if (d > maxValue) {
  55436. return false;
  55437. }
  55438. }
  55439. if (Math.abs(this.direction.z) < 0.0000001) {
  55440. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55441. return false;
  55442. }
  55443. }
  55444. else {
  55445. inv = 1.0 / this.direction.z;
  55446. min = (minimum.z - this.origin.z) * inv;
  55447. max = (maximum.z - this.origin.z) * inv;
  55448. if (max === -Infinity) {
  55449. max = Infinity;
  55450. }
  55451. if (min > max) {
  55452. temp = min;
  55453. min = max;
  55454. max = temp;
  55455. }
  55456. d = Math.max(min, d);
  55457. maxValue = Math.min(max, maxValue);
  55458. if (d > maxValue) {
  55459. return false;
  55460. }
  55461. }
  55462. return true;
  55463. };
  55464. Ray.prototype.intersectsBox = function (box) {
  55465. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55466. };
  55467. Ray.prototype.intersectsSphere = function (sphere) {
  55468. var x = sphere.center.x - this.origin.x;
  55469. var y = sphere.center.y - this.origin.y;
  55470. var z = sphere.center.z - this.origin.z;
  55471. var pyth = (x * x) + (y * y) + (z * z);
  55472. var rr = sphere.radius * sphere.radius;
  55473. if (pyth <= rr) {
  55474. return true;
  55475. }
  55476. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55477. if (dot < 0.0) {
  55478. return false;
  55479. }
  55480. var temp = pyth - (dot * dot);
  55481. return temp <= rr;
  55482. };
  55483. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55484. if (!this._edge1) {
  55485. this._edge1 = BABYLON.Vector3.Zero();
  55486. this._edge2 = BABYLON.Vector3.Zero();
  55487. this._pvec = BABYLON.Vector3.Zero();
  55488. this._tvec = BABYLON.Vector3.Zero();
  55489. this._qvec = BABYLON.Vector3.Zero();
  55490. }
  55491. vertex1.subtractToRef(vertex0, this._edge1);
  55492. vertex2.subtractToRef(vertex0, this._edge2);
  55493. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55494. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55495. if (det === 0) {
  55496. return null;
  55497. }
  55498. var invdet = 1 / det;
  55499. this.origin.subtractToRef(vertex0, this._tvec);
  55500. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55501. if (bu < 0 || bu > 1.0) {
  55502. return null;
  55503. }
  55504. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55505. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55506. if (bv < 0 || bu + bv > 1.0) {
  55507. return null;
  55508. }
  55509. //check if the distance is longer than the predefined length.
  55510. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55511. if (distance > this.length) {
  55512. return null;
  55513. }
  55514. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55515. };
  55516. Ray.prototype.intersectsPlane = function (plane) {
  55517. var distance;
  55518. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55519. if (Math.abs(result1) < 9.99999997475243E-07) {
  55520. return null;
  55521. }
  55522. else {
  55523. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55524. distance = (-plane.d - result2) / result1;
  55525. if (distance < 0.0) {
  55526. if (distance < -9.99999997475243E-07) {
  55527. return null;
  55528. }
  55529. else {
  55530. return 0;
  55531. }
  55532. }
  55533. return distance;
  55534. }
  55535. };
  55536. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55537. var tm = BABYLON.Tmp.Matrix[0];
  55538. mesh.getWorldMatrix().invertToRef(tm);
  55539. if (this._tmpRay) {
  55540. Ray.TransformToRef(this, tm, this._tmpRay);
  55541. }
  55542. else {
  55543. this._tmpRay = Ray.Transform(this, tm);
  55544. }
  55545. return mesh.intersects(this._tmpRay, fastCheck);
  55546. };
  55547. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55548. if (results) {
  55549. results.length = 0;
  55550. }
  55551. else {
  55552. results = [];
  55553. }
  55554. for (var i = 0; i < meshes.length; i++) {
  55555. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55556. if (pickInfo.hit) {
  55557. results.push(pickInfo);
  55558. }
  55559. }
  55560. results.sort(this._comparePickingInfo);
  55561. return results;
  55562. };
  55563. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55564. if (pickingInfoA.distance < pickingInfoB.distance) {
  55565. return -1;
  55566. }
  55567. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55568. return 1;
  55569. }
  55570. else {
  55571. return 0;
  55572. }
  55573. };
  55574. /**
  55575. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55576. * @param sega the first point of the segment to test the intersection against
  55577. * @param segb the second point of the segment to test the intersection against
  55578. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55579. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55580. */
  55581. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55582. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55583. var u = segb.subtract(sega);
  55584. var v = rsegb.subtract(this.origin);
  55585. var w = sega.subtract(this.origin);
  55586. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55587. var b = BABYLON.Vector3.Dot(u, v);
  55588. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55589. var d = BABYLON.Vector3.Dot(u, w);
  55590. var e = BABYLON.Vector3.Dot(v, w);
  55591. var D = a * c - b * b; // always >= 0
  55592. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55593. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55594. // compute the line parameters of the two closest points
  55595. if (D < Ray.smallnum) { // the lines are almost parallel
  55596. sN = 0.0; // force using point P0 on segment S1
  55597. sD = 1.0; // to prevent possible division by 0.0 later
  55598. tN = e;
  55599. tD = c;
  55600. }
  55601. else { // get the closest points on the infinite lines
  55602. sN = (b * e - c * d);
  55603. tN = (a * e - b * d);
  55604. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55605. sN = 0.0;
  55606. tN = e;
  55607. tD = c;
  55608. }
  55609. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55610. sN = sD;
  55611. tN = e + b;
  55612. tD = c;
  55613. }
  55614. }
  55615. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55616. tN = 0.0;
  55617. // recompute sc for this edge
  55618. if (-d < 0.0) {
  55619. sN = 0.0;
  55620. }
  55621. else if (-d > a)
  55622. sN = sD;
  55623. else {
  55624. sN = -d;
  55625. sD = a;
  55626. }
  55627. }
  55628. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55629. tN = tD;
  55630. // recompute sc for this edge
  55631. if ((-d + b) < 0.0) {
  55632. sN = 0;
  55633. }
  55634. else if ((-d + b) > a) {
  55635. sN = sD;
  55636. }
  55637. else {
  55638. sN = (-d + b);
  55639. sD = a;
  55640. }
  55641. }
  55642. // finally do the division to get sc and tc
  55643. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55644. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55645. // get the difference of the two closest points
  55646. var qtc = v.multiplyByFloats(tc, tc, tc);
  55647. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55648. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55649. if (isIntersected) {
  55650. return qtc.length();
  55651. }
  55652. return -1;
  55653. };
  55654. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55655. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55656. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55657. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55658. this.direction.normalize();
  55659. return this;
  55660. };
  55661. // Statics
  55662. Ray.Zero = function () {
  55663. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55664. };
  55665. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55666. var result = Ray.Zero();
  55667. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55668. };
  55669. /**
  55670. * 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
  55671. * transformed to the given world matrix.
  55672. * @param origin The origin point
  55673. * @param end The end point
  55674. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55675. */
  55676. Ray.CreateNewFromTo = function (origin, end, world) {
  55677. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55678. var direction = end.subtract(origin);
  55679. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55680. direction.normalize();
  55681. return Ray.Transform(new Ray(origin, direction, length), world);
  55682. };
  55683. Ray.Transform = function (ray, matrix) {
  55684. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55685. Ray.TransformToRef(ray, matrix, result);
  55686. return result;
  55687. };
  55688. Ray.TransformToRef = function (ray, matrix, result) {
  55689. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55690. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55691. result.length = ray.length;
  55692. var dir = result.direction;
  55693. var len = dir.length();
  55694. if (!(len === 0 || len === 1)) {
  55695. var num = 1.0 / len;
  55696. dir.x *= num;
  55697. dir.y *= num;
  55698. dir.z *= num;
  55699. result.length *= len;
  55700. }
  55701. };
  55702. Ray.smallnum = 0.00000001;
  55703. Ray.rayl = 10e8;
  55704. return Ray;
  55705. }());
  55706. BABYLON.Ray = Ray;
  55707. })(BABYLON || (BABYLON = {}));
  55708. //# sourceMappingURL=babylon.ray.js.map
  55709. var BABYLON;
  55710. (function (BABYLON) {
  55711. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55712. if (boxMin.x > sphereCenter.x + sphereRadius)
  55713. return false;
  55714. if (sphereCenter.x - sphereRadius > boxMax.x)
  55715. return false;
  55716. if (boxMin.y > sphereCenter.y + sphereRadius)
  55717. return false;
  55718. if (sphereCenter.y - sphereRadius > boxMax.y)
  55719. return false;
  55720. if (boxMin.z > sphereCenter.z + sphereRadius)
  55721. return false;
  55722. if (sphereCenter.z - sphereRadius > boxMax.z)
  55723. return false;
  55724. return true;
  55725. };
  55726. var getLowestRoot = (function () {
  55727. var result = { root: 0, found: false };
  55728. return function (a, b, c, maxR) {
  55729. result.root = 0;
  55730. result.found = false;
  55731. var determinant = b * b - 4.0 * a * c;
  55732. if (determinant < 0)
  55733. return result;
  55734. var sqrtD = Math.sqrt(determinant);
  55735. var r1 = (-b - sqrtD) / (2.0 * a);
  55736. var r2 = (-b + sqrtD) / (2.0 * a);
  55737. if (r1 > r2) {
  55738. var temp = r2;
  55739. r2 = r1;
  55740. r1 = temp;
  55741. }
  55742. if (r1 > 0 && r1 < maxR) {
  55743. result.root = r1;
  55744. result.found = true;
  55745. return result;
  55746. }
  55747. if (r2 > 0 && r2 < maxR) {
  55748. result.root = r2;
  55749. result.found = true;
  55750. return result;
  55751. }
  55752. return result;
  55753. };
  55754. })();
  55755. /** @hidden */
  55756. var Collider = /** @class */ (function () {
  55757. function Collider() {
  55758. this._collisionPoint = BABYLON.Vector3.Zero();
  55759. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55760. this._tempVector = BABYLON.Vector3.Zero();
  55761. this._tempVector2 = BABYLON.Vector3.Zero();
  55762. this._tempVector3 = BABYLON.Vector3.Zero();
  55763. this._tempVector4 = BABYLON.Vector3.Zero();
  55764. this._edge = BABYLON.Vector3.Zero();
  55765. this._baseToVertex = BABYLON.Vector3.Zero();
  55766. this._destinationPoint = BABYLON.Vector3.Zero();
  55767. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55768. this._displacementVector = BABYLON.Vector3.Zero();
  55769. /** @hidden */
  55770. this._radius = BABYLON.Vector3.One();
  55771. /** @hidden */
  55772. this._retry = 0;
  55773. /** @hidden */
  55774. this._basePointWorld = BABYLON.Vector3.Zero();
  55775. this._velocityWorld = BABYLON.Vector3.Zero();
  55776. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55777. this._collisionMask = -1;
  55778. }
  55779. Object.defineProperty(Collider.prototype, "collisionMask", {
  55780. get: function () {
  55781. return this._collisionMask;
  55782. },
  55783. set: function (mask) {
  55784. this._collisionMask = !isNaN(mask) ? mask : -1;
  55785. },
  55786. enumerable: true,
  55787. configurable: true
  55788. });
  55789. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55790. /**
  55791. * Gets the plane normal used to compute the sliding response (in local space)
  55792. */
  55793. get: function () {
  55794. return this._slidePlaneNormal;
  55795. },
  55796. enumerable: true,
  55797. configurable: true
  55798. });
  55799. // Methods
  55800. /** @hidden */
  55801. Collider.prototype._initialize = function (source, dir, e) {
  55802. this._velocity = dir;
  55803. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55804. this._basePoint = source;
  55805. source.multiplyToRef(this._radius, this._basePointWorld);
  55806. dir.multiplyToRef(this._radius, this._velocityWorld);
  55807. this._velocityWorldLength = this._velocityWorld.length();
  55808. this._epsilon = e;
  55809. this.collisionFound = false;
  55810. };
  55811. /** @hidden */
  55812. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55813. pa.subtractToRef(point, this._tempVector);
  55814. pb.subtractToRef(point, this._tempVector2);
  55815. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55816. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55817. if (d < 0)
  55818. return false;
  55819. pc.subtractToRef(point, this._tempVector3);
  55820. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55821. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55822. if (d < 0)
  55823. return false;
  55824. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55825. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55826. return d >= 0;
  55827. };
  55828. /** @hidden */
  55829. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55830. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55831. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55832. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55833. return false;
  55834. }
  55835. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55836. return false;
  55837. return true;
  55838. };
  55839. /** @hidden */
  55840. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55841. var t0;
  55842. var embeddedInPlane = false;
  55843. //defensive programming, actually not needed.
  55844. if (!trianglePlaneArray) {
  55845. trianglePlaneArray = [];
  55846. }
  55847. if (!trianglePlaneArray[faceIndex]) {
  55848. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55849. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55850. }
  55851. var trianglePlane = trianglePlaneArray[faceIndex];
  55852. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55853. return;
  55854. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55855. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55856. if (normalDotVelocity == 0) {
  55857. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55858. return;
  55859. embeddedInPlane = true;
  55860. t0 = 0;
  55861. }
  55862. else {
  55863. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55864. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55865. if (t0 > t1) {
  55866. var temp = t1;
  55867. t1 = t0;
  55868. t0 = temp;
  55869. }
  55870. if (t0 > 1.0 || t1 < 0.0)
  55871. return;
  55872. if (t0 < 0)
  55873. t0 = 0;
  55874. if (t0 > 1.0)
  55875. t0 = 1.0;
  55876. }
  55877. this._collisionPoint.copyFromFloats(0, 0, 0);
  55878. var found = false;
  55879. var t = 1.0;
  55880. if (!embeddedInPlane) {
  55881. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55882. this._velocity.scaleToRef(t0, this._tempVector);
  55883. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55884. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55885. found = true;
  55886. t = t0;
  55887. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55888. }
  55889. }
  55890. if (!found) {
  55891. var velocitySquaredLength = this._velocity.lengthSquared();
  55892. var a = velocitySquaredLength;
  55893. this._basePoint.subtractToRef(p1, this._tempVector);
  55894. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55895. var c = this._tempVector.lengthSquared() - 1.0;
  55896. var lowestRoot = getLowestRoot(a, b, c, t);
  55897. if (lowestRoot.found) {
  55898. t = lowestRoot.root;
  55899. found = true;
  55900. this._collisionPoint.copyFrom(p1);
  55901. }
  55902. this._basePoint.subtractToRef(p2, this._tempVector);
  55903. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55904. c = this._tempVector.lengthSquared() - 1.0;
  55905. lowestRoot = getLowestRoot(a, b, c, t);
  55906. if (lowestRoot.found) {
  55907. t = lowestRoot.root;
  55908. found = true;
  55909. this._collisionPoint.copyFrom(p2);
  55910. }
  55911. this._basePoint.subtractToRef(p3, this._tempVector);
  55912. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55913. c = this._tempVector.lengthSquared() - 1.0;
  55914. lowestRoot = getLowestRoot(a, b, c, t);
  55915. if (lowestRoot.found) {
  55916. t = lowestRoot.root;
  55917. found = true;
  55918. this._collisionPoint.copyFrom(p3);
  55919. }
  55920. p2.subtractToRef(p1, this._edge);
  55921. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55922. var edgeSquaredLength = this._edge.lengthSquared();
  55923. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55924. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55925. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55926. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55927. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55928. lowestRoot = getLowestRoot(a, b, c, t);
  55929. if (lowestRoot.found) {
  55930. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55931. if (f >= 0.0 && f <= 1.0) {
  55932. t = lowestRoot.root;
  55933. found = true;
  55934. this._edge.scaleInPlace(f);
  55935. p1.addToRef(this._edge, this._collisionPoint);
  55936. }
  55937. }
  55938. p3.subtractToRef(p2, this._edge);
  55939. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55940. edgeSquaredLength = this._edge.lengthSquared();
  55941. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55942. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55943. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55944. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55945. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55946. lowestRoot = getLowestRoot(a, b, c, t);
  55947. if (lowestRoot.found) {
  55948. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55949. if (f >= 0.0 && f <= 1.0) {
  55950. t = lowestRoot.root;
  55951. found = true;
  55952. this._edge.scaleInPlace(f);
  55953. p2.addToRef(this._edge, this._collisionPoint);
  55954. }
  55955. }
  55956. p1.subtractToRef(p3, this._edge);
  55957. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55958. edgeSquaredLength = this._edge.lengthSquared();
  55959. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55960. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55961. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55962. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55963. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55964. lowestRoot = getLowestRoot(a, b, c, t);
  55965. if (lowestRoot.found) {
  55966. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55967. if (f >= 0.0 && f <= 1.0) {
  55968. t = lowestRoot.root;
  55969. found = true;
  55970. this._edge.scaleInPlace(f);
  55971. p3.addToRef(this._edge, this._collisionPoint);
  55972. }
  55973. }
  55974. }
  55975. if (found) {
  55976. var distToCollision = t * this._velocity.length();
  55977. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55978. if (!this.intersectionPoint) {
  55979. this.intersectionPoint = this._collisionPoint.clone();
  55980. }
  55981. else {
  55982. this.intersectionPoint.copyFrom(this._collisionPoint);
  55983. }
  55984. this._nearestDistance = distToCollision;
  55985. this.collisionFound = true;
  55986. }
  55987. }
  55988. };
  55989. /** @hidden */
  55990. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55991. for (var i = indexStart; i < indexEnd; i += 3) {
  55992. var p1 = pts[indices[i] - decal];
  55993. var p2 = pts[indices[i + 1] - decal];
  55994. var p3 = pts[indices[i + 2] - decal];
  55995. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55996. }
  55997. };
  55998. /** @hidden */
  55999. Collider.prototype._getResponse = function (pos, vel) {
  56000. pos.addToRef(vel, this._destinationPoint);
  56001. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56002. this._basePoint.addToRef(vel, pos);
  56003. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56004. this._slidePlaneNormal.normalize();
  56005. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56006. pos.addInPlace(this._displacementVector);
  56007. this.intersectionPoint.addInPlace(this._displacementVector);
  56008. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56009. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56010. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56011. };
  56012. return Collider;
  56013. }());
  56014. BABYLON.Collider = Collider;
  56015. })(BABYLON || (BABYLON = {}));
  56016. //# sourceMappingURL=babylon.collider.js.map
  56017. var BABYLON;
  56018. (function (BABYLON) {
  56019. //WebWorker code will be inserted to this variable.
  56020. /** @hidden */
  56021. BABYLON.CollisionWorker = "";
  56022. /** Defines supported task for worker process */
  56023. var WorkerTaskType;
  56024. (function (WorkerTaskType) {
  56025. /** Initialization */
  56026. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56027. /** Update of geometry */
  56028. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56029. /** Evaluate collision */
  56030. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56031. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56032. /** Defines kind of replies returned by worker */
  56033. var WorkerReplyType;
  56034. (function (WorkerReplyType) {
  56035. /** Success */
  56036. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56037. /** Unkown error */
  56038. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56039. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56040. /** @hidden */
  56041. var CollisionCoordinatorWorker = /** @class */ (function () {
  56042. function CollisionCoordinatorWorker() {
  56043. var _this = this;
  56044. this._scaledPosition = BABYLON.Vector3.Zero();
  56045. this._scaledVelocity = BABYLON.Vector3.Zero();
  56046. this.onMeshUpdated = function (transformNode) {
  56047. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56048. };
  56049. this.onGeometryUpdated = function (geometry) {
  56050. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56051. };
  56052. this._afterRender = function () {
  56053. if (!_this._init)
  56054. return;
  56055. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56056. return;
  56057. }
  56058. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56059. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56060. if (_this._runningUpdated > 4) {
  56061. return;
  56062. }
  56063. ++_this._runningUpdated;
  56064. var payload = {
  56065. updatedMeshes: _this._addUpdateMeshesList,
  56066. updatedGeometries: _this._addUpdateGeometriesList,
  56067. removedGeometries: _this._toRemoveGeometryArray,
  56068. removedMeshes: _this._toRemoveMeshesArray
  56069. };
  56070. var message = {
  56071. payload: payload,
  56072. taskType: WorkerTaskType.UPDATE
  56073. };
  56074. var serializable = [];
  56075. for (var id in payload.updatedGeometries) {
  56076. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56077. //prepare transferables
  56078. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56079. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56080. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56081. }
  56082. }
  56083. _this._worker.postMessage(message, serializable);
  56084. _this._addUpdateMeshesList = {};
  56085. _this._addUpdateGeometriesList = {};
  56086. _this._toRemoveGeometryArray = [];
  56087. _this._toRemoveMeshesArray = [];
  56088. };
  56089. this._onMessageFromWorker = function (e) {
  56090. var returnData = e.data;
  56091. if (returnData.error != WorkerReplyType.SUCCESS) {
  56092. //TODO what errors can be returned from the worker?
  56093. BABYLON.Tools.Warn("error returned from worker!");
  56094. return;
  56095. }
  56096. switch (returnData.taskType) {
  56097. case WorkerTaskType.INIT:
  56098. _this._init = true;
  56099. //Update the worked with ALL of the scene's current state
  56100. _this._scene.meshes.forEach(function (mesh) {
  56101. _this.onMeshAdded(mesh);
  56102. });
  56103. _this._scene.getGeometries().forEach(function (geometry) {
  56104. _this.onGeometryAdded(geometry);
  56105. });
  56106. break;
  56107. case WorkerTaskType.UPDATE:
  56108. _this._runningUpdated--;
  56109. break;
  56110. case WorkerTaskType.COLLIDE:
  56111. var returnPayload = returnData.payload;
  56112. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56113. return;
  56114. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56115. if (callback) {
  56116. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56117. if (mesh) {
  56118. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56119. }
  56120. }
  56121. //cleanup
  56122. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56123. break;
  56124. }
  56125. };
  56126. this._collisionsCallbackArray = [];
  56127. this._init = false;
  56128. this._runningUpdated = 0;
  56129. this._addUpdateMeshesList = {};
  56130. this._addUpdateGeometriesList = {};
  56131. this._toRemoveGeometryArray = [];
  56132. this._toRemoveMeshesArray = [];
  56133. }
  56134. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56135. if (!this._init)
  56136. return;
  56137. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56138. return;
  56139. position.divideToRef(collider._radius, this._scaledPosition);
  56140. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56141. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56142. var payload = {
  56143. collider: {
  56144. position: this._scaledPosition.asArray(),
  56145. velocity: this._scaledVelocity.asArray(),
  56146. radius: collider._radius.asArray()
  56147. },
  56148. collisionId: collisionIndex,
  56149. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56150. maximumRetry: maximumRetry
  56151. };
  56152. var message = {
  56153. payload: payload,
  56154. taskType: WorkerTaskType.COLLIDE
  56155. };
  56156. this._worker.postMessage(message);
  56157. };
  56158. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56159. this._scene = scene;
  56160. this._scene.registerAfterRender(this._afterRender);
  56161. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56162. this._worker = new Worker(workerUrl);
  56163. this._worker.onmessage = this._onMessageFromWorker;
  56164. var message = {
  56165. payload: {},
  56166. taskType: WorkerTaskType.INIT
  56167. };
  56168. this._worker.postMessage(message);
  56169. };
  56170. CollisionCoordinatorWorker.prototype.destroy = function () {
  56171. this._scene.unregisterAfterRender(this._afterRender);
  56172. this._worker.terminate();
  56173. };
  56174. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56175. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56176. this.onMeshUpdated(mesh);
  56177. };
  56178. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56179. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56180. };
  56181. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56182. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56183. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56184. this.onGeometryUpdated(geometry);
  56185. };
  56186. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56187. this._toRemoveGeometryArray.push(geometry.id);
  56188. };
  56189. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56190. var submeshes = [];
  56191. if (mesh.subMeshes) {
  56192. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56193. var boundingInfo = sm.getBoundingInfo();
  56194. return {
  56195. position: idx,
  56196. verticesStart: sm.verticesStart,
  56197. verticesCount: sm.verticesCount,
  56198. indexStart: sm.indexStart,
  56199. indexCount: sm.indexCount,
  56200. hasMaterial: !!sm.getMaterial(),
  56201. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56202. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56203. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56204. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56205. };
  56206. });
  56207. }
  56208. var geometryId = null;
  56209. if (mesh instanceof BABYLON.Mesh) {
  56210. var geometry = mesh.geometry;
  56211. geometryId = geometry ? geometry.id : null;
  56212. }
  56213. else if (mesh instanceof BABYLON.InstancedMesh) {
  56214. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56215. geometryId = geometry ? geometry.id : null;
  56216. }
  56217. var boundingInfo = mesh.getBoundingInfo();
  56218. return {
  56219. uniqueId: mesh.uniqueId,
  56220. id: mesh.id,
  56221. name: mesh.name,
  56222. geometryId: geometryId,
  56223. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56224. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56225. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56226. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56227. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56228. subMeshes: submeshes,
  56229. checkCollisions: mesh.checkCollisions
  56230. };
  56231. };
  56232. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56233. return {
  56234. id: geometry.id,
  56235. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56236. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56237. indices: new Uint32Array(geometry.getIndices() || []),
  56238. };
  56239. };
  56240. return CollisionCoordinatorWorker;
  56241. }());
  56242. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56243. /** @hidden */
  56244. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56245. function CollisionCoordinatorLegacy() {
  56246. this._scaledPosition = BABYLON.Vector3.Zero();
  56247. this._scaledVelocity = BABYLON.Vector3.Zero();
  56248. this._finalPosition = BABYLON.Vector3.Zero();
  56249. }
  56250. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56251. position.divideToRef(collider._radius, this._scaledPosition);
  56252. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56253. collider.collidedMesh = null;
  56254. collider._retry = 0;
  56255. collider._initialVelocity = this._scaledVelocity;
  56256. collider._initialPosition = this._scaledPosition;
  56257. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56258. this._finalPosition.multiplyInPlace(collider._radius);
  56259. //run the callback
  56260. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56261. };
  56262. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56263. this._scene = scene;
  56264. };
  56265. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56266. //Legacy need no destruction method.
  56267. };
  56268. //No update in legacy mode
  56269. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56270. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56271. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56272. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56273. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56274. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56275. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56276. if (excludedMesh === void 0) { excludedMesh = null; }
  56277. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56278. if (collider._retry >= maximumRetry) {
  56279. finalPosition.copyFrom(position);
  56280. return;
  56281. }
  56282. // Check if this is a mesh else camera or -1
  56283. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56284. collider._initialize(position, velocity, closeDistance);
  56285. // Check all meshes
  56286. for (var index = 0; index < this._scene.meshes.length; index++) {
  56287. var mesh = this._scene.meshes[index];
  56288. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56289. mesh._checkCollision(collider);
  56290. }
  56291. }
  56292. if (!collider.collisionFound) {
  56293. position.addToRef(velocity, finalPosition);
  56294. return;
  56295. }
  56296. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56297. collider._getResponse(position, velocity);
  56298. }
  56299. if (velocity.length() <= closeDistance) {
  56300. finalPosition.copyFrom(position);
  56301. return;
  56302. }
  56303. collider._retry++;
  56304. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56305. };
  56306. return CollisionCoordinatorLegacy;
  56307. }());
  56308. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56309. })(BABYLON || (BABYLON = {}));
  56310. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56311. var BABYLON;
  56312. (function (BABYLON) {
  56313. /**
  56314. * A particle represents one of the element emitted by a particle system.
  56315. * This is mainly define by its coordinates, direction, velocity and age.
  56316. */
  56317. var Particle = /** @class */ (function () {
  56318. /**
  56319. * Creates a new instance Particle
  56320. * @param particleSystem the particle system the particle belongs to
  56321. */
  56322. function Particle(
  56323. /**
  56324. * The particle system the particle belongs to.
  56325. */
  56326. particleSystem) {
  56327. this.particleSystem = particleSystem;
  56328. /**
  56329. * The world position of the particle in the scene.
  56330. */
  56331. this.position = BABYLON.Vector3.Zero();
  56332. /**
  56333. * The world direction of the particle in the scene.
  56334. */
  56335. this.direction = BABYLON.Vector3.Zero();
  56336. /**
  56337. * The color of the particle.
  56338. */
  56339. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56340. /**
  56341. * The color change of the particle per step.
  56342. */
  56343. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56344. /**
  56345. * Defines how long will the life of the particle be.
  56346. */
  56347. this.lifeTime = 1.0;
  56348. /**
  56349. * The current age of the particle.
  56350. */
  56351. this.age = 0;
  56352. /**
  56353. * The current size of the particle.
  56354. */
  56355. this.size = 0;
  56356. /**
  56357. * The current scale of the particle.
  56358. */
  56359. this.scale = new BABYLON.Vector2(1, 1);
  56360. /**
  56361. * The current angle of the particle.
  56362. */
  56363. this.angle = 0;
  56364. /**
  56365. * Defines how fast is the angle changing.
  56366. */
  56367. this.angularSpeed = 0;
  56368. /**
  56369. * Defines the cell index used by the particle to be rendered from a sprite.
  56370. */
  56371. this.cellIndex = 0;
  56372. /** @hidden */
  56373. this._attachedSubEmitters = null;
  56374. /** @hidden */
  56375. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56376. /** @hidden */
  56377. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56378. /** @hidden */
  56379. this._currentSize1 = 0;
  56380. /** @hidden */
  56381. this._currentSize2 = 0;
  56382. /** @hidden */
  56383. this._currentAngularSpeed1 = 0;
  56384. /** @hidden */
  56385. this._currentAngularSpeed2 = 0;
  56386. /** @hidden */
  56387. this._currentVelocity1 = 0;
  56388. /** @hidden */
  56389. this._currentVelocity2 = 0;
  56390. /** @hidden */
  56391. this._currentLimitVelocity1 = 0;
  56392. /** @hidden */
  56393. this._currentLimitVelocity2 = 0;
  56394. /** @hidden */
  56395. this._currentDrag1 = 0;
  56396. /** @hidden */
  56397. this._currentDrag2 = 0;
  56398. this.id = Particle._Count++;
  56399. if (!this.particleSystem.isAnimationSheetEnabled) {
  56400. return;
  56401. }
  56402. this.updateCellInfoFromSystem();
  56403. }
  56404. Particle.prototype.updateCellInfoFromSystem = function () {
  56405. this.cellIndex = this.particleSystem.startSpriteCellID;
  56406. };
  56407. /**
  56408. * Defines how the sprite cell index is updated for the particle
  56409. */
  56410. Particle.prototype.updateCellIndex = function () {
  56411. var offsetAge = this.age;
  56412. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56413. if (this.particleSystem.spriteRandomStartCell) {
  56414. if (this._randomCellOffset === undefined) {
  56415. this._randomCellOffset = Math.random() * this.lifeTime;
  56416. }
  56417. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56418. changeSpeed = 1;
  56419. offsetAge = this._randomCellOffset;
  56420. }
  56421. else {
  56422. offsetAge += this._randomCellOffset;
  56423. }
  56424. }
  56425. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56426. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56427. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56428. };
  56429. /** @hidden */
  56430. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56431. if (subEmitter.particleSystem.emitter.position) {
  56432. var emitterMesh = subEmitter.particleSystem.emitter;
  56433. emitterMesh.position.copyFrom(this.position);
  56434. if (subEmitter.inheritDirection) {
  56435. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56436. // Look at using Y as forward
  56437. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56438. }
  56439. }
  56440. else {
  56441. var emitterPosition = subEmitter.particleSystem.emitter;
  56442. emitterPosition.copyFrom(this.position);
  56443. }
  56444. // Set inheritedVelocityOffset to be used when new particles are created
  56445. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56446. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56447. };
  56448. /** @hidden */
  56449. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56450. var _this = this;
  56451. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56452. this._attachedSubEmitters.forEach(function (subEmitter) {
  56453. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56454. });
  56455. }
  56456. };
  56457. /** @hidden */
  56458. Particle.prototype._reset = function () {
  56459. this.age = 0;
  56460. this._currentColorGradient = null;
  56461. this._currentSizeGradient = null;
  56462. this._currentAngularSpeedGradient = null;
  56463. this._currentVelocityGradient = null;
  56464. this._currentLimitVelocityGradient = null;
  56465. this._currentDragGradient = null;
  56466. this.cellIndex = this.particleSystem.startSpriteCellID;
  56467. this._randomCellOffset = undefined;
  56468. };
  56469. /**
  56470. * Copy the properties of particle to another one.
  56471. * @param other the particle to copy the information to.
  56472. */
  56473. Particle.prototype.copyTo = function (other) {
  56474. other.position.copyFrom(this.position);
  56475. if (this._initialDirection) {
  56476. if (other._initialDirection) {
  56477. other._initialDirection.copyFrom(this._initialDirection);
  56478. }
  56479. else {
  56480. other._initialDirection = this._initialDirection.clone();
  56481. }
  56482. }
  56483. else {
  56484. other._initialDirection = null;
  56485. }
  56486. other.direction.copyFrom(this.direction);
  56487. other.color.copyFrom(this.color);
  56488. other.colorStep.copyFrom(this.colorStep);
  56489. other.lifeTime = this.lifeTime;
  56490. other.age = this.age;
  56491. other._randomCellOffset = this._randomCellOffset;
  56492. other.size = this.size;
  56493. other.scale.copyFrom(this.scale);
  56494. other.angle = this.angle;
  56495. other.angularSpeed = this.angularSpeed;
  56496. other.particleSystem = this.particleSystem;
  56497. other.cellIndex = this.cellIndex;
  56498. other.id = this.id;
  56499. other._attachedSubEmitters = this._attachedSubEmitters;
  56500. if (this._currentColorGradient) {
  56501. other._currentColorGradient = this._currentColorGradient;
  56502. other._currentColor1.copyFrom(this._currentColor1);
  56503. other._currentColor2.copyFrom(this._currentColor2);
  56504. }
  56505. if (this._currentSizeGradient) {
  56506. other._currentSizeGradient = this._currentSizeGradient;
  56507. other._currentSize1 = this._currentSize1;
  56508. other._currentSize2 = this._currentSize2;
  56509. }
  56510. if (this._currentAngularSpeedGradient) {
  56511. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56512. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56513. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56514. }
  56515. if (this._currentVelocityGradient) {
  56516. other._currentVelocityGradient = this._currentVelocityGradient;
  56517. other._currentVelocity1 = this._currentVelocity1;
  56518. other._currentVelocity2 = this._currentVelocity2;
  56519. }
  56520. if (this._currentLimitVelocityGradient) {
  56521. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56522. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56523. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56524. }
  56525. if (this._currentDragGradient) {
  56526. other._currentDragGradient = this._currentDragGradient;
  56527. other._currentDrag1 = this._currentDrag1;
  56528. other._currentDrag2 = this._currentDrag2;
  56529. }
  56530. if (this.particleSystem.isAnimationSheetEnabled) {
  56531. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56532. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56533. }
  56534. if (this.particleSystem.useRampGradients) {
  56535. other.remapData.copyFrom(this.remapData);
  56536. }
  56537. if (this._randomNoiseCoordinates1) {
  56538. if (other._randomNoiseCoordinates1) {
  56539. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56540. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56541. }
  56542. else {
  56543. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56544. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56545. }
  56546. }
  56547. };
  56548. Particle._Count = 0;
  56549. return Particle;
  56550. }());
  56551. BABYLON.Particle = Particle;
  56552. })(BABYLON || (BABYLON = {}));
  56553. //# sourceMappingURL=babylon.particle.js.map
  56554. var BABYLON;
  56555. (function (BABYLON) {
  56556. /**
  56557. * This represents the base class for particle system in Babylon.
  56558. * 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.
  56559. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56560. * @example https://doc.babylonjs.com/babylon101/particles
  56561. */
  56562. var BaseParticleSystem = /** @class */ (function () {
  56563. /**
  56564. * Instantiates a particle system.
  56565. * 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.
  56566. * @param name The name of the particle system
  56567. */
  56568. function BaseParticleSystem(name) {
  56569. /**
  56570. * List of animations used by the particle system.
  56571. */
  56572. this.animations = [];
  56573. /**
  56574. * The rendering group used by the Particle system to chose when to render.
  56575. */
  56576. this.renderingGroupId = 0;
  56577. /**
  56578. * The emitter represents the Mesh or position we are attaching the particle system to.
  56579. */
  56580. this.emitter = null;
  56581. /**
  56582. * The maximum number of particles to emit per frame
  56583. */
  56584. this.emitRate = 10;
  56585. /**
  56586. * If you want to launch only a few particles at once, that can be done, as well.
  56587. */
  56588. this.manualEmitCount = -1;
  56589. /**
  56590. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56591. */
  56592. this.updateSpeed = 0.01;
  56593. /**
  56594. * The amount of time the particle system is running (depends of the overall update speed).
  56595. */
  56596. this.targetStopDuration = 0;
  56597. /**
  56598. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56599. */
  56600. this.disposeOnStop = false;
  56601. /**
  56602. * Minimum power of emitting particles.
  56603. */
  56604. this.minEmitPower = 1;
  56605. /**
  56606. * Maximum power of emitting particles.
  56607. */
  56608. this.maxEmitPower = 1;
  56609. /**
  56610. * Minimum life time of emitting particles.
  56611. */
  56612. this.minLifeTime = 1;
  56613. /**
  56614. * Maximum life time of emitting particles.
  56615. */
  56616. this.maxLifeTime = 1;
  56617. /**
  56618. * Minimum Size of emitting particles.
  56619. */
  56620. this.minSize = 1;
  56621. /**
  56622. * Maximum Size of emitting particles.
  56623. */
  56624. this.maxSize = 1;
  56625. /**
  56626. * Minimum scale of emitting particles on X axis.
  56627. */
  56628. this.minScaleX = 1;
  56629. /**
  56630. * Maximum scale of emitting particles on X axis.
  56631. */
  56632. this.maxScaleX = 1;
  56633. /**
  56634. * Minimum scale of emitting particles on Y axis.
  56635. */
  56636. this.minScaleY = 1;
  56637. /**
  56638. * Maximum scale of emitting particles on Y axis.
  56639. */
  56640. this.maxScaleY = 1;
  56641. /**
  56642. * Gets or sets the minimal initial rotation in radians.
  56643. */
  56644. this.minInitialRotation = 0;
  56645. /**
  56646. * Gets or sets the maximal initial rotation in radians.
  56647. */
  56648. this.maxInitialRotation = 0;
  56649. /**
  56650. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56651. */
  56652. this.minAngularSpeed = 0;
  56653. /**
  56654. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56655. */
  56656. this.maxAngularSpeed = 0;
  56657. /**
  56658. * The layer mask we are rendering the particles through.
  56659. */
  56660. this.layerMask = 0x0FFFFFFF;
  56661. /**
  56662. * This can help using your own shader to render the particle system.
  56663. * The according effect will be created
  56664. */
  56665. this.customShader = null;
  56666. /**
  56667. * By default particle system starts as soon as they are created. This prevents the
  56668. * automatic start to happen and let you decide when to start emitting particles.
  56669. */
  56670. this.preventAutoStart = false;
  56671. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56672. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56673. /**
  56674. * Callback triggered when the particle animation is ending.
  56675. */
  56676. this.onAnimationEnd = null;
  56677. /**
  56678. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56679. */
  56680. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56681. /**
  56682. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56683. * to override the particles.
  56684. */
  56685. this.forceDepthWrite = false;
  56686. /** 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 */
  56687. this.preWarmCycles = 0;
  56688. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56689. this.preWarmStepOffset = 1;
  56690. /**
  56691. * 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)
  56692. */
  56693. this.spriteCellChangeSpeed = 1;
  56694. /**
  56695. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56696. */
  56697. this.startSpriteCellID = 0;
  56698. /**
  56699. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56700. */
  56701. this.endSpriteCellID = 0;
  56702. /**
  56703. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56704. */
  56705. this.spriteCellWidth = 0;
  56706. /**
  56707. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56708. */
  56709. this.spriteCellHeight = 0;
  56710. /**
  56711. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56712. */
  56713. this.spriteRandomStartCell = false;
  56714. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56715. this.translationPivot = new BABYLON.Vector2(0, 0);
  56716. /**
  56717. * You can use gravity if you want to give an orientation to your particles.
  56718. */
  56719. this.gravity = BABYLON.Vector3.Zero();
  56720. this._colorGradients = null;
  56721. this._sizeGradients = null;
  56722. this._lifeTimeGradients = null;
  56723. this._angularSpeedGradients = null;
  56724. this._velocityGradients = null;
  56725. this._limitVelocityGradients = null;
  56726. this._dragGradients = null;
  56727. this._emitRateGradients = null;
  56728. this._startSizeGradients = null;
  56729. this._rampGradients = null;
  56730. this._colorRemapGradients = null;
  56731. this._alphaRemapGradients = null;
  56732. /**
  56733. * Defines the delay in milliseconds before starting the system (0 by default)
  56734. */
  56735. this.startDelay = 0;
  56736. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56737. this.limitVelocityDamping = 0.4;
  56738. /**
  56739. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56740. */
  56741. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56742. /**
  56743. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56744. */
  56745. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56746. /**
  56747. * Color the particle will have at the end of its lifetime
  56748. */
  56749. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56750. /**
  56751. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56752. */
  56753. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56754. /**
  56755. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56756. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56757. */
  56758. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56759. this._isBillboardBased = true;
  56760. /**
  56761. * Local cache of defines for image processing.
  56762. */
  56763. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56764. this.id = name;
  56765. this.name = name;
  56766. }
  56767. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56768. /**
  56769. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56770. */
  56771. get: function () {
  56772. return this._isAnimationSheetEnabled;
  56773. },
  56774. set: function (value) {
  56775. if (this._isAnimationSheetEnabled == value) {
  56776. return;
  56777. }
  56778. this._isAnimationSheetEnabled = value;
  56779. this._reset();
  56780. },
  56781. enumerable: true,
  56782. configurable: true
  56783. });
  56784. /**
  56785. * Get hosting scene
  56786. * @returns the scene
  56787. */
  56788. BaseParticleSystem.prototype.getScene = function () {
  56789. return this._scene;
  56790. };
  56791. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56792. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56793. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56794. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56795. };
  56796. /**
  56797. * Gets the current list of drag gradients.
  56798. * You must use addDragGradient and removeDragGradient to udpate this list
  56799. * @returns the list of drag gradients
  56800. */
  56801. BaseParticleSystem.prototype.getDragGradients = function () {
  56802. return this._dragGradients;
  56803. };
  56804. /**
  56805. * Gets the current list of limit velocity gradients.
  56806. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56807. * @returns the list of limit velocity gradients
  56808. */
  56809. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56810. return this._limitVelocityGradients;
  56811. };
  56812. /**
  56813. * Gets the current list of color gradients.
  56814. * You must use addColorGradient and removeColorGradient to udpate this list
  56815. * @returns the list of color gradients
  56816. */
  56817. BaseParticleSystem.prototype.getColorGradients = function () {
  56818. return this._colorGradients;
  56819. };
  56820. /**
  56821. * Gets the current list of size gradients.
  56822. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56823. * @returns the list of size gradients
  56824. */
  56825. BaseParticleSystem.prototype.getSizeGradients = function () {
  56826. return this._sizeGradients;
  56827. };
  56828. /**
  56829. * Gets the current list of color remap gradients.
  56830. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56831. * @returns the list of color remap gradients
  56832. */
  56833. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56834. return this._colorRemapGradients;
  56835. };
  56836. /**
  56837. * Gets the current list of alpha remap gradients.
  56838. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56839. * @returns the list of alpha remap gradients
  56840. */
  56841. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56842. return this._alphaRemapGradients;
  56843. };
  56844. /**
  56845. * Gets the current list of life time gradients.
  56846. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56847. * @returns the list of life time gradients
  56848. */
  56849. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  56850. return this._lifeTimeGradients;
  56851. };
  56852. /**
  56853. * Gets the current list of angular speed gradients.
  56854. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  56855. * @returns the list of angular speed gradients
  56856. */
  56857. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  56858. return this._angularSpeedGradients;
  56859. };
  56860. /**
  56861. * Gets the current list of velocity gradients.
  56862. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  56863. * @returns the list of velocity gradients
  56864. */
  56865. BaseParticleSystem.prototype.getVelocityGradients = function () {
  56866. return this._velocityGradients;
  56867. };
  56868. /**
  56869. * Gets the current list of start size gradients.
  56870. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  56871. * @returns the list of start size gradients
  56872. */
  56873. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  56874. return this._startSizeGradients;
  56875. };
  56876. /**
  56877. * Gets the current list of emit rate gradients.
  56878. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  56879. * @returns the list of emit rate gradients
  56880. */
  56881. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  56882. return this._emitRateGradients;
  56883. };
  56884. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  56885. /**
  56886. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56887. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56888. */
  56889. get: function () {
  56890. if (this.particleEmitterType.direction1) {
  56891. return this.particleEmitterType.direction1;
  56892. }
  56893. return BABYLON.Vector3.Zero();
  56894. },
  56895. set: function (value) {
  56896. if (this.particleEmitterType.direction1) {
  56897. this.particleEmitterType.direction1 = value;
  56898. }
  56899. },
  56900. enumerable: true,
  56901. configurable: true
  56902. });
  56903. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  56904. /**
  56905. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56906. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56907. */
  56908. get: function () {
  56909. if (this.particleEmitterType.direction2) {
  56910. return this.particleEmitterType.direction2;
  56911. }
  56912. return BABYLON.Vector3.Zero();
  56913. },
  56914. set: function (value) {
  56915. if (this.particleEmitterType.direction2) {
  56916. this.particleEmitterType.direction2 = value;
  56917. }
  56918. },
  56919. enumerable: true,
  56920. configurable: true
  56921. });
  56922. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  56923. /**
  56924. * 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.
  56925. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56926. */
  56927. get: function () {
  56928. if (this.particleEmitterType.minEmitBox) {
  56929. return this.particleEmitterType.minEmitBox;
  56930. }
  56931. return BABYLON.Vector3.Zero();
  56932. },
  56933. set: function (value) {
  56934. if (this.particleEmitterType.minEmitBox) {
  56935. this.particleEmitterType.minEmitBox = value;
  56936. }
  56937. },
  56938. enumerable: true,
  56939. configurable: true
  56940. });
  56941. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  56942. /**
  56943. * 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.
  56944. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56945. */
  56946. get: function () {
  56947. if (this.particleEmitterType.maxEmitBox) {
  56948. return this.particleEmitterType.maxEmitBox;
  56949. }
  56950. return BABYLON.Vector3.Zero();
  56951. },
  56952. set: function (value) {
  56953. if (this.particleEmitterType.maxEmitBox) {
  56954. this.particleEmitterType.maxEmitBox = value;
  56955. }
  56956. },
  56957. enumerable: true,
  56958. configurable: true
  56959. });
  56960. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56961. /**
  56962. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56963. */
  56964. get: function () {
  56965. return this._isBillboardBased;
  56966. },
  56967. set: function (value) {
  56968. if (this._isBillboardBased === value) {
  56969. return;
  56970. }
  56971. this._isBillboardBased = value;
  56972. this._reset();
  56973. },
  56974. enumerable: true,
  56975. configurable: true
  56976. });
  56977. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56978. /**
  56979. * Gets the image processing configuration used either in this material.
  56980. */
  56981. get: function () {
  56982. return this._imageProcessingConfiguration;
  56983. },
  56984. /**
  56985. * Sets the Default image processing configuration used either in the this material.
  56986. *
  56987. * If sets to null, the scene one is in use.
  56988. */
  56989. set: function (value) {
  56990. this._attachImageProcessingConfiguration(value);
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. /**
  56996. * Attaches a new image processing configuration to the Standard Material.
  56997. * @param configuration
  56998. */
  56999. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57000. if (configuration === this._imageProcessingConfiguration) {
  57001. return;
  57002. }
  57003. // Pick the scene configuration if needed.
  57004. if (!configuration) {
  57005. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57006. }
  57007. else {
  57008. this._imageProcessingConfiguration = configuration;
  57009. }
  57010. };
  57011. /** @hidden */
  57012. BaseParticleSystem.prototype._reset = function () {
  57013. };
  57014. /** @hidden */
  57015. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57016. if (!gradients) {
  57017. return this;
  57018. }
  57019. var index = 0;
  57020. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57021. var valueGradient = gradients_1[_i];
  57022. if (valueGradient.gradient === gradient) {
  57023. gradients.splice(index, 1);
  57024. break;
  57025. }
  57026. index++;
  57027. }
  57028. if (texture) {
  57029. texture.dispose();
  57030. }
  57031. return this;
  57032. };
  57033. /**
  57034. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57035. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57036. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57037. * @returns the emitter
  57038. */
  57039. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57040. var particleEmitter = new BABYLON.PointParticleEmitter();
  57041. particleEmitter.direction1 = direction1;
  57042. particleEmitter.direction2 = direction2;
  57043. this.particleEmitterType = particleEmitter;
  57044. return particleEmitter;
  57045. };
  57046. /**
  57047. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57048. * @param radius The radius of the hemisphere to emit from
  57049. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57050. * @returns the emitter
  57051. */
  57052. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57053. if (radius === void 0) { radius = 1; }
  57054. if (radiusRange === void 0) { radiusRange = 1; }
  57055. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57056. this.particleEmitterType = particleEmitter;
  57057. return particleEmitter;
  57058. };
  57059. /**
  57060. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57061. * @param radius The radius of the sphere to emit from
  57062. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57063. * @returns the emitter
  57064. */
  57065. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57066. if (radius === void 0) { radius = 1; }
  57067. if (radiusRange === void 0) { radiusRange = 1; }
  57068. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57069. this.particleEmitterType = particleEmitter;
  57070. return particleEmitter;
  57071. };
  57072. /**
  57073. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57074. * @param radius The radius of the sphere to emit from
  57075. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57076. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57077. * @returns the emitter
  57078. */
  57079. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57080. if (radius === void 0) { radius = 1; }
  57081. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57082. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57083. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57084. this.particleEmitterType = particleEmitter;
  57085. return particleEmitter;
  57086. };
  57087. /**
  57088. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57089. * @param radius The radius of the emission cylinder
  57090. * @param height The height of the emission cylinder
  57091. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57092. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57093. * @returns the emitter
  57094. */
  57095. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57096. if (radius === void 0) { radius = 1; }
  57097. if (height === void 0) { height = 1; }
  57098. if (radiusRange === void 0) { radiusRange = 1; }
  57099. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57100. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57101. this.particleEmitterType = particleEmitter;
  57102. return particleEmitter;
  57103. };
  57104. /**
  57105. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57106. * @param radius The radius of the cylinder to emit from
  57107. * @param height The height of the emission cylinder
  57108. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57109. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57110. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57111. * @returns the emitter
  57112. */
  57113. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57114. if (radius === void 0) { radius = 1; }
  57115. if (height === void 0) { height = 1; }
  57116. if (radiusRange === void 0) { radiusRange = 1; }
  57117. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57118. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57119. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57120. this.particleEmitterType = particleEmitter;
  57121. return particleEmitter;
  57122. };
  57123. /**
  57124. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57125. * @param radius The radius of the cone to emit from
  57126. * @param angle The base angle of the cone
  57127. * @returns the emitter
  57128. */
  57129. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57130. if (radius === void 0) { radius = 1; }
  57131. if (angle === void 0) { angle = Math.PI / 4; }
  57132. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57133. this.particleEmitterType = particleEmitter;
  57134. return particleEmitter;
  57135. };
  57136. /**
  57137. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57138. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57139. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57140. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57141. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57142. * @returns the emitter
  57143. */
  57144. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57145. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57146. this.particleEmitterType = particleEmitter;
  57147. this.direction1 = direction1;
  57148. this.direction2 = direction2;
  57149. this.minEmitBox = minEmitBox;
  57150. this.maxEmitBox = maxEmitBox;
  57151. return particleEmitter;
  57152. };
  57153. /**
  57154. * Source color is added to the destination color without alpha affecting the result
  57155. */
  57156. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57157. /**
  57158. * Blend current color and particle color using particle’s alpha
  57159. */
  57160. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57161. /**
  57162. * Add current color and particle color multiplied by particle’s alpha
  57163. */
  57164. BaseParticleSystem.BLENDMODE_ADD = 2;
  57165. /**
  57166. * Multiply current color with particle color
  57167. */
  57168. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57169. /**
  57170. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57171. */
  57172. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57173. return BaseParticleSystem;
  57174. }());
  57175. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57176. })(BABYLON || (BABYLON = {}));
  57177. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57178. var BABYLON;
  57179. (function (BABYLON) {
  57180. /**
  57181. * This represents a particle system in Babylon.
  57182. * 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.
  57183. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57184. * @example https://doc.babylonjs.com/babylon101/particles
  57185. */
  57186. var ParticleSystem = /** @class */ (function (_super) {
  57187. __extends(ParticleSystem, _super);
  57188. /**
  57189. * Instantiates a particle system.
  57190. * 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.
  57191. * @param name The name of the particle system
  57192. * @param capacity The max number of particles alive at the same time
  57193. * @param scene The scene the particle system belongs to
  57194. * @param customEffect a custom effect used to change the way particles are rendered by default
  57195. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57196. * @param epsilon Offset used to render the particles
  57197. */
  57198. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57199. if (customEffect === void 0) { customEffect = null; }
  57200. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57201. if (epsilon === void 0) { epsilon = 0.01; }
  57202. var _this = _super.call(this, name) || this;
  57203. /**
  57204. * @hidden
  57205. */
  57206. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57207. /**
  57208. * An event triggered when the system is disposed
  57209. */
  57210. _this.onDisposeObservable = new BABYLON.Observable();
  57211. _this._particles = new Array();
  57212. _this._stockParticles = new Array();
  57213. _this._newPartsExcess = 0;
  57214. _this._vertexBuffers = {};
  57215. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57216. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57217. _this._scaledDirection = BABYLON.Vector3.Zero();
  57218. _this._scaledGravity = BABYLON.Vector3.Zero();
  57219. _this._currentRenderId = -1;
  57220. _this._useInstancing = false;
  57221. _this._started = false;
  57222. _this._stopped = false;
  57223. _this._actualFrame = 0;
  57224. /** @hidden */
  57225. _this._currentEmitRate1 = 0;
  57226. /** @hidden */
  57227. _this._currentEmitRate2 = 0;
  57228. /** @hidden */
  57229. _this._currentStartSize1 = 0;
  57230. /** @hidden */
  57231. _this._currentStartSize2 = 0;
  57232. _this._rawTextureWidth = 256;
  57233. _this._useRampGradients = false;
  57234. /**
  57235. * @hidden
  57236. * If the particle systems emitter should be disposed when the particle system is disposed
  57237. */
  57238. _this._disposeEmitterOnDispose = false;
  57239. // start of sub system methods
  57240. /**
  57241. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57242. * Its lifetime will start back at 0.
  57243. */
  57244. _this.recycleParticle = function (particle) {
  57245. // move particle from activeParticle list to stock particles
  57246. var lastParticle = _this._particles.pop();
  57247. if (lastParticle !== particle) {
  57248. lastParticle.copyTo(particle);
  57249. }
  57250. _this._stockParticles.push(lastParticle);
  57251. };
  57252. _this._createParticle = function () {
  57253. var particle;
  57254. if (_this._stockParticles.length !== 0) {
  57255. particle = _this._stockParticles.pop();
  57256. particle._reset();
  57257. }
  57258. else {
  57259. particle = new BABYLON.Particle(_this);
  57260. }
  57261. // Attach emitters
  57262. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57263. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57264. particle._attachedSubEmitters = [];
  57265. subEmitters.forEach(function (subEmitter) {
  57266. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57267. var newEmitter = subEmitter.clone();
  57268. particle._attachedSubEmitters.push(newEmitter);
  57269. newEmitter.particleSystem.start();
  57270. }
  57271. });
  57272. }
  57273. return particle;
  57274. };
  57275. _this._emitFromParticle = function (particle) {
  57276. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57277. return;
  57278. }
  57279. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57280. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57281. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57282. var subSystem = subEmitter.clone();
  57283. particle._inheritParticleInfoToSubEmitter(subSystem);
  57284. subSystem.particleSystem._rootParticleSystem = _this;
  57285. _this.activeSubSystems.push(subSystem.particleSystem);
  57286. subSystem.particleSystem.start();
  57287. }
  57288. });
  57289. };
  57290. _this._capacity = capacity;
  57291. _this._epsilon = epsilon;
  57292. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57293. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57294. // Setup the default processing configuration to the scene.
  57295. _this._attachImageProcessingConfiguration(null);
  57296. _this._customEffect = customEffect;
  57297. _this._scene.particleSystems.push(_this);
  57298. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57299. _this._createIndexBuffer();
  57300. _this._createVertexBuffers();
  57301. // Default emitter type
  57302. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57303. // Update
  57304. _this.updateFunction = function (particles) {
  57305. var noiseTextureSize = null;
  57306. var noiseTextureData = null;
  57307. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57308. noiseTextureSize = _this.noiseTexture.getSize();
  57309. noiseTextureData = (_this.noiseTexture.getContent());
  57310. }
  57311. var _loop_1 = function () {
  57312. particle = particles[index];
  57313. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57314. var previousAge = particle.age;
  57315. particle.age += scaledUpdateSpeed;
  57316. // Evaluate step to death
  57317. if (particle.age > particle.lifeTime) {
  57318. var diff = particle.age - previousAge;
  57319. var oldDiff = particle.lifeTime - previousAge;
  57320. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57321. particle.age = particle.lifeTime;
  57322. }
  57323. var ratio = particle.age / particle.lifeTime;
  57324. // Color
  57325. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57326. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57327. if (currentGradient !== particle._currentColorGradient) {
  57328. particle._currentColor1.copyFrom(particle._currentColor2);
  57329. nextGradient.getColorToRef(particle._currentColor2);
  57330. particle._currentColorGradient = currentGradient;
  57331. }
  57332. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57333. });
  57334. }
  57335. else {
  57336. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57337. particle.color.addInPlace(_this._scaledColorStep);
  57338. if (particle.color.a < 0) {
  57339. particle.color.a = 0;
  57340. }
  57341. }
  57342. // Angular speed
  57343. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57344. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57345. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57346. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57347. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57348. particle._currentAngularSpeedGradient = currentGradient;
  57349. }
  57350. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57351. });
  57352. }
  57353. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57354. // Direction
  57355. var directionScale = scaledUpdateSpeed;
  57356. /// Velocity
  57357. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57358. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57359. if (currentGradient !== particle._currentVelocityGradient) {
  57360. particle._currentVelocity1 = particle._currentVelocity2;
  57361. particle._currentVelocity2 = nextGradient.getFactor();
  57362. particle._currentVelocityGradient = currentGradient;
  57363. }
  57364. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57365. });
  57366. }
  57367. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57368. /// Limit velocity
  57369. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57370. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57371. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57372. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57373. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57374. particle._currentLimitVelocityGradient = currentGradient;
  57375. }
  57376. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57377. var currentVelocity = particle.direction.length();
  57378. if (currentVelocity > limitVelocity) {
  57379. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57380. }
  57381. });
  57382. }
  57383. /// Drag
  57384. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57385. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57386. if (currentGradient !== particle._currentDragGradient) {
  57387. particle._currentDrag1 = particle._currentDrag2;
  57388. particle._currentDrag2 = nextGradient.getFactor();
  57389. particle._currentDragGradient = currentGradient;
  57390. }
  57391. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57392. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57393. });
  57394. }
  57395. particle.position.addInPlace(_this._scaledDirection);
  57396. // Noise
  57397. if (noiseTextureData && noiseTextureSize) {
  57398. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57399. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57400. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57401. var force = BABYLON.Tmp.Vector3[0];
  57402. var scaledForce = BABYLON.Tmp.Vector3[1];
  57403. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57404. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57405. particle.direction.addInPlace(scaledForce);
  57406. }
  57407. // Gravity
  57408. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57409. particle.direction.addInPlace(_this._scaledGravity);
  57410. // Size
  57411. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57412. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57413. if (currentGradient !== particle._currentSizeGradient) {
  57414. particle._currentSize1 = particle._currentSize2;
  57415. particle._currentSize2 = nextGradient.getFactor();
  57416. particle._currentSizeGradient = currentGradient;
  57417. }
  57418. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57419. });
  57420. }
  57421. // Remap data
  57422. if (_this._useRampGradients) {
  57423. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57424. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57425. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57426. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57427. particle.remapData.x = min;
  57428. particle.remapData.y = max - min;
  57429. });
  57430. }
  57431. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57432. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57433. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57434. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57435. particle.remapData.z = min;
  57436. particle.remapData.w = max - min;
  57437. });
  57438. }
  57439. }
  57440. if (_this._isAnimationSheetEnabled) {
  57441. particle.updateCellIndex();
  57442. }
  57443. // Update the position of the attached sub-emitters to match their attached particle
  57444. particle._inheritParticleInfoToSubEmitters();
  57445. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57446. _this._emitFromParticle(particle);
  57447. if (particle._attachedSubEmitters) {
  57448. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57449. subEmitter.particleSystem.disposeOnStop = true;
  57450. subEmitter.particleSystem.stop();
  57451. });
  57452. particle._attachedSubEmitters = null;
  57453. }
  57454. _this.recycleParticle(particle);
  57455. index--;
  57456. return "continue";
  57457. }
  57458. };
  57459. var particle;
  57460. for (var index = 0; index < particles.length; index++) {
  57461. _loop_1();
  57462. }
  57463. };
  57464. return _this;
  57465. }
  57466. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57467. /**
  57468. * Sets a callback that will be triggered when the system is disposed
  57469. */
  57470. set: function (callback) {
  57471. if (this._onDisposeObserver) {
  57472. this.onDisposeObservable.remove(this._onDisposeObserver);
  57473. }
  57474. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57475. },
  57476. enumerable: true,
  57477. configurable: true
  57478. });
  57479. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57480. /** Gets or sets a boolean indicating that ramp gradients must be used
  57481. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57482. */
  57483. get: function () {
  57484. return this._useRampGradients;
  57485. },
  57486. set: function (value) {
  57487. if (this._useRampGradients === value) {
  57488. return;
  57489. }
  57490. this._useRampGradients = value;
  57491. this._resetEffect();
  57492. },
  57493. enumerable: true,
  57494. configurable: true
  57495. });
  57496. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57497. //end of Sub-emitter
  57498. /**
  57499. * Gets the current list of active particles
  57500. */
  57501. get: function () {
  57502. return this._particles;
  57503. },
  57504. enumerable: true,
  57505. configurable: true
  57506. });
  57507. /**
  57508. * Returns the string "ParticleSystem"
  57509. * @returns a string containing the class name
  57510. */
  57511. ParticleSystem.prototype.getClassName = function () {
  57512. return "ParticleSystem";
  57513. };
  57514. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57515. var newGradient = new BABYLON.FactorGradient();
  57516. newGradient.gradient = gradient;
  57517. newGradient.factor1 = factor;
  57518. newGradient.factor2 = factor2;
  57519. factorGradients.push(newGradient);
  57520. factorGradients.sort(function (a, b) {
  57521. if (a.gradient < b.gradient) {
  57522. return -1;
  57523. }
  57524. else if (a.gradient > b.gradient) {
  57525. return 1;
  57526. }
  57527. return 0;
  57528. });
  57529. };
  57530. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57531. if (!factorGradients) {
  57532. return;
  57533. }
  57534. var index = 0;
  57535. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57536. var factorGradient = factorGradients_1[_i];
  57537. if (factorGradient.gradient === gradient) {
  57538. factorGradients.splice(index, 1);
  57539. break;
  57540. }
  57541. index++;
  57542. }
  57543. };
  57544. /**
  57545. * Adds a new life time gradient
  57546. * @param gradient defines the gradient to use (between 0 and 1)
  57547. * @param factor defines the life time factor to affect to the specified gradient
  57548. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57549. * @returns the current particle system
  57550. */
  57551. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57552. if (!this._lifeTimeGradients) {
  57553. this._lifeTimeGradients = [];
  57554. }
  57555. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57556. return this;
  57557. };
  57558. /**
  57559. * Remove a specific life time gradient
  57560. * @param gradient defines the gradient to remove
  57561. * @returns the current particle system
  57562. */
  57563. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57564. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57565. return this;
  57566. };
  57567. /**
  57568. * Adds a new size gradient
  57569. * @param gradient defines the gradient to use (between 0 and 1)
  57570. * @param factor defines the size factor to affect to the specified gradient
  57571. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57572. * @returns the current particle system
  57573. */
  57574. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57575. if (!this._sizeGradients) {
  57576. this._sizeGradients = [];
  57577. }
  57578. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57579. return this;
  57580. };
  57581. /**
  57582. * Remove a specific size gradient
  57583. * @param gradient defines the gradient to remove
  57584. * @returns the current particle system
  57585. */
  57586. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57587. this._removeFactorGradient(this._sizeGradients, gradient);
  57588. return this;
  57589. };
  57590. /**
  57591. * Adds a new color remap gradient
  57592. * @param gradient defines the gradient to use (between 0 and 1)
  57593. * @param min defines the color remap minimal range
  57594. * @param max defines the color remap maximal range
  57595. * @returns the current particle system
  57596. */
  57597. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57598. if (!this._colorRemapGradients) {
  57599. this._colorRemapGradients = [];
  57600. }
  57601. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57602. return this;
  57603. };
  57604. /**
  57605. * Remove a specific color remap gradient
  57606. * @param gradient defines the gradient to remove
  57607. * @returns the current particle system
  57608. */
  57609. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57610. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57611. return this;
  57612. };
  57613. /**
  57614. * Adds a new alpha remap gradient
  57615. * @param gradient defines the gradient to use (between 0 and 1)
  57616. * @param min defines the alpha remap minimal range
  57617. * @param max defines the alpha remap maximal range
  57618. * @returns the current particle system
  57619. */
  57620. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57621. if (!this._alphaRemapGradients) {
  57622. this._alphaRemapGradients = [];
  57623. }
  57624. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57625. return this;
  57626. };
  57627. /**
  57628. * Remove a specific alpha remap gradient
  57629. * @param gradient defines the gradient to remove
  57630. * @returns the current particle system
  57631. */
  57632. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57633. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57634. return this;
  57635. };
  57636. /**
  57637. * Adds a new angular speed gradient
  57638. * @param gradient defines the gradient to use (between 0 and 1)
  57639. * @param factor defines the angular speed to affect to the specified gradient
  57640. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57641. * @returns the current particle system
  57642. */
  57643. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57644. if (!this._angularSpeedGradients) {
  57645. this._angularSpeedGradients = [];
  57646. }
  57647. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57648. return this;
  57649. };
  57650. /**
  57651. * Remove a specific angular speed gradient
  57652. * @param gradient defines the gradient to remove
  57653. * @returns the current particle system
  57654. */
  57655. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57656. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57657. return this;
  57658. };
  57659. /**
  57660. * Adds a new velocity gradient
  57661. * @param gradient defines the gradient to use (between 0 and 1)
  57662. * @param factor defines the velocity to affect to the specified gradient
  57663. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57664. * @returns the current particle system
  57665. */
  57666. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57667. if (!this._velocityGradients) {
  57668. this._velocityGradients = [];
  57669. }
  57670. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57671. return this;
  57672. };
  57673. /**
  57674. * Remove a specific velocity gradient
  57675. * @param gradient defines the gradient to remove
  57676. * @returns the current particle system
  57677. */
  57678. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57679. this._removeFactorGradient(this._velocityGradients, gradient);
  57680. return this;
  57681. };
  57682. /**
  57683. * Adds a new limit velocity gradient
  57684. * @param gradient defines the gradient to use (between 0 and 1)
  57685. * @param factor defines the limit velocity value to affect to the specified gradient
  57686. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57687. * @returns the current particle system
  57688. */
  57689. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57690. if (!this._limitVelocityGradients) {
  57691. this._limitVelocityGradients = [];
  57692. }
  57693. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57694. return this;
  57695. };
  57696. /**
  57697. * Remove a specific limit velocity gradient
  57698. * @param gradient defines the gradient to remove
  57699. * @returns the current particle system
  57700. */
  57701. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57702. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57703. return this;
  57704. };
  57705. /**
  57706. * Adds a new drag gradient
  57707. * @param gradient defines the gradient to use (between 0 and 1)
  57708. * @param factor defines the drag value to affect to the specified gradient
  57709. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57710. * @returns the current particle system
  57711. */
  57712. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57713. if (!this._dragGradients) {
  57714. this._dragGradients = [];
  57715. }
  57716. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57717. return this;
  57718. };
  57719. /**
  57720. * Remove a specific drag gradient
  57721. * @param gradient defines the gradient to remove
  57722. * @returns the current particle system
  57723. */
  57724. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57725. this._removeFactorGradient(this._dragGradients, gradient);
  57726. return this;
  57727. };
  57728. /**
  57729. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57730. * @param gradient defines the gradient to use (between 0 and 1)
  57731. * @param factor defines the emit rate value to affect to the specified gradient
  57732. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57733. * @returns the current particle system
  57734. */
  57735. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57736. if (!this._emitRateGradients) {
  57737. this._emitRateGradients = [];
  57738. }
  57739. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57740. if (!this._currentEmitRateGradient) {
  57741. this._currentEmitRateGradient = this._emitRateGradients[0];
  57742. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57743. this._currentEmitRate2 = this._currentEmitRate1;
  57744. }
  57745. if (this._emitRateGradients.length === 2) {
  57746. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57747. }
  57748. return this;
  57749. };
  57750. /**
  57751. * Remove a specific emit rate gradient
  57752. * @param gradient defines the gradient to remove
  57753. * @returns the current particle system
  57754. */
  57755. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57756. this._removeFactorGradient(this._emitRateGradients, gradient);
  57757. return this;
  57758. };
  57759. /**
  57760. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57761. * @param gradient defines the gradient to use (between 0 and 1)
  57762. * @param factor defines the start size value to affect to the specified gradient
  57763. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57764. * @returns the current particle system
  57765. */
  57766. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57767. if (!this._startSizeGradients) {
  57768. this._startSizeGradients = [];
  57769. }
  57770. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57771. if (!this._currentStartSizeGradient) {
  57772. this._currentStartSizeGradient = this._startSizeGradients[0];
  57773. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57774. this._currentStartSize2 = this._currentStartSize1;
  57775. }
  57776. if (this._startSizeGradients.length === 2) {
  57777. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57778. }
  57779. return this;
  57780. };
  57781. /**
  57782. * Remove a specific start size gradient
  57783. * @param gradient defines the gradient to remove
  57784. * @returns the current particle system
  57785. */
  57786. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57787. this._removeFactorGradient(this._emitRateGradients, gradient);
  57788. return this;
  57789. };
  57790. ParticleSystem.prototype._createRampGradientTexture = function () {
  57791. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57792. return;
  57793. }
  57794. var data = new Uint8Array(this._rawTextureWidth * 4);
  57795. var tmpColor = BABYLON.Tmp.Color3[0];
  57796. for (var x = 0; x < this._rawTextureWidth; x++) {
  57797. var ratio = x / this._rawTextureWidth;
  57798. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57799. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57800. data[x * 4] = tmpColor.r * 255;
  57801. data[x * 4 + 1] = tmpColor.g * 255;
  57802. data[x * 4 + 2] = tmpColor.b * 255;
  57803. data[x * 4 + 3] = 255;
  57804. });
  57805. }
  57806. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57807. };
  57808. /**
  57809. * Gets the current list of ramp gradients.
  57810. * You must use addRampGradient and removeRampGradient to udpate this list
  57811. * @returns the list of ramp gradients
  57812. */
  57813. ParticleSystem.prototype.getRampGradients = function () {
  57814. return this._rampGradients;
  57815. };
  57816. /**
  57817. * Adds a new ramp gradient used to remap particle colors
  57818. * @param gradient defines the gradient to use (between 0 and 1)
  57819. * @param color defines the color to affect to the specified gradient
  57820. * @returns the current particle system
  57821. */
  57822. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57823. if (!this._rampGradients) {
  57824. this._rampGradients = [];
  57825. }
  57826. var rampGradient = new BABYLON.Color3Gradient();
  57827. rampGradient.gradient = gradient;
  57828. rampGradient.color = color;
  57829. this._rampGradients.push(rampGradient);
  57830. this._rampGradients.sort(function (a, b) {
  57831. if (a.gradient < b.gradient) {
  57832. return -1;
  57833. }
  57834. else if (a.gradient > b.gradient) {
  57835. return 1;
  57836. }
  57837. return 0;
  57838. });
  57839. if (this._rampGradientsTexture) {
  57840. this._rampGradientsTexture.dispose();
  57841. this._rampGradientsTexture = null;
  57842. }
  57843. this._createRampGradientTexture();
  57844. return this;
  57845. };
  57846. /**
  57847. * Remove a specific ramp gradient
  57848. * @param gradient defines the gradient to remove
  57849. * @returns the current particle system
  57850. */
  57851. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  57852. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  57853. this._rampGradientsTexture = null;
  57854. if (this._rampGradients && this._rampGradients.length > 0) {
  57855. this._createRampGradientTexture();
  57856. }
  57857. return this;
  57858. };
  57859. /**
  57860. * Adds a new color gradient
  57861. * @param gradient defines the gradient to use (between 0 and 1)
  57862. * @param color1 defines the color to affect to the specified gradient
  57863. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57864. */
  57865. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57866. if (!this._colorGradients) {
  57867. this._colorGradients = [];
  57868. }
  57869. var colorGradient = new BABYLON.ColorGradient();
  57870. colorGradient.gradient = gradient;
  57871. colorGradient.color1 = color1;
  57872. colorGradient.color2 = color2;
  57873. this._colorGradients.push(colorGradient);
  57874. this._colorGradients.sort(function (a, b) {
  57875. if (a.gradient < b.gradient) {
  57876. return -1;
  57877. }
  57878. else if (a.gradient > b.gradient) {
  57879. return 1;
  57880. }
  57881. return 0;
  57882. });
  57883. return this;
  57884. };
  57885. /**
  57886. * Remove a specific color gradient
  57887. * @param gradient defines the gradient to remove
  57888. */
  57889. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  57890. if (!this._colorGradients) {
  57891. return this;
  57892. }
  57893. var index = 0;
  57894. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57895. var colorGradient = _a[_i];
  57896. if (colorGradient.gradient === gradient) {
  57897. this._colorGradients.splice(index, 1);
  57898. break;
  57899. }
  57900. index++;
  57901. }
  57902. return this;
  57903. };
  57904. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  57905. u = Math.abs(u) * 0.5 + 0.5;
  57906. v = Math.abs(v) * 0.5 + 0.5;
  57907. var wrappedU = ((u * width) % width) | 0;
  57908. var wrappedV = ((v * height) % height) | 0;
  57909. var position = (wrappedU + wrappedV * width) * 4;
  57910. return pixels[position] / 255;
  57911. };
  57912. ParticleSystem.prototype._reset = function () {
  57913. this._resetEffect();
  57914. };
  57915. ParticleSystem.prototype._resetEffect = function () {
  57916. if (this._vertexBuffer) {
  57917. this._vertexBuffer.dispose();
  57918. this._vertexBuffer = null;
  57919. }
  57920. if (this._spriteBuffer) {
  57921. this._spriteBuffer.dispose();
  57922. this._spriteBuffer = null;
  57923. }
  57924. this._createVertexBuffers();
  57925. };
  57926. ParticleSystem.prototype._createVertexBuffers = function () {
  57927. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  57928. if (this._isAnimationSheetEnabled) {
  57929. this._vertexBufferSize += 1;
  57930. }
  57931. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57932. this._vertexBufferSize += 3;
  57933. }
  57934. if (this._useRampGradients) {
  57935. this._vertexBufferSize += 4;
  57936. }
  57937. var engine = this._scene.getEngine();
  57938. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  57939. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  57940. var dataOffset = 0;
  57941. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57943. dataOffset += 3;
  57944. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57945. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57946. dataOffset += 4;
  57947. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57948. this._vertexBuffers["angle"] = options;
  57949. dataOffset += 1;
  57950. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57951. this._vertexBuffers["size"] = size;
  57952. dataOffset += 2;
  57953. if (this._isAnimationSheetEnabled) {
  57954. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57955. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  57956. dataOffset += 1;
  57957. }
  57958. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57959. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57960. this._vertexBuffers["direction"] = directionBuffer;
  57961. dataOffset += 3;
  57962. }
  57963. if (this._useRampGradients) {
  57964. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57965. this._vertexBuffers["remapData"] = rampDataBuffer;
  57966. dataOffset += 4;
  57967. }
  57968. var offsets;
  57969. if (this._useInstancing) {
  57970. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  57971. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  57972. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  57973. }
  57974. else {
  57975. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57976. dataOffset += 2;
  57977. }
  57978. this._vertexBuffers["offset"] = offsets;
  57979. };
  57980. ParticleSystem.prototype._createIndexBuffer = function () {
  57981. if (this._useInstancing) {
  57982. return;
  57983. }
  57984. var indices = [];
  57985. var index = 0;
  57986. for (var count = 0; count < this._capacity; count++) {
  57987. indices.push(index);
  57988. indices.push(index + 1);
  57989. indices.push(index + 2);
  57990. indices.push(index);
  57991. indices.push(index + 2);
  57992. indices.push(index + 3);
  57993. index += 4;
  57994. }
  57995. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57996. };
  57997. /**
  57998. * Gets the maximum number of particles active at the same time.
  57999. * @returns The max number of active particles.
  58000. */
  58001. ParticleSystem.prototype.getCapacity = function () {
  58002. return this._capacity;
  58003. };
  58004. /**
  58005. * Gets whether there are still active particles in the system.
  58006. * @returns True if it is alive, otherwise false.
  58007. */
  58008. ParticleSystem.prototype.isAlive = function () {
  58009. return this._alive;
  58010. };
  58011. /**
  58012. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58013. * @returns True if it has been started, otherwise false.
  58014. */
  58015. ParticleSystem.prototype.isStarted = function () {
  58016. return this._started;
  58017. };
  58018. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58019. var _this = this;
  58020. this._subEmitters = new Array();
  58021. if (this.subEmitters) {
  58022. this.subEmitters.forEach(function (subEmitter) {
  58023. if (subEmitter instanceof ParticleSystem) {
  58024. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58025. }
  58026. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58027. _this._subEmitters.push([subEmitter]);
  58028. }
  58029. else if (subEmitter instanceof Array) {
  58030. _this._subEmitters.push(subEmitter);
  58031. }
  58032. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  58033. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  58034. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  58035. }
  58036. });
  58037. });
  58038. }
  58039. };
  58040. /**
  58041. * Starts the particle system and begins to emit
  58042. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58043. */
  58044. ParticleSystem.prototype.start = function (delay) {
  58045. var _this = this;
  58046. if (delay === void 0) { delay = this.startDelay; }
  58047. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58048. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58049. }
  58050. if (delay) {
  58051. setTimeout(function () {
  58052. _this.start(0);
  58053. }, delay);
  58054. return;
  58055. }
  58056. // Convert the subEmitters field to the constant type field _subEmitters
  58057. this._prepareSubEmitterInternalArray();
  58058. this._started = true;
  58059. this._stopped = false;
  58060. this._actualFrame = 0;
  58061. if (this._subEmitters && this._subEmitters.length != 0) {
  58062. this.activeSubSystems = new Array();
  58063. }
  58064. if (this.preWarmCycles) {
  58065. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58066. this.emitter.computeWorldMatrix(true);
  58067. }
  58068. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58069. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58070. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58071. setTimeout(function () {
  58072. for (var index = 0; index < _this.preWarmCycles; index++) {
  58073. _this.animate(true);
  58074. noiseTextureAsProcedural_1.render();
  58075. }
  58076. });
  58077. });
  58078. }
  58079. else {
  58080. for (var index = 0; index < this.preWarmCycles; index++) {
  58081. this.animate(true);
  58082. }
  58083. }
  58084. }
  58085. };
  58086. /**
  58087. * Stops the particle system.
  58088. * @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.
  58089. */
  58090. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58091. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58092. this._stopped = true;
  58093. if (stopSubEmitters) {
  58094. this._stopSubEmitters();
  58095. }
  58096. };
  58097. // animation sheet
  58098. /**
  58099. * Remove all active particles
  58100. */
  58101. ParticleSystem.prototype.reset = function () {
  58102. this._stockParticles = [];
  58103. this._particles = [];
  58104. };
  58105. /**
  58106. * @hidden (for internal use only)
  58107. */
  58108. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58109. var offset = index * this._vertexBufferSize;
  58110. this._vertexData[offset++] = particle.position.x;
  58111. this._vertexData[offset++] = particle.position.y;
  58112. this._vertexData[offset++] = particle.position.z;
  58113. this._vertexData[offset++] = particle.color.r;
  58114. this._vertexData[offset++] = particle.color.g;
  58115. this._vertexData[offset++] = particle.color.b;
  58116. this._vertexData[offset++] = particle.color.a;
  58117. this._vertexData[offset++] = particle.angle;
  58118. this._vertexData[offset++] = particle.scale.x * particle.size;
  58119. this._vertexData[offset++] = particle.scale.y * particle.size;
  58120. if (this._isAnimationSheetEnabled) {
  58121. this._vertexData[offset++] = particle.cellIndex;
  58122. }
  58123. if (!this._isBillboardBased) {
  58124. if (particle._initialDirection) {
  58125. this._vertexData[offset++] = particle._initialDirection.x;
  58126. this._vertexData[offset++] = particle._initialDirection.y;
  58127. this._vertexData[offset++] = particle._initialDirection.z;
  58128. }
  58129. else {
  58130. this._vertexData[offset++] = particle.direction.x;
  58131. this._vertexData[offset++] = particle.direction.y;
  58132. this._vertexData[offset++] = particle.direction.z;
  58133. }
  58134. }
  58135. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58136. this._vertexData[offset++] = particle.direction.x;
  58137. this._vertexData[offset++] = particle.direction.y;
  58138. this._vertexData[offset++] = particle.direction.z;
  58139. }
  58140. if (this._useRampGradients) {
  58141. this._vertexData[offset++] = particle.remapData.x;
  58142. this._vertexData[offset++] = particle.remapData.y;
  58143. this._vertexData[offset++] = particle.remapData.z;
  58144. this._vertexData[offset++] = particle.remapData.w;
  58145. }
  58146. if (!this._useInstancing) {
  58147. if (this._isAnimationSheetEnabled) {
  58148. if (offsetX === 0)
  58149. offsetX = this._epsilon;
  58150. else if (offsetX === 1)
  58151. offsetX = 1 - this._epsilon;
  58152. if (offsetY === 0)
  58153. offsetY = this._epsilon;
  58154. else if (offsetY === 1)
  58155. offsetY = 1 - this._epsilon;
  58156. }
  58157. this._vertexData[offset++] = offsetX;
  58158. this._vertexData[offset++] = offsetY;
  58159. }
  58160. };
  58161. ParticleSystem.prototype._stopSubEmitters = function () {
  58162. if (!this.activeSubSystems) {
  58163. return;
  58164. }
  58165. this.activeSubSystems.forEach(function (subSystem) {
  58166. subSystem.stop(true);
  58167. });
  58168. this.activeSubSystems = new Array();
  58169. };
  58170. ParticleSystem.prototype._removeFromRoot = function () {
  58171. if (!this._rootParticleSystem) {
  58172. return;
  58173. }
  58174. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58175. if (index !== -1) {
  58176. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58177. }
  58178. this._rootParticleSystem = null;
  58179. };
  58180. // End of sub system methods
  58181. ParticleSystem.prototype._update = function (newParticles) {
  58182. var _this = this;
  58183. // Update current
  58184. this._alive = this._particles.length > 0;
  58185. if (this.emitter.position) {
  58186. var emitterMesh = this.emitter;
  58187. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58188. }
  58189. else {
  58190. var emitterPosition = this.emitter;
  58191. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58192. }
  58193. this.updateFunction(this._particles);
  58194. // Add new ones
  58195. var particle;
  58196. var _loop_2 = function () {
  58197. if (this_1._particles.length === this_1._capacity) {
  58198. return "break";
  58199. }
  58200. particle = this_1._createParticle();
  58201. this_1._particles.push(particle);
  58202. // Emitter
  58203. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58204. if (this_1.startPositionFunction) {
  58205. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58206. }
  58207. else {
  58208. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58209. }
  58210. if (this_1.startDirectionFunction) {
  58211. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58212. }
  58213. else {
  58214. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58215. }
  58216. if (emitPower === 0) {
  58217. if (!particle._initialDirection) {
  58218. particle._initialDirection = particle.direction.clone();
  58219. }
  58220. else {
  58221. particle._initialDirection.copyFrom(particle.direction);
  58222. }
  58223. }
  58224. else {
  58225. particle._initialDirection = null;
  58226. }
  58227. particle.direction.scaleInPlace(emitPower);
  58228. // Life time
  58229. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58230. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58231. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58232. var factorGradient1 = currentGradient;
  58233. var factorGradient2 = nextGradient;
  58234. var lifeTime1 = factorGradient1.getFactor();
  58235. var lifeTime2 = factorGradient2.getFactor();
  58236. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58237. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58238. });
  58239. }
  58240. else {
  58241. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58242. }
  58243. // Size
  58244. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58245. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58246. }
  58247. else {
  58248. particle._currentSizeGradient = this_1._sizeGradients[0];
  58249. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58250. particle.size = particle._currentSize1;
  58251. if (this_1._sizeGradients.length > 1) {
  58252. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58253. }
  58254. else {
  58255. particle._currentSize2 = particle._currentSize1;
  58256. }
  58257. }
  58258. // Size and scale
  58259. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58260. // Adjust scale by start size
  58261. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58262. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58263. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58264. if (currentGradient !== _this._currentStartSizeGradient) {
  58265. _this._currentStartSize1 = _this._currentStartSize2;
  58266. _this._currentStartSize2 = nextGradient.getFactor();
  58267. _this._currentStartSizeGradient = currentGradient;
  58268. }
  58269. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58270. particle.scale.scaleInPlace(value);
  58271. });
  58272. }
  58273. // Angle
  58274. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58275. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58276. }
  58277. else {
  58278. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58279. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58280. particle._currentAngularSpeed1 = particle.angularSpeed;
  58281. if (this_1._angularSpeedGradients.length > 1) {
  58282. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58283. }
  58284. else {
  58285. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58286. }
  58287. }
  58288. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58289. // Velocity
  58290. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58291. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58292. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58293. if (this_1._velocityGradients.length > 1) {
  58294. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58295. }
  58296. else {
  58297. particle._currentVelocity2 = particle._currentVelocity1;
  58298. }
  58299. }
  58300. // Limit velocity
  58301. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58302. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58303. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58304. if (this_1._limitVelocityGradients.length > 1) {
  58305. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58306. }
  58307. else {
  58308. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58309. }
  58310. }
  58311. // Drag
  58312. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58313. particle._currentDragGradient = this_1._dragGradients[0];
  58314. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58315. if (this_1._dragGradients.length > 1) {
  58316. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58317. }
  58318. else {
  58319. particle._currentDrag2 = particle._currentDrag1;
  58320. }
  58321. }
  58322. // Color
  58323. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58324. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58325. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58326. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58327. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58328. }
  58329. else {
  58330. particle._currentColorGradient = this_1._colorGradients[0];
  58331. particle._currentColorGradient.getColorToRef(particle.color);
  58332. particle._currentColor1.copyFrom(particle.color);
  58333. if (this_1._colorGradients.length > 1) {
  58334. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58335. }
  58336. else {
  58337. particle._currentColor2.copyFrom(particle.color);
  58338. }
  58339. }
  58340. // Sheet
  58341. if (this_1._isAnimationSheetEnabled) {
  58342. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58343. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58344. }
  58345. // Inherited Velocity
  58346. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58347. // Ramp
  58348. if (this_1._useRampGradients) {
  58349. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58350. }
  58351. // Noise texture coordinates
  58352. if (this_1.noiseTexture) {
  58353. if (particle._randomNoiseCoordinates1) {
  58354. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58355. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58356. }
  58357. else {
  58358. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58359. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58360. }
  58361. }
  58362. // Update the position of the attached sub-emitters to match their attached particle
  58363. particle._inheritParticleInfoToSubEmitters();
  58364. };
  58365. var this_1 = this, step;
  58366. for (var index = 0; index < newParticles; index++) {
  58367. var state_1 = _loop_2();
  58368. if (state_1 === "break")
  58369. break;
  58370. }
  58371. };
  58372. /** @hidden */
  58373. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58374. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58375. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58376. if (useRampGradients === void 0) { useRampGradients = false; }
  58377. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58378. if (isAnimationSheetEnabled) {
  58379. attributeNamesOrOptions.push("cellIndex");
  58380. }
  58381. if (!isBillboardBased) {
  58382. attributeNamesOrOptions.push("direction");
  58383. }
  58384. if (useRampGradients) {
  58385. attributeNamesOrOptions.push("remapData");
  58386. }
  58387. return attributeNamesOrOptions;
  58388. };
  58389. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58390. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58391. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58392. if (isAnimationSheetEnabled) {
  58393. effectCreationOption.push("particlesInfos");
  58394. }
  58395. return effectCreationOption;
  58396. };
  58397. ParticleSystem.prototype._getEffect = function (blendMode) {
  58398. if (this._customEffect) {
  58399. return this._customEffect;
  58400. }
  58401. ;
  58402. var defines = [];
  58403. if (this._scene.clipPlane) {
  58404. defines.push("#define CLIPPLANE");
  58405. }
  58406. if (this._scene.clipPlane2) {
  58407. defines.push("#define CLIPPLANE2");
  58408. }
  58409. if (this._scene.clipPlane3) {
  58410. defines.push("#define CLIPPLANE3");
  58411. }
  58412. if (this._scene.clipPlane4) {
  58413. defines.push("#define CLIPPLANE4");
  58414. }
  58415. if (this._isAnimationSheetEnabled) {
  58416. defines.push("#define ANIMATESHEET");
  58417. }
  58418. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58419. defines.push("#define BLENDMULTIPLYMODE");
  58420. }
  58421. if (this._useRampGradients) {
  58422. defines.push("#define RAMPGRADIENT");
  58423. }
  58424. if (this._isBillboardBased) {
  58425. defines.push("#define BILLBOARD");
  58426. switch (this.billboardMode) {
  58427. case ParticleSystem.BILLBOARDMODE_Y:
  58428. defines.push("#define BILLBOARDY");
  58429. break;
  58430. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58431. defines.push("#define BILLBOARDSTRETCHED");
  58432. break;
  58433. case ParticleSystem.BILLBOARDMODE_ALL:
  58434. default:
  58435. break;
  58436. }
  58437. }
  58438. if (this._imageProcessingConfiguration) {
  58439. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58440. defines.push(this._imageProcessingConfigurationDefines.toString());
  58441. }
  58442. // Effect
  58443. var join = defines.join("\n");
  58444. if (this._cachedDefines !== join) {
  58445. this._cachedDefines = join;
  58446. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58447. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58448. var samplers = ["diffuseSampler", "rampSampler"];
  58449. if (BABYLON.ImageProcessingConfiguration) {
  58450. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58451. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58452. }
  58453. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58454. }
  58455. return this._effect;
  58456. };
  58457. /**
  58458. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58459. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58460. */
  58461. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58462. var _this = this;
  58463. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58464. if (!this._started)
  58465. return;
  58466. if (!preWarmOnly) {
  58467. // Check
  58468. if (!this.isReady())
  58469. return;
  58470. if (this._currentRenderId === this._scene.getRenderId()) {
  58471. return;
  58472. }
  58473. this._currentRenderId = this._scene.getRenderId();
  58474. }
  58475. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58476. // Determine the number of particles we need to create
  58477. var newParticles;
  58478. if (this.manualEmitCount > -1) {
  58479. newParticles = this.manualEmitCount;
  58480. this._newPartsExcess = 0;
  58481. this.manualEmitCount = 0;
  58482. }
  58483. else {
  58484. var rate_1 = this.emitRate;
  58485. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58486. var ratio = this._actualFrame / this.targetStopDuration;
  58487. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58488. if (currentGradient !== _this._currentEmitRateGradient) {
  58489. _this._currentEmitRate1 = _this._currentEmitRate2;
  58490. _this._currentEmitRate2 = nextGradient.getFactor();
  58491. _this._currentEmitRateGradient = currentGradient;
  58492. }
  58493. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58494. });
  58495. }
  58496. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58497. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58498. }
  58499. if (this._newPartsExcess > 1.0) {
  58500. newParticles += this._newPartsExcess >> 0;
  58501. this._newPartsExcess -= this._newPartsExcess >> 0;
  58502. }
  58503. this._alive = false;
  58504. if (!this._stopped) {
  58505. this._actualFrame += this._scaledUpdateSpeed;
  58506. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58507. this.stop();
  58508. }
  58509. else {
  58510. newParticles = 0;
  58511. }
  58512. this._update(newParticles);
  58513. // Stopped?
  58514. if (this._stopped) {
  58515. if (!this._alive) {
  58516. this._started = false;
  58517. if (this.onAnimationEnd) {
  58518. this.onAnimationEnd();
  58519. }
  58520. if (this.disposeOnStop) {
  58521. this._scene._toBeDisposed.push(this);
  58522. }
  58523. }
  58524. }
  58525. if (!preWarmOnly) {
  58526. // Update VBO
  58527. var offset = 0;
  58528. for (var index = 0; index < this._particles.length; index++) {
  58529. var particle = this._particles[index];
  58530. this._appendParticleVertices(offset, particle);
  58531. offset += this._useInstancing ? 1 : 4;
  58532. }
  58533. if (this._vertexBuffer) {
  58534. this._vertexBuffer.update(this._vertexData);
  58535. }
  58536. }
  58537. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58538. this.stop();
  58539. }
  58540. };
  58541. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58542. this._appendParticleVertex(offset++, particle, 0, 0);
  58543. if (!this._useInstancing) {
  58544. this._appendParticleVertex(offset++, particle, 1, 0);
  58545. this._appendParticleVertex(offset++, particle, 1, 1);
  58546. this._appendParticleVertex(offset++, particle, 0, 1);
  58547. }
  58548. };
  58549. /**
  58550. * Rebuilds the particle system.
  58551. */
  58552. ParticleSystem.prototype.rebuild = function () {
  58553. this._createIndexBuffer();
  58554. if (this._vertexBuffer) {
  58555. this._vertexBuffer._rebuild();
  58556. }
  58557. };
  58558. /**
  58559. * Is this system ready to be used/rendered
  58560. * @return true if the system is ready
  58561. */
  58562. ParticleSystem.prototype.isReady = function () {
  58563. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58564. return false;
  58565. }
  58566. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58567. if (!this._getEffect(this.blendMode).isReady()) {
  58568. return false;
  58569. }
  58570. }
  58571. else {
  58572. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58573. return false;
  58574. }
  58575. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58576. return false;
  58577. }
  58578. }
  58579. return true;
  58580. };
  58581. ParticleSystem.prototype._render = function (blendMode) {
  58582. var effect = this._getEffect(blendMode);
  58583. var engine = this._scene.getEngine();
  58584. // Render
  58585. engine.enableEffect(effect);
  58586. var viewMatrix = this._scene.getViewMatrix();
  58587. effect.setTexture("diffuseSampler", this.particleTexture);
  58588. effect.setMatrix("view", viewMatrix);
  58589. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58590. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58591. var baseSize = this.particleTexture.getBaseSize();
  58592. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58593. }
  58594. effect.setVector2("translationPivot", this.translationPivot);
  58595. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58596. if (this._isBillboardBased) {
  58597. var camera = this._scene.activeCamera;
  58598. effect.setVector3("eyePosition", camera.globalPosition);
  58599. }
  58600. if (this._rampGradientsTexture) {
  58601. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58602. }
  58603. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58604. var invView = viewMatrix.clone();
  58605. invView.invert();
  58606. effect.setMatrix("invView", invView);
  58607. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58608. }
  58609. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58610. // image processing
  58611. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58612. this._imageProcessingConfiguration.bind(effect);
  58613. }
  58614. // Draw order
  58615. switch (blendMode) {
  58616. case ParticleSystem.BLENDMODE_ADD:
  58617. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58618. break;
  58619. case ParticleSystem.BLENDMODE_ONEONE:
  58620. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58621. break;
  58622. case ParticleSystem.BLENDMODE_STANDARD:
  58623. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58624. break;
  58625. case ParticleSystem.BLENDMODE_MULTIPLY:
  58626. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58627. break;
  58628. }
  58629. if (this._useInstancing) {
  58630. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58631. }
  58632. else {
  58633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58634. }
  58635. return this._particles.length;
  58636. };
  58637. /**
  58638. * Renders the particle system in its current state.
  58639. * @returns the current number of particles
  58640. */
  58641. ParticleSystem.prototype.render = function () {
  58642. // Check
  58643. if (!this.isReady() || !this._particles.length) {
  58644. return 0;
  58645. }
  58646. var engine = this._scene.getEngine();
  58647. engine.setState(false);
  58648. if (this.forceDepthWrite) {
  58649. engine.setDepthWrite(true);
  58650. }
  58651. var outparticles = 0;
  58652. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58653. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58654. }
  58655. outparticles = this._render(this.blendMode);
  58656. engine.unbindInstanceAttributes();
  58657. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58658. return outparticles;
  58659. };
  58660. /**
  58661. * Disposes the particle system and free the associated resources
  58662. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58663. */
  58664. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58665. if (disposeTexture === void 0) { disposeTexture = true; }
  58666. if (this._vertexBuffer) {
  58667. this._vertexBuffer.dispose();
  58668. this._vertexBuffer = null;
  58669. }
  58670. if (this._spriteBuffer) {
  58671. this._spriteBuffer.dispose();
  58672. this._spriteBuffer = null;
  58673. }
  58674. if (this._indexBuffer) {
  58675. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58676. this._indexBuffer = null;
  58677. }
  58678. if (disposeTexture && this.particleTexture) {
  58679. this.particleTexture.dispose();
  58680. this.particleTexture = null;
  58681. }
  58682. if (disposeTexture && this.noiseTexture) {
  58683. this.noiseTexture.dispose();
  58684. this.noiseTexture = null;
  58685. }
  58686. if (this._rampGradientsTexture) {
  58687. this._rampGradientsTexture.dispose();
  58688. this._rampGradientsTexture = null;
  58689. }
  58690. this._removeFromRoot();
  58691. if (this._subEmitters && this._subEmitters.length) {
  58692. for (var index = 0; index < this._subEmitters.length; index++) {
  58693. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58694. var subEmitter = _a[_i];
  58695. subEmitter.dispose();
  58696. }
  58697. }
  58698. this._subEmitters = [];
  58699. this.subEmitters = [];
  58700. }
  58701. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58702. this.emitter.dispose(true);
  58703. }
  58704. // Remove from scene
  58705. var index = this._scene.particleSystems.indexOf(this);
  58706. if (index > -1) {
  58707. this._scene.particleSystems.splice(index, 1);
  58708. }
  58709. this._scene._activeParticleSystems.dispose();
  58710. // Callback
  58711. this.onDisposeObservable.notifyObservers(this);
  58712. this.onDisposeObservable.clear();
  58713. this.reset();
  58714. };
  58715. // Clone
  58716. /**
  58717. * Clones the particle system.
  58718. * @param name The name of the cloned object
  58719. * @param newEmitter The new emitter to use
  58720. * @returns the cloned particle system
  58721. */
  58722. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58723. var custom = null;
  58724. var program = null;
  58725. if (this.customShader != null) {
  58726. program = this.customShader;
  58727. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58728. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58729. }
  58730. else if (this._customEffect) {
  58731. custom = this._customEffect;
  58732. }
  58733. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58734. result.customShader = program;
  58735. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58736. if (newEmitter === undefined) {
  58737. newEmitter = this.emitter;
  58738. }
  58739. result.noiseTexture = this.noiseTexture;
  58740. result.emitter = newEmitter;
  58741. if (this.particleTexture) {
  58742. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58743. }
  58744. // Clone gradients
  58745. if (this._colorGradients) {
  58746. this._colorGradients.forEach(function (v) {
  58747. result.addColorGradient(v.gradient, v.color1, v.color2);
  58748. });
  58749. }
  58750. if (this._dragGradients) {
  58751. this._dragGradients.forEach(function (v) {
  58752. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58753. });
  58754. }
  58755. if (this._angularSpeedGradients) {
  58756. this._angularSpeedGradients.forEach(function (v) {
  58757. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58758. });
  58759. }
  58760. if (this._emitRateGradients) {
  58761. this._emitRateGradients.forEach(function (v) {
  58762. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58763. });
  58764. }
  58765. if (this._lifeTimeGradients) {
  58766. this._lifeTimeGradients.forEach(function (v) {
  58767. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58768. });
  58769. }
  58770. if (this._limitVelocityGradients) {
  58771. this._limitVelocityGradients.forEach(function (v) {
  58772. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58773. });
  58774. }
  58775. if (this._sizeGradients) {
  58776. this._sizeGradients.forEach(function (v) {
  58777. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58778. });
  58779. }
  58780. if (this._startSizeGradients) {
  58781. this._startSizeGradients.forEach(function (v) {
  58782. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58783. });
  58784. }
  58785. if (this._velocityGradients) {
  58786. this._velocityGradients.forEach(function (v) {
  58787. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58788. });
  58789. }
  58790. if (this._rampGradients) {
  58791. this._rampGradients.forEach(function (v) {
  58792. result.addRampGradient(v.gradient, v.color);
  58793. });
  58794. }
  58795. if (this._colorRemapGradients) {
  58796. this._colorRemapGradients.forEach(function (v) {
  58797. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58798. });
  58799. }
  58800. if (this._alphaRemapGradients) {
  58801. this._alphaRemapGradients.forEach(function (v) {
  58802. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58803. });
  58804. }
  58805. if (!this.preventAutoStart) {
  58806. result.start();
  58807. }
  58808. return result;
  58809. };
  58810. /**
  58811. * Serializes the particle system to a JSON object.
  58812. * @returns the JSON object
  58813. */
  58814. ParticleSystem.prototype.serialize = function () {
  58815. var serializationObject = {};
  58816. ParticleSystem._Serialize(serializationObject, this);
  58817. serializationObject.textureMask = this.textureMask.asArray();
  58818. serializationObject.customShader = this.customShader;
  58819. serializationObject.preventAutoStart = this.preventAutoStart;
  58820. // SubEmitters
  58821. if (this.subEmitters) {
  58822. serializationObject.subEmitters = [];
  58823. if (!this._subEmitters) {
  58824. this._prepareSubEmitterInternalArray();
  58825. }
  58826. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  58827. var subs = _a[_i];
  58828. var cell = [];
  58829. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  58830. var sub = subs_1[_b];
  58831. cell.push(sub.serialize());
  58832. }
  58833. serializationObject.subEmitters.push(cell);
  58834. }
  58835. }
  58836. return serializationObject;
  58837. };
  58838. /** @hidden */
  58839. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58840. serializationObject.name = particleSystem.name;
  58841. serializationObject.id = particleSystem.id;
  58842. serializationObject.capacity = particleSystem.getCapacity();
  58843. // Emitter
  58844. if (particleSystem.emitter.position) {
  58845. var emitterMesh = particleSystem.emitter;
  58846. serializationObject.emitterId = emitterMesh.id;
  58847. }
  58848. else {
  58849. var emitterPosition = particleSystem.emitter;
  58850. serializationObject.emitter = emitterPosition.asArray();
  58851. }
  58852. // Emitter
  58853. if (particleSystem.particleEmitterType) {
  58854. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  58855. }
  58856. if (particleSystem.particleTexture) {
  58857. serializationObject.textureName = particleSystem.particleTexture.name;
  58858. serializationObject.invertY = particleSystem.particleTexture._invertY;
  58859. }
  58860. // Animations
  58861. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  58862. // Particle system
  58863. serializationObject.startDelay = particleSystem.startDelay;
  58864. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  58865. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  58866. serializationObject.billboardMode = particleSystem.billboardMode;
  58867. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  58868. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  58869. serializationObject.minSize = particleSystem.minSize;
  58870. serializationObject.maxSize = particleSystem.maxSize;
  58871. serializationObject.minScaleX = particleSystem.minScaleX;
  58872. serializationObject.maxScaleX = particleSystem.maxScaleX;
  58873. serializationObject.minScaleY = particleSystem.minScaleY;
  58874. serializationObject.maxScaleY = particleSystem.maxScaleY;
  58875. serializationObject.minEmitPower = particleSystem.minEmitPower;
  58876. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  58877. serializationObject.minLifeTime = particleSystem.minLifeTime;
  58878. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  58879. serializationObject.emitRate = particleSystem.emitRate;
  58880. serializationObject.gravity = particleSystem.gravity.asArray();
  58881. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  58882. serializationObject.color1 = particleSystem.color1.asArray();
  58883. serializationObject.color2 = particleSystem.color2.asArray();
  58884. serializationObject.colorDead = particleSystem.colorDead.asArray();
  58885. serializationObject.updateSpeed = particleSystem.updateSpeed;
  58886. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  58887. serializationObject.blendMode = particleSystem.blendMode;
  58888. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  58889. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  58890. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  58891. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  58892. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  58893. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  58894. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  58895. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  58896. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  58897. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  58898. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  58899. var colorGradients = particleSystem.getColorGradients();
  58900. if (colorGradients) {
  58901. serializationObject.colorGradients = [];
  58902. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  58903. var colorGradient = colorGradients_1[_i];
  58904. var serializedGradient = {
  58905. gradient: colorGradient.gradient,
  58906. color1: colorGradient.color1.asArray()
  58907. };
  58908. if (colorGradient.color2) {
  58909. serializedGradient.color2 = colorGradient.color2.asArray();
  58910. }
  58911. serializationObject.colorGradients.push(serializedGradient);
  58912. }
  58913. }
  58914. var rampGradients = particleSystem.getRampGradients();
  58915. if (rampGradients) {
  58916. serializationObject.rampGradients = [];
  58917. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  58918. var rampGradient = rampGradients_1[_a];
  58919. var serializedGradient = {
  58920. gradient: rampGradient.gradient,
  58921. color: rampGradient.color.asArray()
  58922. };
  58923. serializationObject.rampGradients.push(serializedGradient);
  58924. }
  58925. serializationObject.useRampGradients = particleSystem.useRampGradients;
  58926. }
  58927. var colorRemapGradients = particleSystem.getColorRemapGradients();
  58928. if (colorRemapGradients) {
  58929. serializationObject.colorRemapGradients = [];
  58930. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  58931. var colorRemapGradient = colorRemapGradients_1[_b];
  58932. var serializedGradient = {
  58933. gradient: colorRemapGradient.gradient,
  58934. factor1: colorRemapGradient.factor1
  58935. };
  58936. if (colorRemapGradient.factor2 !== undefined) {
  58937. serializedGradient.factor2 = colorRemapGradient.factor2;
  58938. }
  58939. serializationObject.colorRemapGradients.push(serializedGradient);
  58940. }
  58941. }
  58942. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  58943. if (alphaRemapGradients) {
  58944. serializationObject.alphaRemapGradients = [];
  58945. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  58946. var alphaRemapGradient = alphaRemapGradients_1[_c];
  58947. var serializedGradient = {
  58948. gradient: alphaRemapGradient.gradient,
  58949. factor1: alphaRemapGradient.factor1
  58950. };
  58951. if (alphaRemapGradient.factor2 !== undefined) {
  58952. serializedGradient.factor2 = alphaRemapGradient.factor2;
  58953. }
  58954. serializationObject.alphaRemapGradients.push(serializedGradient);
  58955. }
  58956. }
  58957. var sizeGradients = particleSystem.getSizeGradients();
  58958. if (sizeGradients) {
  58959. serializationObject.sizeGradients = [];
  58960. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  58961. var sizeGradient = sizeGradients_1[_d];
  58962. var serializedGradient = {
  58963. gradient: sizeGradient.gradient,
  58964. factor1: sizeGradient.factor1
  58965. };
  58966. if (sizeGradient.factor2 !== undefined) {
  58967. serializedGradient.factor2 = sizeGradient.factor2;
  58968. }
  58969. serializationObject.sizeGradients.push(serializedGradient);
  58970. }
  58971. }
  58972. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  58973. if (angularSpeedGradients) {
  58974. serializationObject.angularSpeedGradients = [];
  58975. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  58976. var angularSpeedGradient = angularSpeedGradients_1[_e];
  58977. var serializedGradient = {
  58978. gradient: angularSpeedGradient.gradient,
  58979. factor1: angularSpeedGradient.factor1
  58980. };
  58981. if (angularSpeedGradient.factor2 !== undefined) {
  58982. serializedGradient.factor2 = angularSpeedGradient.factor2;
  58983. }
  58984. serializationObject.angularSpeedGradients.push(serializedGradient);
  58985. }
  58986. }
  58987. var velocityGradients = particleSystem.getVelocityGradients();
  58988. if (velocityGradients) {
  58989. serializationObject.velocityGradients = [];
  58990. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  58991. var velocityGradient = velocityGradients_1[_f];
  58992. var serializedGradient = {
  58993. gradient: velocityGradient.gradient,
  58994. factor1: velocityGradient.factor1
  58995. };
  58996. if (velocityGradient.factor2 !== undefined) {
  58997. serializedGradient.factor2 = velocityGradient.factor2;
  58998. }
  58999. serializationObject.velocityGradients.push(serializedGradient);
  59000. }
  59001. }
  59002. var dragGradients = particleSystem.getDragGradients();
  59003. if (dragGradients) {
  59004. serializationObject.dragyGradients = [];
  59005. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59006. var dragGradient = dragGradients_1[_g];
  59007. var serializedGradient = {
  59008. gradient: dragGradient.gradient,
  59009. factor1: dragGradient.factor1
  59010. };
  59011. if (dragGradient.factor2 !== undefined) {
  59012. serializedGradient.factor2 = dragGradient.factor2;
  59013. }
  59014. serializationObject.dragGradients.push(serializedGradient);
  59015. }
  59016. }
  59017. var emitRateGradients = particleSystem.getEmitRateGradients();
  59018. if (emitRateGradients) {
  59019. serializationObject.emitRateGradients = [];
  59020. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59021. var emitRateGradient = emitRateGradients_1[_h];
  59022. var serializedGradient = {
  59023. gradient: emitRateGradient.gradient,
  59024. factor1: emitRateGradient.factor1
  59025. };
  59026. if (emitRateGradient.factor2 !== undefined) {
  59027. serializedGradient.factor2 = emitRateGradient.factor2;
  59028. }
  59029. serializationObject.emitRateGradients.push(serializedGradient);
  59030. }
  59031. }
  59032. var startSizeGradients = particleSystem.getStartSizeGradients();
  59033. if (startSizeGradients) {
  59034. serializationObject.startSizeGradients = [];
  59035. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59036. var startSizeGradient = startSizeGradients_1[_j];
  59037. var serializedGradient = {
  59038. gradient: startSizeGradient.gradient,
  59039. factor1: startSizeGradient.factor1
  59040. };
  59041. if (startSizeGradient.factor2 !== undefined) {
  59042. serializedGradient.factor2 = startSizeGradient.factor2;
  59043. }
  59044. serializationObject.startSizeGradients.push(serializedGradient);
  59045. }
  59046. }
  59047. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59048. if (limitVelocityGradients) {
  59049. serializationObject.limitVelocityGradients = [];
  59050. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  59051. var limitVelocityGradient = limitVelocityGradients_1[_k];
  59052. var serializedGradient = {
  59053. gradient: limitVelocityGradient.gradient,
  59054. factor1: limitVelocityGradient.factor1
  59055. };
  59056. if (limitVelocityGradient.factor2 !== undefined) {
  59057. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59058. }
  59059. serializationObject.limitVelocityGradients.push(serializedGradient);
  59060. }
  59061. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59062. }
  59063. if (particleSystem.noiseTexture) {
  59064. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59065. }
  59066. };
  59067. /** @hidden */
  59068. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59069. // Texture
  59070. if (parsedParticleSystem.textureName) {
  59071. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59072. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59073. }
  59074. // Emitter
  59075. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59076. particleSystem.emitter = BABYLON.Vector3.Zero();
  59077. }
  59078. else if (parsedParticleSystem.emitterId) {
  59079. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59080. }
  59081. else {
  59082. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59083. }
  59084. // Misc.
  59085. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59086. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59087. }
  59088. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59089. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59090. }
  59091. if (parsedParticleSystem.billboardMode !== undefined) {
  59092. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59093. }
  59094. // Animations
  59095. if (parsedParticleSystem.animations) {
  59096. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59097. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59098. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59099. }
  59100. }
  59101. if (parsedParticleSystem.autoAnimate) {
  59102. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59103. }
  59104. // Particle system
  59105. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59106. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59107. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59108. particleSystem.minSize = parsedParticleSystem.minSize;
  59109. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59110. if (parsedParticleSystem.minScaleX) {
  59111. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59112. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59113. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59114. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59115. }
  59116. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59117. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59118. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59119. }
  59120. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59121. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59122. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59123. }
  59124. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59125. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59126. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59127. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59128. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59129. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59130. if (parsedParticleSystem.noiseStrength) {
  59131. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59132. }
  59133. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59134. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59135. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59136. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59137. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59138. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59139. if (parsedParticleSystem.colorGradients) {
  59140. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59141. var colorGradient = _a[_i];
  59142. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59143. }
  59144. }
  59145. if (parsedParticleSystem.rampGradients) {
  59146. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59147. var rampGradient = _c[_b];
  59148. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59149. }
  59150. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59151. }
  59152. if (parsedParticleSystem.colorRemapGradients) {
  59153. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59154. var colorRemapGradient = _e[_d];
  59155. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59156. }
  59157. }
  59158. if (parsedParticleSystem.alphaRemapGradients) {
  59159. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59160. var alphaRemapGradient = _g[_f];
  59161. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59162. }
  59163. }
  59164. if (parsedParticleSystem.sizeGradients) {
  59165. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59166. var sizeGradient = _j[_h];
  59167. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59168. }
  59169. }
  59170. if (parsedParticleSystem.sizeGradients) {
  59171. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59172. var sizeGradient = _l[_k];
  59173. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59174. }
  59175. }
  59176. if (parsedParticleSystem.angularSpeedGradients) {
  59177. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59178. var angularSpeedGradient = _o[_m];
  59179. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59180. }
  59181. }
  59182. if (parsedParticleSystem.velocityGradients) {
  59183. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59184. var velocityGradient = _q[_p];
  59185. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59186. }
  59187. }
  59188. if (parsedParticleSystem.dragGradients) {
  59189. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59190. var dragGradient = _s[_r];
  59191. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59192. }
  59193. }
  59194. if (parsedParticleSystem.emitRateGradients) {
  59195. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59196. var emitRateGradient = _u[_t];
  59197. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59198. }
  59199. }
  59200. if (parsedParticleSystem.startSizeGradients) {
  59201. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59202. var startSizeGradient = _w[_v];
  59203. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59204. }
  59205. }
  59206. if (parsedParticleSystem.limitVelocityGradients) {
  59207. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  59208. var limitVelocityGradient = _y[_x];
  59209. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59210. }
  59211. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59212. }
  59213. if (parsedParticleSystem.noiseTexture) {
  59214. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59215. }
  59216. // Emitter
  59217. var emitterType;
  59218. if (parsedParticleSystem.particleEmitterType) {
  59219. switch (parsedParticleSystem.particleEmitterType.type) {
  59220. case "SphereParticleEmitter":
  59221. emitterType = new BABYLON.SphereParticleEmitter();
  59222. break;
  59223. case "SphereDirectedParticleEmitter":
  59224. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59225. break;
  59226. case "ConeEmitter":
  59227. case "ConeParticleEmitter":
  59228. emitterType = new BABYLON.ConeParticleEmitter();
  59229. break;
  59230. case "BoxEmitter":
  59231. case "BoxParticleEmitter":
  59232. default:
  59233. emitterType = new BABYLON.BoxParticleEmitter();
  59234. break;
  59235. }
  59236. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59237. }
  59238. else {
  59239. emitterType = new BABYLON.BoxParticleEmitter();
  59240. emitterType.parse(parsedParticleSystem);
  59241. }
  59242. particleSystem.particleEmitterType = emitterType;
  59243. // Animation sheet
  59244. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59245. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59246. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59247. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59248. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59249. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59250. };
  59251. /**
  59252. * Parses a JSON object to create a particle system.
  59253. * @param parsedParticleSystem The JSON object to parse
  59254. * @param scene The scene to create the particle system in
  59255. * @param rootUrl The root url to use to load external dependencies like texture
  59256. * @returns the Parsed particle system
  59257. */
  59258. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  59259. var name = parsedParticleSystem.name;
  59260. var custom = null;
  59261. var program = null;
  59262. if (parsedParticleSystem.customShader) {
  59263. program = parsedParticleSystem.customShader;
  59264. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59265. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59266. }
  59267. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59268. particleSystem.customShader = program;
  59269. if (parsedParticleSystem.id) {
  59270. particleSystem.id = parsedParticleSystem.id;
  59271. }
  59272. // SubEmitters
  59273. if (parsedParticleSystem.subEmitters) {
  59274. particleSystem.subEmitters = [];
  59275. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59276. var cell = _a[_i];
  59277. var cellArray = [];
  59278. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59279. var sub = cell_1[_b];
  59280. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59281. }
  59282. particleSystem.subEmitters.push(cellArray);
  59283. }
  59284. }
  59285. // Auto start
  59286. if (parsedParticleSystem.preventAutoStart) {
  59287. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59288. }
  59289. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59290. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59291. if (!particleSystem.preventAutoStart) {
  59292. particleSystem.start();
  59293. }
  59294. return particleSystem;
  59295. };
  59296. /**
  59297. * Billboard mode will only apply to Y axis
  59298. */
  59299. ParticleSystem.BILLBOARDMODE_Y = 2;
  59300. /**
  59301. * Billboard mode will apply to all axes
  59302. */
  59303. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59304. /**
  59305. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59306. */
  59307. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59308. return ParticleSystem;
  59309. }(BABYLON.BaseParticleSystem));
  59310. BABYLON.ParticleSystem = ParticleSystem;
  59311. })(BABYLON || (BABYLON = {}));
  59312. //# sourceMappingURL=babylon.particleSystem.js.map
  59313. var BABYLON;
  59314. (function (BABYLON) {
  59315. /**
  59316. * Particle emitter emitting particles from the inside of a box.
  59317. * It emits the particles randomly between 2 given directions.
  59318. */
  59319. var BoxParticleEmitter = /** @class */ (function () {
  59320. /**
  59321. * Creates a new instance BoxParticleEmitter
  59322. */
  59323. function BoxParticleEmitter() {
  59324. /**
  59325. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59326. */
  59327. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59328. /**
  59329. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59330. */
  59331. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59332. /**
  59333. * 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.
  59334. */
  59335. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59336. /**
  59337. * 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.
  59338. */
  59339. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59340. }
  59341. /**
  59342. * Called by the particle System when the direction is computed for the created particle.
  59343. * @param worldMatrix is the world matrix of the particle system
  59344. * @param directionToUpdate is the direction vector to update with the result
  59345. * @param particle is the particle we are computed the direction for
  59346. */
  59347. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59348. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59349. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59350. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59351. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59352. };
  59353. /**
  59354. * Called by the particle System when the position is computed for the created particle.
  59355. * @param worldMatrix is the world matrix of the particle system
  59356. * @param positionToUpdate is the position vector to update with the result
  59357. * @param particle is the particle we are computed the position for
  59358. */
  59359. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59360. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59361. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59362. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59364. };
  59365. /**
  59366. * Clones the current emitter and returns a copy of it
  59367. * @returns the new emitter
  59368. */
  59369. BoxParticleEmitter.prototype.clone = function () {
  59370. var newOne = new BoxParticleEmitter();
  59371. BABYLON.Tools.DeepCopy(this, newOne);
  59372. return newOne;
  59373. };
  59374. /**
  59375. * Called by the GPUParticleSystem to setup the update shader
  59376. * @param effect defines the update shader
  59377. */
  59378. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59379. effect.setVector3("direction1", this.direction1);
  59380. effect.setVector3("direction2", this.direction2);
  59381. effect.setVector3("minEmitBox", this.minEmitBox);
  59382. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59383. };
  59384. /**
  59385. * Returns a string to use to update the GPU particles update shader
  59386. * @returns a string containng the defines string
  59387. */
  59388. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59389. return "#define BOXEMITTER";
  59390. };
  59391. /**
  59392. * Returns the string "BoxParticleEmitter"
  59393. * @returns a string containing the class name
  59394. */
  59395. BoxParticleEmitter.prototype.getClassName = function () {
  59396. return "BoxParticleEmitter";
  59397. };
  59398. /**
  59399. * Serializes the particle system to a JSON object.
  59400. * @returns the JSON object
  59401. */
  59402. BoxParticleEmitter.prototype.serialize = function () {
  59403. var serializationObject = {};
  59404. serializationObject.type = this.getClassName();
  59405. serializationObject.direction1 = this.direction1.asArray();
  59406. serializationObject.direction2 = this.direction2.asArray();
  59407. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59408. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59409. return serializationObject;
  59410. };
  59411. /**
  59412. * Parse properties from a JSON object
  59413. * @param serializationObject defines the JSON object
  59414. */
  59415. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59416. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59417. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59418. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59419. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59420. };
  59421. return BoxParticleEmitter;
  59422. }());
  59423. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59424. })(BABYLON || (BABYLON = {}));
  59425. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59426. var BABYLON;
  59427. (function (BABYLON) {
  59428. /**
  59429. * Particle emitter emitting particles from the inside of a cylinder.
  59430. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59431. */
  59432. var CylinderParticleEmitter = /** @class */ (function () {
  59433. /**
  59434. * Creates a new instance CylinderParticleEmitter
  59435. * @param radius the radius of the emission cylinder (1 by default)
  59436. * @param height the height of the emission cylinder (1 by default)
  59437. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59438. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59439. */
  59440. function CylinderParticleEmitter(
  59441. /**
  59442. * The radius of the emission cylinder.
  59443. */
  59444. radius,
  59445. /**
  59446. * The height of the emission cylinder.
  59447. */
  59448. height,
  59449. /**
  59450. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59451. */
  59452. radiusRange,
  59453. /**
  59454. * How much to randomize the particle direction [0-1].
  59455. */
  59456. directionRandomizer) {
  59457. if (radius === void 0) { radius = 1; }
  59458. if (height === void 0) { height = 1; }
  59459. if (radiusRange === void 0) { radiusRange = 1; }
  59460. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59461. this.radius = radius;
  59462. this.height = height;
  59463. this.radiusRange = radiusRange;
  59464. this.directionRandomizer = directionRandomizer;
  59465. }
  59466. /**
  59467. * Called by the particle System when the direction is computed for the created particle.
  59468. * @param worldMatrix is the world matrix of the particle system
  59469. * @param directionToUpdate is the direction vector to update with the result
  59470. * @param particle is the particle we are computed the direction for
  59471. */
  59472. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59473. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59474. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59475. var angle = Math.atan2(direction.x, direction.z);
  59476. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59477. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59478. direction.x = Math.sin(angle);
  59479. direction.z = Math.cos(angle);
  59480. direction.normalize();
  59481. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59482. };
  59483. /**
  59484. * Called by the particle System when the position is computed for the created particle.
  59485. * @param worldMatrix is the world matrix of the particle system
  59486. * @param positionToUpdate is the position vector to update with the result
  59487. * @param particle is the particle we are computed the position for
  59488. */
  59489. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59490. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59491. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59492. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59493. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59494. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59495. var xPos = positionRadius * Math.cos(angle);
  59496. var zPos = positionRadius * Math.sin(angle);
  59497. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59498. };
  59499. /**
  59500. * Clones the current emitter and returns a copy of it
  59501. * @returns the new emitter
  59502. */
  59503. CylinderParticleEmitter.prototype.clone = function () {
  59504. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59505. BABYLON.Tools.DeepCopy(this, newOne);
  59506. return newOne;
  59507. };
  59508. /**
  59509. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59510. * @param effect defines the update shader
  59511. */
  59512. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59513. effect.setFloat("radius", this.radius);
  59514. effect.setFloat("height", this.height);
  59515. effect.setFloat("radiusRange", this.radiusRange);
  59516. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59517. };
  59518. /**
  59519. * Returns a string to use to update the GPU particles update shader
  59520. * @returns a string containng the defines string
  59521. */
  59522. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59523. return "#define CYLINDEREMITTER";
  59524. };
  59525. /**
  59526. * Returns the string "CylinderParticleEmitter"
  59527. * @returns a string containing the class name
  59528. */
  59529. CylinderParticleEmitter.prototype.getClassName = function () {
  59530. return "CylinderParticleEmitter";
  59531. };
  59532. /**
  59533. * Serializes the particle system to a JSON object.
  59534. * @returns the JSON object
  59535. */
  59536. CylinderParticleEmitter.prototype.serialize = function () {
  59537. var serializationObject = {};
  59538. serializationObject.type = this.getClassName();
  59539. serializationObject.radius = this.radius;
  59540. serializationObject.height = this.height;
  59541. serializationObject.radiusRange = this.radiusRange;
  59542. serializationObject.directionRandomizer = this.directionRandomizer;
  59543. return serializationObject;
  59544. };
  59545. /**
  59546. * Parse properties from a JSON object
  59547. * @param serializationObject defines the JSON object
  59548. */
  59549. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59550. this.radius = serializationObject.radius;
  59551. this.height = serializationObject.height;
  59552. this.radiusRange = serializationObject.radiusRange;
  59553. this.directionRandomizer = serializationObject.directionRandomizer;
  59554. };
  59555. return CylinderParticleEmitter;
  59556. }());
  59557. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59558. /**
  59559. * Particle emitter emitting particles from the inside of a cylinder.
  59560. * It emits the particles randomly between two vectors.
  59561. */
  59562. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59563. __extends(CylinderDirectedParticleEmitter, _super);
  59564. /**
  59565. * Creates a new instance CylinderDirectedParticleEmitter
  59566. * @param radius the radius of the emission cylinder (1 by default)
  59567. * @param height the height of the emission cylinder (1 by default)
  59568. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59569. * @param direction1 the min limit of the emission direction (up vector by default)
  59570. * @param direction2 the max limit of the emission direction (up vector by default)
  59571. */
  59572. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59573. /**
  59574. * The min limit of the emission direction.
  59575. */
  59576. direction1,
  59577. /**
  59578. * The max limit of the emission direction.
  59579. */
  59580. direction2) {
  59581. if (radius === void 0) { radius = 1; }
  59582. if (height === void 0) { height = 1; }
  59583. if (radiusRange === void 0) { radiusRange = 1; }
  59584. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59585. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59586. var _this = _super.call(this, radius, height, radiusRange) || this;
  59587. _this.direction1 = direction1;
  59588. _this.direction2 = direction2;
  59589. return _this;
  59590. }
  59591. /**
  59592. * Called by the particle System when the direction is computed for the created particle.
  59593. * @param worldMatrix is the world matrix of the particle system
  59594. * @param directionToUpdate is the direction vector to update with the result
  59595. * @param particle is the particle we are computed the direction for
  59596. */
  59597. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59598. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59599. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59600. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59601. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59602. };
  59603. /**
  59604. * Clones the current emitter and returns a copy of it
  59605. * @returns the new emitter
  59606. */
  59607. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59608. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59609. BABYLON.Tools.DeepCopy(this, newOne);
  59610. return newOne;
  59611. };
  59612. /**
  59613. * Called by the GPUParticleSystem to setup the update shader
  59614. * @param effect defines the update shader
  59615. */
  59616. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59617. effect.setFloat("radius", this.radius);
  59618. effect.setFloat("height", this.height);
  59619. effect.setFloat("radiusRange", this.radiusRange);
  59620. effect.setVector3("direction1", this.direction1);
  59621. effect.setVector3("direction2", this.direction2);
  59622. };
  59623. /**
  59624. * Returns a string to use to update the GPU particles update shader
  59625. * @returns a string containng the defines string
  59626. */
  59627. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59628. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59629. };
  59630. /**
  59631. * Returns the string "CylinderDirectedParticleEmitter"
  59632. * @returns a string containing the class name
  59633. */
  59634. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59635. return "CylinderDirectedParticleEmitter";
  59636. };
  59637. /**
  59638. * Serializes the particle system to a JSON object.
  59639. * @returns the JSON object
  59640. */
  59641. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59642. var serializationObject = _super.prototype.serialize.call(this);
  59643. serializationObject.direction1 = this.direction1.asArray();
  59644. serializationObject.direction2 = this.direction2.asArray();
  59645. return serializationObject;
  59646. };
  59647. /**
  59648. * Parse properties from a JSON object
  59649. * @param serializationObject defines the JSON object
  59650. */
  59651. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59652. _super.prototype.parse.call(this, serializationObject);
  59653. this.direction1.copyFrom(serializationObject.direction1);
  59654. this.direction2.copyFrom(serializationObject.direction2);
  59655. };
  59656. return CylinderDirectedParticleEmitter;
  59657. }(CylinderParticleEmitter));
  59658. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59659. })(BABYLON || (BABYLON = {}));
  59660. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59661. var BABYLON;
  59662. (function (BABYLON) {
  59663. /**
  59664. * Particle emitter emitting particles from the inside of a cone.
  59665. * It emits the particles alongside the cone volume from the base to the particle.
  59666. * The emission direction might be randomized.
  59667. */
  59668. var ConeParticleEmitter = /** @class */ (function () {
  59669. /**
  59670. * Creates a new instance ConeParticleEmitter
  59671. * @param radius the radius of the emission cone (1 by default)
  59672. * @param angles the cone base angle (PI by default)
  59673. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59674. */
  59675. function ConeParticleEmitter(radius, angle,
  59676. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59677. directionRandomizer) {
  59678. if (radius === void 0) { radius = 1; }
  59679. if (angle === void 0) { angle = Math.PI; }
  59680. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59681. this.directionRandomizer = directionRandomizer;
  59682. /**
  59683. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59684. */
  59685. this.radiusRange = 1;
  59686. /**
  59687. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59688. */
  59689. this.heightRange = 1;
  59690. /**
  59691. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59692. */
  59693. this.emitFromSpawnPointOnly = false;
  59694. this.angle = angle;
  59695. this.radius = radius;
  59696. }
  59697. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59698. /**
  59699. * Gets or sets the radius of the emission cone
  59700. */
  59701. get: function () {
  59702. return this._radius;
  59703. },
  59704. set: function (value) {
  59705. this._radius = value;
  59706. this._buildHeight();
  59707. },
  59708. enumerable: true,
  59709. configurable: true
  59710. });
  59711. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59712. /**
  59713. * Gets or sets the angle of the emission cone
  59714. */
  59715. get: function () {
  59716. return this._angle;
  59717. },
  59718. set: function (value) {
  59719. this._angle = value;
  59720. this._buildHeight();
  59721. },
  59722. enumerable: true,
  59723. configurable: true
  59724. });
  59725. ConeParticleEmitter.prototype._buildHeight = function () {
  59726. if (this._angle !== 0) {
  59727. this._height = this._radius / Math.tan(this._angle / 2);
  59728. }
  59729. else {
  59730. this._height = 1;
  59731. }
  59732. };
  59733. /**
  59734. * Called by the particle System when the direction is computed for the created particle.
  59735. * @param worldMatrix is the world matrix of the particle system
  59736. * @param directionToUpdate is the direction vector to update with the result
  59737. * @param particle is the particle we are computed the direction for
  59738. */
  59739. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59740. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59741. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59742. }
  59743. else {
  59744. // measure the direction Vector from the emitter to the particle.
  59745. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59746. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59747. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59748. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59749. direction.x += randX;
  59750. direction.y += randY;
  59751. direction.z += randZ;
  59752. direction.normalize();
  59753. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59754. }
  59755. };
  59756. /**
  59757. * Called by the particle System when the position is computed for the created particle.
  59758. * @param worldMatrix is the world matrix of the particle system
  59759. * @param positionToUpdate is the position vector to update with the result
  59760. * @param particle is the particle we are computed the position for
  59761. */
  59762. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59763. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59764. var h;
  59765. if (!this.emitFromSpawnPointOnly) {
  59766. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59767. // Better distribution in a cone at normal angles.
  59768. h = 1 - h * h;
  59769. }
  59770. else {
  59771. h = 0.0001;
  59772. }
  59773. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59774. radius = radius * h;
  59775. var randX = radius * Math.sin(s);
  59776. var randZ = radius * Math.cos(s);
  59777. var randY = h * this._height;
  59778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59779. };
  59780. /**
  59781. * Clones the current emitter and returns a copy of it
  59782. * @returns the new emitter
  59783. */
  59784. ConeParticleEmitter.prototype.clone = function () {
  59785. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59786. BABYLON.Tools.DeepCopy(this, newOne);
  59787. return newOne;
  59788. };
  59789. /**
  59790. * Called by the GPUParticleSystem to setup the update shader
  59791. * @param effect defines the update shader
  59792. */
  59793. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59794. effect.setFloat2("radius", this._radius, this.radiusRange);
  59795. effect.setFloat("coneAngle", this._angle);
  59796. effect.setFloat2("height", this._height, this.heightRange);
  59797. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59798. };
  59799. /**
  59800. * Returns a string to use to update the GPU particles update shader
  59801. * @returns a string containng the defines string
  59802. */
  59803. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59804. var defines = "#define CONEEMITTER";
  59805. if (this.emitFromSpawnPointOnly) {
  59806. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59807. }
  59808. return defines;
  59809. };
  59810. /**
  59811. * Returns the string "ConeParticleEmitter"
  59812. * @returns a string containing the class name
  59813. */
  59814. ConeParticleEmitter.prototype.getClassName = function () {
  59815. return "ConeParticleEmitter";
  59816. };
  59817. /**
  59818. * Serializes the particle system to a JSON object.
  59819. * @returns the JSON object
  59820. */
  59821. ConeParticleEmitter.prototype.serialize = function () {
  59822. var serializationObject = {};
  59823. serializationObject.type = this.getClassName();
  59824. serializationObject.radius = this._radius;
  59825. serializationObject.angle = this._angle;
  59826. serializationObject.directionRandomizer = this.directionRandomizer;
  59827. return serializationObject;
  59828. };
  59829. /**
  59830. * Parse properties from a JSON object
  59831. * @param serializationObject defines the JSON object
  59832. */
  59833. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  59834. this.radius = serializationObject.radius;
  59835. this.angle = serializationObject.angle;
  59836. this.directionRandomizer = serializationObject.directionRandomizer;
  59837. };
  59838. return ConeParticleEmitter;
  59839. }());
  59840. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  59841. })(BABYLON || (BABYLON = {}));
  59842. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  59843. var BABYLON;
  59844. (function (BABYLON) {
  59845. /**
  59846. * Particle emitter emitting particles from the inside of a sphere.
  59847. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  59848. */
  59849. var SphereParticleEmitter = /** @class */ (function () {
  59850. /**
  59851. * Creates a new instance SphereParticleEmitter
  59852. * @param radius the radius of the emission sphere (1 by default)
  59853. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59854. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59855. */
  59856. function SphereParticleEmitter(
  59857. /**
  59858. * The radius of the emission sphere.
  59859. */
  59860. radius,
  59861. /**
  59862. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59863. */
  59864. radiusRange,
  59865. /**
  59866. * How much to randomize the particle direction [0-1].
  59867. */
  59868. directionRandomizer) {
  59869. if (radius === void 0) { radius = 1; }
  59870. if (radiusRange === void 0) { radiusRange = 1; }
  59871. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59872. this.radius = radius;
  59873. this.radiusRange = radiusRange;
  59874. this.directionRandomizer = directionRandomizer;
  59875. }
  59876. /**
  59877. * Called by the particle System when the direction is computed for the created particle.
  59878. * @param worldMatrix is the world matrix of the particle system
  59879. * @param directionToUpdate is the direction vector to update with the result
  59880. * @param particle is the particle we are computed the direction for
  59881. */
  59882. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59883. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59884. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59885. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59886. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59887. direction.x += randX;
  59888. direction.y += randY;
  59889. direction.z += randZ;
  59890. direction.normalize();
  59891. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59892. };
  59893. /**
  59894. * Called by the particle System when the position is computed for the created particle.
  59895. * @param worldMatrix is the world matrix of the particle system
  59896. * @param positionToUpdate is the position vector to update with the result
  59897. * @param particle is the particle we are computed the position for
  59898. */
  59899. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59900. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59901. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59902. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59903. var theta = Math.acos(2 * v - 1);
  59904. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59905. var randY = randRadius * Math.cos(theta);
  59906. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59907. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59908. };
  59909. /**
  59910. * Clones the current emitter and returns a copy of it
  59911. * @returns the new emitter
  59912. */
  59913. SphereParticleEmitter.prototype.clone = function () {
  59914. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  59915. BABYLON.Tools.DeepCopy(this, newOne);
  59916. return newOne;
  59917. };
  59918. /**
  59919. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59920. * @param effect defines the update shader
  59921. */
  59922. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  59923. effect.setFloat("radius", this.radius);
  59924. effect.setFloat("radiusRange", this.radiusRange);
  59925. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59926. };
  59927. /**
  59928. * Returns a string to use to update the GPU particles update shader
  59929. * @returns a string containng the defines string
  59930. */
  59931. SphereParticleEmitter.prototype.getEffectDefines = function () {
  59932. return "#define SPHEREEMITTER";
  59933. };
  59934. /**
  59935. * Returns the string "SphereParticleEmitter"
  59936. * @returns a string containing the class name
  59937. */
  59938. SphereParticleEmitter.prototype.getClassName = function () {
  59939. return "SphereParticleEmitter";
  59940. };
  59941. /**
  59942. * Serializes the particle system to a JSON object.
  59943. * @returns the JSON object
  59944. */
  59945. SphereParticleEmitter.prototype.serialize = function () {
  59946. var serializationObject = {};
  59947. serializationObject.type = this.getClassName();
  59948. serializationObject.radius = this.radius;
  59949. serializationObject.radiusRange = this.radiusRange;
  59950. serializationObject.directionRandomizer = this.directionRandomizer;
  59951. return serializationObject;
  59952. };
  59953. /**
  59954. * Parse properties from a JSON object
  59955. * @param serializationObject defines the JSON object
  59956. */
  59957. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  59958. this.radius = serializationObject.radius;
  59959. this.radiusRange = serializationObject.radiusRange;
  59960. this.directionRandomizer = serializationObject.directionRandomizer;
  59961. };
  59962. return SphereParticleEmitter;
  59963. }());
  59964. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  59965. /**
  59966. * Particle emitter emitting particles from the inside of a sphere.
  59967. * It emits the particles randomly between two vectors.
  59968. */
  59969. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  59970. __extends(SphereDirectedParticleEmitter, _super);
  59971. /**
  59972. * Creates a new instance SphereDirectedParticleEmitter
  59973. * @param radius the radius of the emission sphere (1 by default)
  59974. * @param direction1 the min limit of the emission direction (up vector by default)
  59975. * @param direction2 the max limit of the emission direction (up vector by default)
  59976. */
  59977. function SphereDirectedParticleEmitter(radius,
  59978. /**
  59979. * The min limit of the emission direction.
  59980. */
  59981. direction1,
  59982. /**
  59983. * The max limit of the emission direction.
  59984. */
  59985. direction2) {
  59986. if (radius === void 0) { radius = 1; }
  59987. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59988. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59989. var _this = _super.call(this, radius) || this;
  59990. _this.direction1 = direction1;
  59991. _this.direction2 = direction2;
  59992. return _this;
  59993. }
  59994. /**
  59995. * Called by the particle System when the direction is computed for the created particle.
  59996. * @param worldMatrix is the world matrix of the particle system
  59997. * @param directionToUpdate is the direction vector to update with the result
  59998. * @param particle is the particle we are computed the direction for
  59999. */
  60000. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60001. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60002. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60003. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60004. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60005. };
  60006. /**
  60007. * Clones the current emitter and returns a copy of it
  60008. * @returns the new emitter
  60009. */
  60010. SphereDirectedParticleEmitter.prototype.clone = function () {
  60011. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60012. BABYLON.Tools.DeepCopy(this, newOne);
  60013. return newOne;
  60014. };
  60015. /**
  60016. * Called by the GPUParticleSystem to setup the update shader
  60017. * @param effect defines the update shader
  60018. */
  60019. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60020. effect.setFloat("radius", this.radius);
  60021. effect.setFloat("radiusRange", this.radiusRange);
  60022. effect.setVector3("direction1", this.direction1);
  60023. effect.setVector3("direction2", this.direction2);
  60024. };
  60025. /**
  60026. * Returns a string to use to update the GPU particles update shader
  60027. * @returns a string containng the defines string
  60028. */
  60029. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60030. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60031. };
  60032. /**
  60033. * Returns the string "SphereDirectedParticleEmitter"
  60034. * @returns a string containing the class name
  60035. */
  60036. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60037. return "SphereDirectedParticleEmitter";
  60038. };
  60039. /**
  60040. * Serializes the particle system to a JSON object.
  60041. * @returns the JSON object
  60042. */
  60043. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60044. var serializationObject = _super.prototype.serialize.call(this);
  60045. serializationObject.direction1 = this.direction1.asArray();
  60046. serializationObject.direction2 = this.direction2.asArray();
  60047. return serializationObject;
  60048. };
  60049. /**
  60050. * Parse properties from a JSON object
  60051. * @param serializationObject defines the JSON object
  60052. */
  60053. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60054. _super.prototype.parse.call(this, serializationObject);
  60055. this.direction1.copyFrom(serializationObject.direction1);
  60056. this.direction2.copyFrom(serializationObject.direction2);
  60057. };
  60058. return SphereDirectedParticleEmitter;
  60059. }(SphereParticleEmitter));
  60060. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60061. })(BABYLON || (BABYLON = {}));
  60062. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60063. var BABYLON;
  60064. (function (BABYLON) {
  60065. /**
  60066. * Particle emitter emitting particles from the inside of a hemisphere.
  60067. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60068. */
  60069. var HemisphericParticleEmitter = /** @class */ (function () {
  60070. /**
  60071. * Creates a new instance HemisphericParticleEmitter
  60072. * @param radius the radius of the emission hemisphere (1 by default)
  60073. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60074. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60075. */
  60076. function HemisphericParticleEmitter(
  60077. /**
  60078. * The radius of the emission hemisphere.
  60079. */
  60080. radius,
  60081. /**
  60082. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60083. */
  60084. radiusRange,
  60085. /**
  60086. * How much to randomize the particle direction [0-1].
  60087. */
  60088. directionRandomizer) {
  60089. if (radius === void 0) { radius = 1; }
  60090. if (radiusRange === void 0) { radiusRange = 1; }
  60091. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60092. this.radius = radius;
  60093. this.radiusRange = radiusRange;
  60094. this.directionRandomizer = directionRandomizer;
  60095. }
  60096. /**
  60097. * Called by the particle System when the direction is computed for the created particle.
  60098. * @param worldMatrix is the world matrix of the particle system
  60099. * @param directionToUpdate is the direction vector to update with the result
  60100. * @param particle is the particle we are computed the direction for
  60101. */
  60102. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60103. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60104. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60105. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60106. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60107. direction.x += randX;
  60108. direction.y += randY;
  60109. direction.z += randZ;
  60110. direction.normalize();
  60111. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60112. };
  60113. /**
  60114. * Called by the particle System when the position is computed for the created particle.
  60115. * @param worldMatrix is the world matrix of the particle system
  60116. * @param positionToUpdate is the position vector to update with the result
  60117. * @param particle is the particle we are computed the position for
  60118. */
  60119. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60120. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60121. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60122. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60123. var theta = Math.acos(2 * v - 1);
  60124. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60125. var randY = randRadius * Math.cos(theta);
  60126. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60128. };
  60129. /**
  60130. * Clones the current emitter and returns a copy of it
  60131. * @returns the new emitter
  60132. */
  60133. HemisphericParticleEmitter.prototype.clone = function () {
  60134. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60135. BABYLON.Tools.DeepCopy(this, newOne);
  60136. return newOne;
  60137. };
  60138. /**
  60139. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60140. * @param effect defines the update shader
  60141. */
  60142. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60143. effect.setFloat("radius", this.radius);
  60144. effect.setFloat("radiusRange", this.radiusRange);
  60145. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60146. };
  60147. /**
  60148. * Returns a string to use to update the GPU particles update shader
  60149. * @returns a string containng the defines string
  60150. */
  60151. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60152. return "#define HEMISPHERICEMITTER";
  60153. };
  60154. /**
  60155. * Returns the string "HemisphericParticleEmitter"
  60156. * @returns a string containing the class name
  60157. */
  60158. HemisphericParticleEmitter.prototype.getClassName = function () {
  60159. return "HemisphericParticleEmitter";
  60160. };
  60161. /**
  60162. * Serializes the particle system to a JSON object.
  60163. * @returns the JSON object
  60164. */
  60165. HemisphericParticleEmitter.prototype.serialize = function () {
  60166. var serializationObject = {};
  60167. serializationObject.type = this.getClassName();
  60168. serializationObject.radius = this.radius;
  60169. serializationObject.radiusRange = this.radiusRange;
  60170. serializationObject.directionRandomizer = this.directionRandomizer;
  60171. return serializationObject;
  60172. };
  60173. /**
  60174. * Parse properties from a JSON object
  60175. * @param serializationObject defines the JSON object
  60176. */
  60177. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60178. this.radius = serializationObject.radius;
  60179. this.radiusRange = serializationObject.radiusRange;
  60180. this.directionRandomizer = serializationObject.directionRandomizer;
  60181. };
  60182. return HemisphericParticleEmitter;
  60183. }());
  60184. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60185. })(BABYLON || (BABYLON = {}));
  60186. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60187. var BABYLON;
  60188. (function (BABYLON) {
  60189. /**
  60190. * Particle emitter emitting particles from a point.
  60191. * It emits the particles randomly between 2 given directions.
  60192. */
  60193. var PointParticleEmitter = /** @class */ (function () {
  60194. /**
  60195. * Creates a new instance PointParticleEmitter
  60196. */
  60197. function PointParticleEmitter() {
  60198. /**
  60199. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60200. */
  60201. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60202. /**
  60203. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60204. */
  60205. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60206. }
  60207. /**
  60208. * Called by the particle System when the direction is computed for the created particle.
  60209. * @param worldMatrix is the world matrix of the particle system
  60210. * @param directionToUpdate is the direction vector to update with the result
  60211. * @param particle is the particle we are computed the direction for
  60212. */
  60213. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60214. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60215. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60216. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60217. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60218. };
  60219. /**
  60220. * Called by the particle System when the position is computed for the created particle.
  60221. * @param worldMatrix is the world matrix of the particle system
  60222. * @param positionToUpdate is the position vector to update with the result
  60223. * @param particle is the particle we are computed the position for
  60224. */
  60225. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60227. };
  60228. /**
  60229. * Clones the current emitter and returns a copy of it
  60230. * @returns the new emitter
  60231. */
  60232. PointParticleEmitter.prototype.clone = function () {
  60233. var newOne = new PointParticleEmitter();
  60234. BABYLON.Tools.DeepCopy(this, newOne);
  60235. return newOne;
  60236. };
  60237. /**
  60238. * Called by the GPUParticleSystem to setup the update shader
  60239. * @param effect defines the update shader
  60240. */
  60241. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60242. effect.setVector3("direction1", this.direction1);
  60243. effect.setVector3("direction2", this.direction2);
  60244. };
  60245. /**
  60246. * Returns a string to use to update the GPU particles update shader
  60247. * @returns a string containng the defines string
  60248. */
  60249. PointParticleEmitter.prototype.getEffectDefines = function () {
  60250. return "#define POINTEMITTER";
  60251. };
  60252. /**
  60253. * Returns the string "PointParticleEmitter"
  60254. * @returns a string containing the class name
  60255. */
  60256. PointParticleEmitter.prototype.getClassName = function () {
  60257. return "PointParticleEmitter";
  60258. };
  60259. /**
  60260. * Serializes the particle system to a JSON object.
  60261. * @returns the JSON object
  60262. */
  60263. PointParticleEmitter.prototype.serialize = function () {
  60264. var serializationObject = {};
  60265. serializationObject.type = this.getClassName();
  60266. serializationObject.direction1 = this.direction1.asArray();
  60267. serializationObject.direction2 = this.direction2.asArray();
  60268. return serializationObject;
  60269. };
  60270. /**
  60271. * Parse properties from a JSON object
  60272. * @param serializationObject defines the JSON object
  60273. */
  60274. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60275. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60276. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60277. };
  60278. return PointParticleEmitter;
  60279. }());
  60280. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60281. })(BABYLON || (BABYLON = {}));
  60282. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60283. var BABYLON;
  60284. (function (BABYLON) {
  60285. // Adds the parsers to the scene parsers.
  60286. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60287. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60288. if (!individualParser) {
  60289. return;
  60290. }
  60291. // Particles Systems
  60292. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60293. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60294. var parsedParticleSystem = parsedData.particleSystems[index];
  60295. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60296. }
  60297. }
  60298. });
  60299. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60300. if (parsedParticleSystem.activeParticleCount) {
  60301. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60302. return ps;
  60303. }
  60304. else {
  60305. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60306. return ps;
  60307. }
  60308. });
  60309. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60310. if (uniformsNames === void 0) { uniformsNames = []; }
  60311. if (samplers === void 0) { samplers = []; }
  60312. if (defines === void 0) { defines = ""; }
  60313. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60314. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60315. if (defines.indexOf(" BILLBOARD") === -1) {
  60316. defines += "\n#define BILLBOARD\n";
  60317. }
  60318. if (samplers.indexOf("diffuseSampler") === -1) {
  60319. samplers.push("diffuseSampler");
  60320. }
  60321. return this.createEffect({
  60322. vertex: "particles",
  60323. fragmentElement: fragmentName
  60324. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60325. };
  60326. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60327. var results = new Array();
  60328. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60329. var particleSystem = this.getScene().particleSystems[index];
  60330. if (particleSystem.emitter === this) {
  60331. results.push(particleSystem);
  60332. }
  60333. }
  60334. return results;
  60335. };
  60336. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60337. var results = new Array();
  60338. var descendants = this.getDescendants();
  60339. descendants.push(this);
  60340. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60341. var particleSystem = this.getScene().particleSystems[index];
  60342. var emitter = particleSystem.emitter;
  60343. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60344. results.push(particleSystem);
  60345. }
  60346. }
  60347. return results;
  60348. };
  60349. })(BABYLON || (BABYLON = {}));
  60350. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60351. var BABYLON;
  60352. (function (BABYLON) {
  60353. /**
  60354. * Type of sub emitter
  60355. */
  60356. var SubEmitterType;
  60357. (function (SubEmitterType) {
  60358. /**
  60359. * Attached to the particle over it's lifetime
  60360. */
  60361. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60362. /**
  60363. * Created when the particle dies
  60364. */
  60365. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60366. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60367. /**
  60368. * Sub emitter class used to emit particles from an existing particle
  60369. */
  60370. var SubEmitter = /** @class */ (function () {
  60371. /**
  60372. * Creates a sub emitter
  60373. * @param particleSystem the particle system to be used by the sub emitter
  60374. */
  60375. function SubEmitter(
  60376. /**
  60377. * the particle system to be used by the sub emitter
  60378. */
  60379. particleSystem) {
  60380. this.particleSystem = particleSystem;
  60381. /**
  60382. * Type of the submitter (Default: END)
  60383. */
  60384. this.type = SubEmitterType.END;
  60385. /**
  60386. * 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)
  60387. * Note: This only is supported when using an emitter of type Mesh
  60388. */
  60389. this.inheritDirection = false;
  60390. /**
  60391. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60392. */
  60393. this.inheritedVelocityAmount = 0;
  60394. }
  60395. /**
  60396. * Clones the sub emitter
  60397. * @returns the cloned sub emitter
  60398. */
  60399. SubEmitter.prototype.clone = function () {
  60400. // Clone particle system
  60401. var emitter = this.particleSystem.emitter;
  60402. if (!emitter) {
  60403. emitter = new BABYLON.Vector3();
  60404. }
  60405. else if (emitter instanceof BABYLON.Vector3) {
  60406. emitter = emitter.clone();
  60407. }
  60408. else if (emitter instanceof BABYLON.AbstractMesh) {
  60409. emitter = new BABYLON.Mesh("", emitter.getScene());
  60410. emitter.isVisible = false;
  60411. }
  60412. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60413. // Clone properties
  60414. clone.type = this.type;
  60415. clone.inheritDirection = this.inheritDirection;
  60416. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60417. clone.particleSystem._disposeEmitterOnDispose = true;
  60418. clone.particleSystem.disposeOnStop = true;
  60419. return clone;
  60420. };
  60421. /**
  60422. * Serialize current object to a JSON object
  60423. * @returns the serialized object
  60424. */
  60425. SubEmitter.prototype.serialize = function () {
  60426. var serializationObject = {};
  60427. serializationObject.type = this.type;
  60428. serializationObject.inheritDirection = this.inheritDirection;
  60429. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60430. serializationObject.particleSystem = this.particleSystem.serialize();
  60431. return serializationObject;
  60432. };
  60433. /**
  60434. * Creates a new SubEmitter from a serialized JSON version
  60435. * @param serializationObject defines the JSON object to read from
  60436. * @param scene defines the hosting scene
  60437. * @param rootUrl defines the rootUrl for data loading
  60438. * @returns a new SubEmitter
  60439. */
  60440. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60441. var system = serializationObject.particleSystem;
  60442. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60443. subEmitter.type = serializationObject.type;
  60444. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60445. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60446. return subEmitter;
  60447. };
  60448. /** Release associated resources */
  60449. SubEmitter.prototype.dispose = function () {
  60450. this.particleSystem.dispose();
  60451. };
  60452. return SubEmitter;
  60453. }());
  60454. BABYLON.SubEmitter = SubEmitter;
  60455. })(BABYLON || (BABYLON = {}));
  60456. //# sourceMappingURL=babylon.subEmitter.js.map
  60457. var BABYLON;
  60458. (function (BABYLON) {
  60459. var ShaderMaterial = /** @class */ (function (_super) {
  60460. __extends(ShaderMaterial, _super);
  60461. function ShaderMaterial(name, scene, shaderPath, options) {
  60462. var _this = _super.call(this, name, scene) || this;
  60463. _this._textures = {};
  60464. _this._textureArrays = {};
  60465. _this._floats = {};
  60466. _this._ints = {};
  60467. _this._floatsArrays = {};
  60468. _this._colors3 = {};
  60469. _this._colors3Arrays = {};
  60470. _this._colors4 = {};
  60471. _this._vectors2 = {};
  60472. _this._vectors3 = {};
  60473. _this._vectors4 = {};
  60474. _this._matrices = {};
  60475. _this._matrices3x3 = {};
  60476. _this._matrices2x2 = {};
  60477. _this._vectors2Arrays = {};
  60478. _this._vectors3Arrays = {};
  60479. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60480. _this._shaderPath = shaderPath;
  60481. options.needAlphaBlending = options.needAlphaBlending || false;
  60482. options.needAlphaTesting = options.needAlphaTesting || false;
  60483. options.attributes = options.attributes || ["position", "normal", "uv"];
  60484. options.uniforms = options.uniforms || ["worldViewProjection"];
  60485. options.uniformBuffers = options.uniformBuffers || [];
  60486. options.samplers = options.samplers || [];
  60487. options.defines = options.defines || [];
  60488. _this._options = options;
  60489. return _this;
  60490. }
  60491. ShaderMaterial.prototype.getClassName = function () {
  60492. return "ShaderMaterial";
  60493. };
  60494. ShaderMaterial.prototype.needAlphaBlending = function () {
  60495. return this._options.needAlphaBlending;
  60496. };
  60497. ShaderMaterial.prototype.needAlphaTesting = function () {
  60498. return this._options.needAlphaTesting;
  60499. };
  60500. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60501. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60502. this._options.uniforms.push(uniformName);
  60503. }
  60504. };
  60505. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60506. if (this._options.samplers.indexOf(name) === -1) {
  60507. this._options.samplers.push(name);
  60508. }
  60509. this._textures[name] = texture;
  60510. return this;
  60511. };
  60512. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60513. if (this._options.samplers.indexOf(name) === -1) {
  60514. this._options.samplers.push(name);
  60515. }
  60516. this._checkUniform(name);
  60517. this._textureArrays[name] = textures;
  60518. return this;
  60519. };
  60520. ShaderMaterial.prototype.setFloat = function (name, value) {
  60521. this._checkUniform(name);
  60522. this._floats[name] = value;
  60523. return this;
  60524. };
  60525. ShaderMaterial.prototype.setInt = function (name, value) {
  60526. this._checkUniform(name);
  60527. this._ints[name] = value;
  60528. return this;
  60529. };
  60530. ShaderMaterial.prototype.setFloats = function (name, value) {
  60531. this._checkUniform(name);
  60532. this._floatsArrays[name] = value;
  60533. return this;
  60534. };
  60535. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60536. this._checkUniform(name);
  60537. this._colors3[name] = value;
  60538. return this;
  60539. };
  60540. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60541. this._checkUniform(name);
  60542. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60543. color.toArray(arr, arr.length);
  60544. return arr;
  60545. }, []);
  60546. return this;
  60547. };
  60548. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60549. this._checkUniform(name);
  60550. this._colors4[name] = value;
  60551. return this;
  60552. };
  60553. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60554. this._checkUniform(name);
  60555. this._vectors2[name] = value;
  60556. return this;
  60557. };
  60558. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60559. this._checkUniform(name);
  60560. this._vectors3[name] = value;
  60561. return this;
  60562. };
  60563. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60564. this._checkUniform(name);
  60565. this._vectors4[name] = value;
  60566. return this;
  60567. };
  60568. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60569. this._checkUniform(name);
  60570. this._matrices[name] = value;
  60571. return this;
  60572. };
  60573. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60574. this._checkUniform(name);
  60575. this._matrices3x3[name] = value;
  60576. return this;
  60577. };
  60578. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60579. this._checkUniform(name);
  60580. this._matrices2x2[name] = value;
  60581. return this;
  60582. };
  60583. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60584. this._checkUniform(name);
  60585. this._vectors2Arrays[name] = value;
  60586. return this;
  60587. };
  60588. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60589. this._checkUniform(name);
  60590. this._vectors3Arrays[name] = value;
  60591. return this;
  60592. };
  60593. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60594. if (!mesh) {
  60595. return true;
  60596. }
  60597. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60598. return false;
  60599. }
  60600. return false;
  60601. };
  60602. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60603. var scene = this.getScene();
  60604. var engine = scene.getEngine();
  60605. if (!this.checkReadyOnEveryCall) {
  60606. if (this._renderId === scene.getRenderId()) {
  60607. if (this._checkCache(scene, mesh, useInstances)) {
  60608. return true;
  60609. }
  60610. }
  60611. }
  60612. // Instances
  60613. var defines = [];
  60614. var attribs = [];
  60615. var fallbacks = new BABYLON.EffectFallbacks();
  60616. if (useInstances) {
  60617. defines.push("#define INSTANCES");
  60618. }
  60619. for (var index = 0; index < this._options.defines.length; index++) {
  60620. defines.push(this._options.defines[index]);
  60621. }
  60622. for (var index = 0; index < this._options.attributes.length; index++) {
  60623. attribs.push(this._options.attributes[index]);
  60624. }
  60625. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60626. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60627. defines.push("#define VERTEXCOLOR");
  60628. }
  60629. // Bones
  60630. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60631. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60632. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60633. if (mesh.numBoneInfluencers > 4) {
  60634. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60635. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60636. }
  60637. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60638. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60639. fallbacks.addCPUSkinningFallback(0, mesh);
  60640. if (this._options.uniforms.indexOf("mBones") === -1) {
  60641. this._options.uniforms.push("mBones");
  60642. }
  60643. }
  60644. else {
  60645. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60646. }
  60647. // Textures
  60648. for (var name in this._textures) {
  60649. if (!this._textures[name].isReady()) {
  60650. return false;
  60651. }
  60652. }
  60653. // Alpha test
  60654. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60655. defines.push("#define ALPHATEST");
  60656. }
  60657. var previousEffect = this._effect;
  60658. var join = defines.join("\n");
  60659. this._effect = engine.createEffect(this._shaderPath, {
  60660. attributes: attribs,
  60661. uniformsNames: this._options.uniforms,
  60662. uniformBuffersNames: this._options.uniformBuffers,
  60663. samplers: this._options.samplers,
  60664. defines: join,
  60665. fallbacks: fallbacks,
  60666. onCompiled: this.onCompiled,
  60667. onError: this.onError
  60668. }, engine);
  60669. if (!this._effect.isReady()) {
  60670. return false;
  60671. }
  60672. if (previousEffect !== this._effect) {
  60673. scene.resetCachedMaterial();
  60674. }
  60675. this._renderId = scene.getRenderId();
  60676. return true;
  60677. };
  60678. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60679. var scene = this.getScene();
  60680. if (!this._effect) {
  60681. return;
  60682. }
  60683. if (this._options.uniforms.indexOf("world") !== -1) {
  60684. this._effect.setMatrix("world", world);
  60685. }
  60686. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60687. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60688. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60689. }
  60690. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60691. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60692. }
  60693. };
  60694. ShaderMaterial.prototype.bind = function (world, mesh) {
  60695. // Std values
  60696. this.bindOnlyWorldMatrix(world);
  60697. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60698. if (this._options.uniforms.indexOf("view") !== -1) {
  60699. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60700. }
  60701. if (this._options.uniforms.indexOf("projection") !== -1) {
  60702. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60703. }
  60704. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60705. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60706. }
  60707. // Bones
  60708. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60709. var name;
  60710. // Texture
  60711. for (name in this._textures) {
  60712. this._effect.setTexture(name, this._textures[name]);
  60713. }
  60714. // Texture arrays
  60715. for (name in this._textureArrays) {
  60716. this._effect.setTextureArray(name, this._textureArrays[name]);
  60717. }
  60718. // Int
  60719. for (name in this._ints) {
  60720. this._effect.setInt(name, this._ints[name]);
  60721. }
  60722. // Float
  60723. for (name in this._floats) {
  60724. this._effect.setFloat(name, this._floats[name]);
  60725. }
  60726. // Floats
  60727. for (name in this._floatsArrays) {
  60728. this._effect.setArray(name, this._floatsArrays[name]);
  60729. }
  60730. // Color3
  60731. for (name in this._colors3) {
  60732. this._effect.setColor3(name, this._colors3[name]);
  60733. }
  60734. for (name in this._colors3Arrays) {
  60735. this._effect.setArray3(name, this._colors3Arrays[name]);
  60736. }
  60737. // Color4
  60738. for (name in this._colors4) {
  60739. var color = this._colors4[name];
  60740. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60741. }
  60742. // Vector2
  60743. for (name in this._vectors2) {
  60744. this._effect.setVector2(name, this._vectors2[name]);
  60745. }
  60746. // Vector3
  60747. for (name in this._vectors3) {
  60748. this._effect.setVector3(name, this._vectors3[name]);
  60749. }
  60750. // Vector4
  60751. for (name in this._vectors4) {
  60752. this._effect.setVector4(name, this._vectors4[name]);
  60753. }
  60754. // Matrix
  60755. for (name in this._matrices) {
  60756. this._effect.setMatrix(name, this._matrices[name]);
  60757. }
  60758. // Matrix 3x3
  60759. for (name in this._matrices3x3) {
  60760. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60761. }
  60762. // Matrix 2x2
  60763. for (name in this._matrices2x2) {
  60764. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60765. }
  60766. // Vector2Array
  60767. for (name in this._vectors2Arrays) {
  60768. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60769. }
  60770. // Vector3Array
  60771. for (name in this._vectors3Arrays) {
  60772. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60773. }
  60774. }
  60775. this._afterBind(mesh);
  60776. };
  60777. ShaderMaterial.prototype.getActiveTextures = function () {
  60778. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60779. for (var name in this._textures) {
  60780. activeTextures.push(this._textures[name]);
  60781. }
  60782. for (var name in this._textureArrays) {
  60783. var array = this._textureArrays[name];
  60784. for (var index = 0; index < array.length; index++) {
  60785. activeTextures.push(array[index]);
  60786. }
  60787. }
  60788. return activeTextures;
  60789. };
  60790. ShaderMaterial.prototype.hasTexture = function (texture) {
  60791. if (_super.prototype.hasTexture.call(this, texture)) {
  60792. return true;
  60793. }
  60794. for (var name in this._textures) {
  60795. if (this._textures[name] === texture) {
  60796. return true;
  60797. }
  60798. }
  60799. for (var name in this._textureArrays) {
  60800. var array = this._textureArrays[name];
  60801. for (var index = 0; index < array.length; index++) {
  60802. if (array[index] === texture) {
  60803. return true;
  60804. }
  60805. }
  60806. }
  60807. return false;
  60808. };
  60809. ShaderMaterial.prototype.clone = function (name) {
  60810. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60811. return newShaderMaterial;
  60812. };
  60813. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60814. if (forceDisposeTextures) {
  60815. var name;
  60816. for (name in this._textures) {
  60817. this._textures[name].dispose();
  60818. }
  60819. for (name in this._textureArrays) {
  60820. var array = this._textureArrays[name];
  60821. for (var index = 0; index < array.length; index++) {
  60822. array[index].dispose();
  60823. }
  60824. }
  60825. }
  60826. this._textures = {};
  60827. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60828. };
  60829. ShaderMaterial.prototype.serialize = function () {
  60830. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60831. serializationObject.customType = "BABYLON.ShaderMaterial";
  60832. serializationObject.options = this._options;
  60833. serializationObject.shaderPath = this._shaderPath;
  60834. var name;
  60835. // Texture
  60836. serializationObject.textures = {};
  60837. for (name in this._textures) {
  60838. serializationObject.textures[name] = this._textures[name].serialize();
  60839. }
  60840. // Texture arrays
  60841. serializationObject.textureArrays = {};
  60842. for (name in this._textureArrays) {
  60843. serializationObject.textureArrays[name] = [];
  60844. var array = this._textureArrays[name];
  60845. for (var index = 0; index < array.length; index++) {
  60846. serializationObject.textureArrays[name].push(array[index].serialize());
  60847. }
  60848. }
  60849. // Float
  60850. serializationObject.floats = {};
  60851. for (name in this._floats) {
  60852. serializationObject.floats[name] = this._floats[name];
  60853. }
  60854. // Float s
  60855. serializationObject.FloatArrays = {};
  60856. for (name in this._floatsArrays) {
  60857. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60858. }
  60859. // Color3
  60860. serializationObject.colors3 = {};
  60861. for (name in this._colors3) {
  60862. serializationObject.colors3[name] = this._colors3[name].asArray();
  60863. }
  60864. // Color3 array
  60865. serializationObject.colors3Arrays = {};
  60866. for (name in this._colors3Arrays) {
  60867. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60868. }
  60869. // Color4
  60870. serializationObject.colors4 = {};
  60871. for (name in this._colors4) {
  60872. serializationObject.colors4[name] = this._colors4[name].asArray();
  60873. }
  60874. // Vector2
  60875. serializationObject.vectors2 = {};
  60876. for (name in this._vectors2) {
  60877. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60878. }
  60879. // Vector3
  60880. serializationObject.vectors3 = {};
  60881. for (name in this._vectors3) {
  60882. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60883. }
  60884. // Vector4
  60885. serializationObject.vectors4 = {};
  60886. for (name in this._vectors4) {
  60887. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60888. }
  60889. // Matrix
  60890. serializationObject.matrices = {};
  60891. for (name in this._matrices) {
  60892. serializationObject.matrices[name] = this._matrices[name].asArray();
  60893. }
  60894. // Matrix 3x3
  60895. serializationObject.matrices3x3 = {};
  60896. for (name in this._matrices3x3) {
  60897. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60898. }
  60899. // Matrix 2x2
  60900. serializationObject.matrices2x2 = {};
  60901. for (name in this._matrices2x2) {
  60902. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60903. }
  60904. // Vector2Array
  60905. serializationObject.vectors2Arrays = {};
  60906. for (name in this._vectors2Arrays) {
  60907. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60908. }
  60909. // Vector3Array
  60910. serializationObject.vectors3Arrays = {};
  60911. for (name in this._vectors3Arrays) {
  60912. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60913. }
  60914. return serializationObject;
  60915. };
  60916. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60917. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60918. var name;
  60919. // Texture
  60920. for (name in source.textures) {
  60921. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60922. }
  60923. // Texture arrays
  60924. for (name in source.textureArrays) {
  60925. var array = source.textureArrays[name];
  60926. var textureArray = new Array();
  60927. for (var index = 0; index < array.length; index++) {
  60928. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60929. }
  60930. material.setTextureArray(name, textureArray);
  60931. }
  60932. // Float
  60933. for (name in source.floats) {
  60934. material.setFloat(name, source.floats[name]);
  60935. }
  60936. // Float s
  60937. for (name in source.floatsArrays) {
  60938. material.setFloats(name, source.floatsArrays[name]);
  60939. }
  60940. // Color3
  60941. for (name in source.colors3) {
  60942. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60943. }
  60944. // Color3 arrays
  60945. for (name in source.colors3Arrays) {
  60946. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60947. if (i % 3 === 0) {
  60948. arr.push([num]);
  60949. }
  60950. else {
  60951. arr[arr.length - 1].push(num);
  60952. }
  60953. return arr;
  60954. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60955. material.setColor3Array(name, colors);
  60956. }
  60957. // Color4
  60958. for (name in source.colors4) {
  60959. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60960. }
  60961. // Vector2
  60962. for (name in source.vectors2) {
  60963. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60964. }
  60965. // Vector3
  60966. for (name in source.vectors3) {
  60967. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60968. }
  60969. // Vector4
  60970. for (name in source.vectors4) {
  60971. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60972. }
  60973. // Matrix
  60974. for (name in source.matrices) {
  60975. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60976. }
  60977. // Matrix 3x3
  60978. for (name in source.matrices3x3) {
  60979. material.setMatrix3x3(name, source.matrices3x3[name]);
  60980. }
  60981. // Matrix 2x2
  60982. for (name in source.matrices2x2) {
  60983. material.setMatrix2x2(name, source.matrices2x2[name]);
  60984. }
  60985. // Vector2Array
  60986. for (name in source.vectors2Arrays) {
  60987. material.setArray2(name, source.vectors2Arrays[name]);
  60988. }
  60989. // Vector3Array
  60990. for (name in source.vectors3Arrays) {
  60991. material.setArray3(name, source.vectors3Arrays[name]);
  60992. }
  60993. return material;
  60994. };
  60995. return ShaderMaterial;
  60996. }(BABYLON.Material));
  60997. BABYLON.ShaderMaterial = ShaderMaterial;
  60998. })(BABYLON || (BABYLON = {}));
  60999. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61000. var BABYLON;
  61001. (function (BABYLON) {
  61002. var GroundMesh = /** @class */ (function (_super) {
  61003. __extends(GroundMesh, _super);
  61004. function GroundMesh(name, scene) {
  61005. var _this = _super.call(this, name, scene) || this;
  61006. _this.generateOctree = false;
  61007. return _this;
  61008. }
  61009. GroundMesh.prototype.getClassName = function () {
  61010. return "GroundMesh";
  61011. };
  61012. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61013. get: function () {
  61014. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61015. },
  61016. enumerable: true,
  61017. configurable: true
  61018. });
  61019. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61020. get: function () {
  61021. return this._subdivisionsX;
  61022. },
  61023. enumerable: true,
  61024. configurable: true
  61025. });
  61026. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61027. get: function () {
  61028. return this._subdivisionsY;
  61029. },
  61030. enumerable: true,
  61031. configurable: true
  61032. });
  61033. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61034. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61035. this._subdivisionsX = chunksCount;
  61036. this._subdivisionsY = chunksCount;
  61037. this.subdivide(chunksCount);
  61038. // Call the octree system optimization if it is defined.
  61039. var thisAsAny = this;
  61040. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61041. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61042. }
  61043. };
  61044. /**
  61045. * Returns a height (y) value in the Worl system :
  61046. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61047. * Returns the ground y position if (x, z) are outside the ground surface.
  61048. */
  61049. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61050. var world = this.getWorldMatrix();
  61051. var invMat = BABYLON.Tmp.Matrix[5];
  61052. world.invertToRef(invMat);
  61053. var tmpVect = BABYLON.Tmp.Vector3[8];
  61054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61055. x = tmpVect.x;
  61056. z = tmpVect.z;
  61057. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61058. return this.position.y;
  61059. }
  61060. if (!this._heightQuads || this._heightQuads.length == 0) {
  61061. this._initHeightQuads();
  61062. this._computeHeightQuads();
  61063. }
  61064. var facet = this._getFacetAt(x, z);
  61065. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61066. // return y in the World system
  61067. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61068. return tmpVect.y;
  61069. };
  61070. /**
  61071. * Returns a normalized vector (Vector3) orthogonal to the ground
  61072. * at the ground coordinates (x, z) expressed in the World system.
  61073. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61074. */
  61075. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61076. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61077. this.getNormalAtCoordinatesToRef(x, z, normal);
  61078. return normal;
  61079. };
  61080. /**
  61081. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61082. * at the ground coordinates (x, z) expressed in the World system.
  61083. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61084. * Returns the GroundMesh.
  61085. */
  61086. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61087. var world = this.getWorldMatrix();
  61088. var tmpMat = BABYLON.Tmp.Matrix[5];
  61089. world.invertToRef(tmpMat);
  61090. var tmpVect = BABYLON.Tmp.Vector3[8];
  61091. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61092. x = tmpVect.x;
  61093. z = tmpVect.z;
  61094. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61095. return this;
  61096. }
  61097. if (!this._heightQuads || this._heightQuads.length == 0) {
  61098. this._initHeightQuads();
  61099. this._computeHeightQuads();
  61100. }
  61101. var facet = this._getFacetAt(x, z);
  61102. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61103. return this;
  61104. };
  61105. /**
  61106. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61107. * if the ground has been updated.
  61108. * This can be used in the render loop.
  61109. * Returns the GroundMesh.
  61110. */
  61111. GroundMesh.prototype.updateCoordinateHeights = function () {
  61112. if (!this._heightQuads || this._heightQuads.length == 0) {
  61113. this._initHeightQuads();
  61114. }
  61115. this._computeHeightQuads();
  61116. return this;
  61117. };
  61118. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61119. GroundMesh.prototype._getFacetAt = function (x, z) {
  61120. // retrieve col and row from x, z coordinates in the ground local system
  61121. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61122. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61123. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61124. var facet;
  61125. if (z < quad.slope.x * x + quad.slope.y) {
  61126. facet = quad.facet1;
  61127. }
  61128. else {
  61129. facet = quad.facet2;
  61130. }
  61131. return facet;
  61132. };
  61133. // Creates and populates the heightMap array with "facet" elements :
  61134. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61135. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61136. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61137. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61138. // Returns the GroundMesh.
  61139. GroundMesh.prototype._initHeightQuads = function () {
  61140. var subdivisionsX = this._subdivisionsX;
  61141. var subdivisionsY = this._subdivisionsY;
  61142. this._heightQuads = new Array();
  61143. for (var row = 0; row < subdivisionsY; row++) {
  61144. for (var col = 0; col < subdivisionsX; col++) {
  61145. 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) };
  61146. this._heightQuads[row * subdivisionsX + col] = quad;
  61147. }
  61148. }
  61149. return this;
  61150. };
  61151. // Compute each quad element values and update the the heightMap array :
  61152. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61153. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61154. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61155. // Returns the GroundMesh.
  61156. GroundMesh.prototype._computeHeightQuads = function () {
  61157. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61158. if (!positions) {
  61159. return this;
  61160. }
  61161. var v1 = BABYLON.Tmp.Vector3[3];
  61162. var v2 = BABYLON.Tmp.Vector3[2];
  61163. var v3 = BABYLON.Tmp.Vector3[1];
  61164. var v4 = BABYLON.Tmp.Vector3[0];
  61165. var v1v2 = BABYLON.Tmp.Vector3[4];
  61166. var v1v3 = BABYLON.Tmp.Vector3[5];
  61167. var v1v4 = BABYLON.Tmp.Vector3[6];
  61168. var norm1 = BABYLON.Tmp.Vector3[7];
  61169. var norm2 = BABYLON.Tmp.Vector3[8];
  61170. var i = 0;
  61171. var j = 0;
  61172. var k = 0;
  61173. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61174. var h = 0;
  61175. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61176. var d2 = 0;
  61177. var subdivisionsX = this._subdivisionsX;
  61178. var subdivisionsY = this._subdivisionsY;
  61179. for (var row = 0; row < subdivisionsY; row++) {
  61180. for (var col = 0; col < subdivisionsX; col++) {
  61181. i = col * 3;
  61182. j = row * (subdivisionsX + 1) * 3;
  61183. k = (row + 1) * (subdivisionsX + 1) * 3;
  61184. v1.x = positions[j + i];
  61185. v1.y = positions[j + i + 1];
  61186. v1.z = positions[j + i + 2];
  61187. v2.x = positions[j + i + 3];
  61188. v2.y = positions[j + i + 4];
  61189. v2.z = positions[j + i + 5];
  61190. v3.x = positions[k + i];
  61191. v3.y = positions[k + i + 1];
  61192. v3.z = positions[k + i + 2];
  61193. v4.x = positions[k + i + 3];
  61194. v4.y = positions[k + i + 4];
  61195. v4.z = positions[k + i + 5];
  61196. // 2D slope V1V4
  61197. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61198. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61199. // facet equations :
  61200. // we compute each facet normal vector
  61201. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61202. // we compute the value d by applying the equation to v1 which belongs to the plane
  61203. // then we store the facet equation in a Vector4
  61204. v2.subtractToRef(v1, v1v2);
  61205. v3.subtractToRef(v1, v1v3);
  61206. v4.subtractToRef(v1, v1v4);
  61207. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61208. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61209. norm1.normalize();
  61210. norm2.normalize();
  61211. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61212. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61213. var quad = this._heightQuads[row * subdivisionsX + col];
  61214. quad.slope.copyFromFloats(cd, h);
  61215. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61216. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61217. }
  61218. }
  61219. return this;
  61220. };
  61221. GroundMesh.prototype.serialize = function (serializationObject) {
  61222. _super.prototype.serialize.call(this, serializationObject);
  61223. serializationObject.subdivisionsX = this._subdivisionsX;
  61224. serializationObject.subdivisionsY = this._subdivisionsY;
  61225. serializationObject.minX = this._minX;
  61226. serializationObject.maxX = this._maxX;
  61227. serializationObject.minZ = this._minZ;
  61228. serializationObject.maxZ = this._maxZ;
  61229. serializationObject.width = this._width;
  61230. serializationObject.height = this._height;
  61231. };
  61232. GroundMesh.Parse = function (parsedMesh, scene) {
  61233. var result = new GroundMesh(parsedMesh.name, scene);
  61234. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61235. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61236. result._minX = parsedMesh.minX;
  61237. result._maxX = parsedMesh.maxX;
  61238. result._minZ = parsedMesh.minZ;
  61239. result._maxZ = parsedMesh.maxZ;
  61240. result._width = parsedMesh.width;
  61241. result._height = parsedMesh.height;
  61242. return result;
  61243. };
  61244. return GroundMesh;
  61245. }(BABYLON.Mesh));
  61246. BABYLON.GroundMesh = GroundMesh;
  61247. })(BABYLON || (BABYLON = {}));
  61248. //# sourceMappingURL=babylon.groundMesh.js.map
  61249. var BABYLON;
  61250. (function (BABYLON) {
  61251. /**
  61252. * Creates an instance based on a source mesh.
  61253. */
  61254. var InstancedMesh = /** @class */ (function (_super) {
  61255. __extends(InstancedMesh, _super);
  61256. function InstancedMesh(name, source) {
  61257. var _this = _super.call(this, name, source.getScene()) || this;
  61258. source.instances.push(_this);
  61259. _this._sourceMesh = source;
  61260. _this.position.copyFrom(source.position);
  61261. _this.rotation.copyFrom(source.rotation);
  61262. _this.scaling.copyFrom(source.scaling);
  61263. if (source.rotationQuaternion) {
  61264. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61265. }
  61266. _this.infiniteDistance = source.infiniteDistance;
  61267. _this.setPivotMatrix(source.getPivotMatrix());
  61268. _this.refreshBoundingInfo();
  61269. _this._syncSubMeshes();
  61270. return _this;
  61271. }
  61272. /**
  61273. * Returns the string "InstancedMesh".
  61274. */
  61275. InstancedMesh.prototype.getClassName = function () {
  61276. return "InstancedMesh";
  61277. };
  61278. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61279. // Methods
  61280. get: function () {
  61281. return this._sourceMesh.receiveShadows;
  61282. },
  61283. enumerable: true,
  61284. configurable: true
  61285. });
  61286. Object.defineProperty(InstancedMesh.prototype, "material", {
  61287. get: function () {
  61288. return this._sourceMesh.material;
  61289. },
  61290. enumerable: true,
  61291. configurable: true
  61292. });
  61293. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61294. get: function () {
  61295. return this._sourceMesh.visibility;
  61296. },
  61297. enumerable: true,
  61298. configurable: true
  61299. });
  61300. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61301. get: function () {
  61302. return this._sourceMesh.skeleton;
  61303. },
  61304. enumerable: true,
  61305. configurable: true
  61306. });
  61307. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61308. get: function () {
  61309. return this._sourceMesh.renderingGroupId;
  61310. },
  61311. set: function (value) {
  61312. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61313. return;
  61314. }
  61315. //no-op with warning
  61316. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61317. },
  61318. enumerable: true,
  61319. configurable: true
  61320. });
  61321. /**
  61322. * Returns the total number of vertices (integer).
  61323. */
  61324. InstancedMesh.prototype.getTotalVertices = function () {
  61325. return this._sourceMesh.getTotalVertices();
  61326. };
  61327. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61328. get: function () {
  61329. return this._sourceMesh;
  61330. },
  61331. enumerable: true,
  61332. configurable: true
  61333. });
  61334. /**
  61335. * Is this node ready to be used/rendered
  61336. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61337. * @return {boolean} is it ready
  61338. */
  61339. InstancedMesh.prototype.isReady = function (completeCheck) {
  61340. if (completeCheck === void 0) { completeCheck = false; }
  61341. return this._sourceMesh.isReady(completeCheck, true);
  61342. };
  61343. /**
  61344. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61345. */
  61346. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61347. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61348. };
  61349. /**
  61350. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61351. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61352. * The `data` are either a numeric array either a Float32Array.
  61353. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61354. * 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).
  61355. * Note that a new underlying VertexBuffer object is created each call.
  61356. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61357. *
  61358. * Possible `kind` values :
  61359. * - BABYLON.VertexBuffer.PositionKind
  61360. * - BABYLON.VertexBuffer.UVKind
  61361. * - BABYLON.VertexBuffer.UV2Kind
  61362. * - BABYLON.VertexBuffer.UV3Kind
  61363. * - BABYLON.VertexBuffer.UV4Kind
  61364. * - BABYLON.VertexBuffer.UV5Kind
  61365. * - BABYLON.VertexBuffer.UV6Kind
  61366. * - BABYLON.VertexBuffer.ColorKind
  61367. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61368. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61369. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61370. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61371. *
  61372. * Returns the Mesh.
  61373. */
  61374. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61375. if (this.sourceMesh) {
  61376. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61377. }
  61378. return this.sourceMesh;
  61379. };
  61380. /**
  61381. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61382. * If the mesh has no geometry, it is simply returned as it is.
  61383. * The `data` are either a numeric array either a Float32Array.
  61384. * No new underlying VertexBuffer object is created.
  61385. * 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.
  61386. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61387. *
  61388. * Possible `kind` values :
  61389. * - BABYLON.VertexBuffer.PositionKind
  61390. * - BABYLON.VertexBuffer.UVKind
  61391. * - BABYLON.VertexBuffer.UV2Kind
  61392. * - BABYLON.VertexBuffer.UV3Kind
  61393. * - BABYLON.VertexBuffer.UV4Kind
  61394. * - BABYLON.VertexBuffer.UV5Kind
  61395. * - BABYLON.VertexBuffer.UV6Kind
  61396. * - BABYLON.VertexBuffer.ColorKind
  61397. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61398. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61399. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61400. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61401. *
  61402. * Returns the Mesh.
  61403. */
  61404. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61405. if (this.sourceMesh) {
  61406. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61407. }
  61408. return this.sourceMesh;
  61409. };
  61410. /**
  61411. * Sets the mesh indices.
  61412. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61413. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61414. * This method creates a new index buffer each call.
  61415. * Returns the Mesh.
  61416. */
  61417. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61418. if (totalVertices === void 0) { totalVertices = null; }
  61419. if (this.sourceMesh) {
  61420. this.sourceMesh.setIndices(indices, totalVertices);
  61421. }
  61422. return this.sourceMesh;
  61423. };
  61424. /**
  61425. * Boolean : True if the mesh owns the requested kind of data.
  61426. */
  61427. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61428. return this._sourceMesh.isVerticesDataPresent(kind);
  61429. };
  61430. /**
  61431. * Returns an array of indices (IndicesArray).
  61432. */
  61433. InstancedMesh.prototype.getIndices = function () {
  61434. return this._sourceMesh.getIndices();
  61435. };
  61436. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61437. get: function () {
  61438. return this._sourceMesh._positions;
  61439. },
  61440. enumerable: true,
  61441. configurable: true
  61442. });
  61443. /**
  61444. * Sets a new updated BoundingInfo to the mesh.
  61445. * Returns the mesh.
  61446. */
  61447. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61448. var meshBB = this._sourceMesh.getBoundingInfo();
  61449. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61450. this._updateBoundingInfo();
  61451. return this;
  61452. };
  61453. /** @hidden */
  61454. InstancedMesh.prototype._preActivate = function () {
  61455. if (this._currentLOD) {
  61456. this._currentLOD._preActivate();
  61457. }
  61458. return this;
  61459. };
  61460. /** @hidden */
  61461. InstancedMesh.prototype._activate = function (renderId) {
  61462. if (this._currentLOD) {
  61463. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61464. }
  61465. return this;
  61466. };
  61467. /**
  61468. * Returns the current associated LOD AbstractMesh.
  61469. */
  61470. InstancedMesh.prototype.getLOD = function (camera) {
  61471. if (!camera) {
  61472. return this;
  61473. }
  61474. var boundingInfo = this.getBoundingInfo();
  61475. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61476. if (this._currentLOD === this.sourceMesh) {
  61477. return this;
  61478. }
  61479. return this._currentLOD;
  61480. };
  61481. /** @hidden */
  61482. InstancedMesh.prototype._syncSubMeshes = function () {
  61483. this.releaseSubMeshes();
  61484. if (this._sourceMesh.subMeshes) {
  61485. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61486. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61487. }
  61488. }
  61489. return this;
  61490. };
  61491. /** @hidden */
  61492. InstancedMesh.prototype._generatePointsArray = function () {
  61493. return this._sourceMesh._generatePointsArray();
  61494. };
  61495. /**
  61496. * Creates a new InstancedMesh from the current mesh.
  61497. * - name (string) : the cloned mesh name
  61498. * - newParent (optional Node) : the optional Node to parent the clone to.
  61499. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61500. *
  61501. * Returns the clone.
  61502. */
  61503. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61504. var result = this._sourceMesh.createInstance(name);
  61505. // Deep copy
  61506. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61507. // Bounding info
  61508. this.refreshBoundingInfo();
  61509. // Parent
  61510. if (newParent) {
  61511. result.parent = newParent;
  61512. }
  61513. if (!doNotCloneChildren) {
  61514. // Children
  61515. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61516. var mesh = this.getScene().meshes[index];
  61517. if (mesh.parent === this) {
  61518. mesh.clone(mesh.name, result);
  61519. }
  61520. }
  61521. }
  61522. result.computeWorldMatrix(true);
  61523. return result;
  61524. };
  61525. /**
  61526. * Disposes the InstancedMesh.
  61527. * Returns nothing.
  61528. */
  61529. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61530. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61531. // Remove from mesh
  61532. var index = this._sourceMesh.instances.indexOf(this);
  61533. this._sourceMesh.instances.splice(index, 1);
  61534. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61535. };
  61536. return InstancedMesh;
  61537. }(BABYLON.AbstractMesh));
  61538. BABYLON.InstancedMesh = InstancedMesh;
  61539. })(BABYLON || (BABYLON = {}));
  61540. //# sourceMappingURL=babylon.instancedMesh.js.map
  61541. var BABYLON;
  61542. (function (BABYLON) {
  61543. var LinesMesh = /** @class */ (function (_super) {
  61544. __extends(LinesMesh, _super);
  61545. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61546. if (scene === void 0) { scene = null; }
  61547. if (parent === void 0) { parent = null; }
  61548. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61549. _this.useVertexColor = useVertexColor;
  61550. _this.useVertexAlpha = useVertexAlpha;
  61551. _this.color = new BABYLON.Color3(1, 1, 1);
  61552. _this.alpha = 1;
  61553. if (source) {
  61554. _this.color = source.color.clone();
  61555. _this.alpha = source.alpha;
  61556. _this.useVertexColor = source.useVertexColor;
  61557. _this.useVertexAlpha = source.useVertexAlpha;
  61558. }
  61559. _this._intersectionThreshold = 0.1;
  61560. var defines = [];
  61561. var options = {
  61562. attributes: [BABYLON.VertexBuffer.PositionKind],
  61563. uniforms: ["world", "viewProjection"],
  61564. needAlphaBlending: true,
  61565. defines: defines
  61566. };
  61567. if (useVertexAlpha === false) {
  61568. options.needAlphaBlending = false;
  61569. }
  61570. if (!useVertexColor) {
  61571. options.uniforms.push("color");
  61572. }
  61573. else {
  61574. options.defines.push("#define VERTEXCOLOR");
  61575. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61576. }
  61577. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61578. return _this;
  61579. }
  61580. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61581. /**
  61582. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61583. * This margin is expressed in world space coordinates, so its value may vary.
  61584. * Default value is 0.1
  61585. * @returns the intersection Threshold value.
  61586. */
  61587. get: function () {
  61588. return this._intersectionThreshold;
  61589. },
  61590. /**
  61591. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61592. * This margin is expressed in world space coordinates, so its value may vary.
  61593. * @param value the new threshold to apply
  61594. */
  61595. set: function (value) {
  61596. if (this._intersectionThreshold === value) {
  61597. return;
  61598. }
  61599. this._intersectionThreshold = value;
  61600. if (this.geometry) {
  61601. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61602. }
  61603. },
  61604. enumerable: true,
  61605. configurable: true
  61606. });
  61607. /**
  61608. * Returns the string "LineMesh"
  61609. */
  61610. LinesMesh.prototype.getClassName = function () {
  61611. return "LinesMesh";
  61612. };
  61613. Object.defineProperty(LinesMesh.prototype, "material", {
  61614. /**
  61615. * @hidden
  61616. */
  61617. get: function () {
  61618. return this._colorShader;
  61619. },
  61620. /**
  61621. * @hidden
  61622. */
  61623. set: function (value) {
  61624. // Do nothing
  61625. },
  61626. enumerable: true,
  61627. configurable: true
  61628. });
  61629. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61630. /**
  61631. * @hidden
  61632. */
  61633. get: function () {
  61634. return false;
  61635. },
  61636. enumerable: true,
  61637. configurable: true
  61638. });
  61639. LinesMesh.prototype.createInstance = function (name) {
  61640. throw new Error("LinesMeshes do not support createInstance.");
  61641. };
  61642. /** @hidden */
  61643. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61644. if (!this._geometry) {
  61645. return this;
  61646. }
  61647. // VBOs
  61648. this._geometry._bind(this._colorShader.getEffect());
  61649. // Color
  61650. if (!this.useVertexColor) {
  61651. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61652. }
  61653. return this;
  61654. };
  61655. /** @hidden */
  61656. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61657. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61658. return this;
  61659. }
  61660. var engine = this.getScene().getEngine();
  61661. // Draw order
  61662. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61663. return this;
  61664. };
  61665. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61666. this._colorShader.dispose();
  61667. _super.prototype.dispose.call(this, doNotRecurse);
  61668. };
  61669. /**
  61670. * Returns a new LineMesh object cloned from the current one.
  61671. */
  61672. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61673. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61674. };
  61675. return LinesMesh;
  61676. }(BABYLON.Mesh));
  61677. BABYLON.LinesMesh = LinesMesh;
  61678. })(BABYLON || (BABYLON = {}));
  61679. //# sourceMappingURL=babylon.linesMesh.js.map
  61680. var BABYLON;
  61681. (function (BABYLON) {
  61682. /**
  61683. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61684. * The underlying implementation relies on an associative array to ensure the best performances.
  61685. * The value can be anything including 'null' but except 'undefined'
  61686. */
  61687. var StringDictionary = /** @class */ (function () {
  61688. function StringDictionary() {
  61689. this._count = 0;
  61690. this._data = {};
  61691. }
  61692. /**
  61693. * This will clear this dictionary and copy the content from the 'source' one.
  61694. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61695. * @param source the dictionary to take the content from and copy to this dictionary
  61696. */
  61697. StringDictionary.prototype.copyFrom = function (source) {
  61698. var _this = this;
  61699. this.clear();
  61700. source.forEach(function (t, v) { return _this.add(t, v); });
  61701. };
  61702. /**
  61703. * Get a value based from its key
  61704. * @param key the given key to get the matching value from
  61705. * @return the value if found, otherwise undefined is returned
  61706. */
  61707. StringDictionary.prototype.get = function (key) {
  61708. var val = this._data[key];
  61709. if (val !== undefined) {
  61710. return val;
  61711. }
  61712. return undefined;
  61713. };
  61714. /**
  61715. * Get a value from its key or add it if it doesn't exist.
  61716. * This method will ensure you that a given key/data will be present in the dictionary.
  61717. * @param key the given key to get the matching value from
  61718. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61719. * The factory will only be invoked if there's no data for the given key.
  61720. * @return the value corresponding to the key.
  61721. */
  61722. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61723. var val = this.get(key);
  61724. if (val !== undefined) {
  61725. return val;
  61726. }
  61727. val = factory(key);
  61728. if (val) {
  61729. this.add(key, val);
  61730. }
  61731. return val;
  61732. };
  61733. /**
  61734. * Get a value from its key if present in the dictionary otherwise add it
  61735. * @param key the key to get the value from
  61736. * @param val if there's no such key/value pair in the dictionary add it with this value
  61737. * @return the value corresponding to the key
  61738. */
  61739. StringDictionary.prototype.getOrAdd = function (key, val) {
  61740. var curVal = this.get(key);
  61741. if (curVal !== undefined) {
  61742. return curVal;
  61743. }
  61744. this.add(key, val);
  61745. return val;
  61746. };
  61747. /**
  61748. * Check if there's a given key in the dictionary
  61749. * @param key the key to check for
  61750. * @return true if the key is present, false otherwise
  61751. */
  61752. StringDictionary.prototype.contains = function (key) {
  61753. return this._data[key] !== undefined;
  61754. };
  61755. /**
  61756. * Add a new key and its corresponding value
  61757. * @param key the key to add
  61758. * @param value the value corresponding to the key
  61759. * @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
  61760. */
  61761. StringDictionary.prototype.add = function (key, value) {
  61762. if (this._data[key] !== undefined) {
  61763. return false;
  61764. }
  61765. this._data[key] = value;
  61766. ++this._count;
  61767. return true;
  61768. };
  61769. StringDictionary.prototype.set = function (key, value) {
  61770. if (this._data[key] === undefined) {
  61771. return false;
  61772. }
  61773. this._data[key] = value;
  61774. return true;
  61775. };
  61776. /**
  61777. * Get the element of the given key and remove it from the dictionary
  61778. * @param key
  61779. */
  61780. StringDictionary.prototype.getAndRemove = function (key) {
  61781. var val = this.get(key);
  61782. if (val !== undefined) {
  61783. delete this._data[key];
  61784. --this._count;
  61785. return val;
  61786. }
  61787. return null;
  61788. };
  61789. /**
  61790. * Remove a key/value from the dictionary.
  61791. * @param key the key to remove
  61792. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61793. */
  61794. StringDictionary.prototype.remove = function (key) {
  61795. if (this.contains(key)) {
  61796. delete this._data[key];
  61797. --this._count;
  61798. return true;
  61799. }
  61800. return false;
  61801. };
  61802. /**
  61803. * Clear the whole content of the dictionary
  61804. */
  61805. StringDictionary.prototype.clear = function () {
  61806. this._data = {};
  61807. this._count = 0;
  61808. };
  61809. Object.defineProperty(StringDictionary.prototype, "count", {
  61810. get: function () {
  61811. return this._count;
  61812. },
  61813. enumerable: true,
  61814. configurable: true
  61815. });
  61816. /**
  61817. * Execute a callback on each key/val of the dictionary.
  61818. * Note that you can remove any element in this dictionary in the callback implementation
  61819. * @param callback the callback to execute on a given key/value pair
  61820. */
  61821. StringDictionary.prototype.forEach = function (callback) {
  61822. for (var cur in this._data) {
  61823. var val = this._data[cur];
  61824. callback(cur, val);
  61825. }
  61826. };
  61827. /**
  61828. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61829. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61830. * Note that you can remove any element in this dictionary in the callback implementation
  61831. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61832. */
  61833. StringDictionary.prototype.first = function (callback) {
  61834. for (var cur in this._data) {
  61835. var val = this._data[cur];
  61836. var res = callback(cur, val);
  61837. if (res) {
  61838. return res;
  61839. }
  61840. }
  61841. return null;
  61842. };
  61843. return StringDictionary;
  61844. }());
  61845. BABYLON.StringDictionary = StringDictionary;
  61846. })(BABYLON || (BABYLON = {}));
  61847. //# sourceMappingURL=babylon.stringDictionary.js.map
  61848. var BABYLON;
  61849. (function (BABYLON) {
  61850. var Debug;
  61851. (function (Debug) {
  61852. /**
  61853. * Class used to render a debug view of a given skeleton
  61854. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  61855. */
  61856. var SkeletonViewer = /** @class */ (function () {
  61857. /**
  61858. * Creates a new SkeletonViewer
  61859. * @param skeleton defines the skeleton to render
  61860. * @param mesh defines the mesh attached to the skeleton
  61861. * @param scene defines the hosting scene
  61862. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  61863. * @param renderingGroupId defines the rendering group id to use with the viewer
  61864. */
  61865. function SkeletonViewer(
  61866. /** defines the skeleton to render */
  61867. skeleton,
  61868. /** defines the mesh attached to the skeleton */
  61869. mesh, scene,
  61870. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  61871. autoUpdateBonesMatrices,
  61872. /** defines the rendering group id to use with the viewer */
  61873. renderingGroupId) {
  61874. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61875. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61876. this.skeleton = skeleton;
  61877. this.mesh = mesh;
  61878. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61879. this.renderingGroupId = renderingGroupId;
  61880. /** Gets or sets the color used to render the skeleton */
  61881. this.color = BABYLON.Color3.White();
  61882. this._debugLines = new Array();
  61883. this._isEnabled = false;
  61884. this._scene = scene;
  61885. this.update();
  61886. this._renderFunction = this.update.bind(this);
  61887. }
  61888. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61889. get: function () {
  61890. return this._isEnabled;
  61891. },
  61892. /** Gets or sets a boolean indicating if the viewer is enabled */
  61893. set: function (value) {
  61894. if (this._isEnabled === value) {
  61895. return;
  61896. }
  61897. this._isEnabled = value;
  61898. if (value) {
  61899. this._scene.registerBeforeRender(this._renderFunction);
  61900. }
  61901. else {
  61902. this._scene.unregisterBeforeRender(this._renderFunction);
  61903. }
  61904. },
  61905. enumerable: true,
  61906. configurable: true
  61907. });
  61908. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61909. if (x === void 0) { x = 0; }
  61910. if (y === void 0) { y = 0; }
  61911. if (z === void 0) { z = 0; }
  61912. var tmat = BABYLON.Tmp.Matrix[0];
  61913. var parentBone = bone.getParent();
  61914. tmat.copyFrom(bone.getLocalMatrix());
  61915. if (x !== 0 || y !== 0 || z !== 0) {
  61916. var tmat2 = BABYLON.Tmp.Matrix[1];
  61917. BABYLON.Matrix.IdentityToRef(tmat2);
  61918. tmat2.m[12] = x;
  61919. tmat2.m[13] = y;
  61920. tmat2.m[14] = z;
  61921. tmat2.multiplyToRef(tmat, tmat);
  61922. }
  61923. if (parentBone) {
  61924. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61925. }
  61926. tmat.multiplyToRef(meshMat, tmat);
  61927. position.x = tmat.m[12];
  61928. position.y = tmat.m[13];
  61929. position.z = tmat.m[14];
  61930. };
  61931. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61932. var len = bones.length;
  61933. var meshPos = this.mesh.position;
  61934. for (var i = 0; i < len; i++) {
  61935. var bone = bones[i];
  61936. var points = this._debugLines[i];
  61937. if (!points) {
  61938. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61939. this._debugLines[i] = points;
  61940. }
  61941. this._getBonePosition(points[0], bone, meshMat);
  61942. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61943. points[0].subtractInPlace(meshPos);
  61944. points[1].subtractInPlace(meshPos);
  61945. }
  61946. };
  61947. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61948. var len = bones.length;
  61949. var boneNum = 0;
  61950. var meshPos = this.mesh.position;
  61951. for (var i = len - 1; i >= 0; i--) {
  61952. var childBone = bones[i];
  61953. var parentBone = childBone.getParent();
  61954. if (!parentBone) {
  61955. continue;
  61956. }
  61957. var points = this._debugLines[boneNum];
  61958. if (!points) {
  61959. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61960. this._debugLines[boneNum] = points;
  61961. }
  61962. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61963. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61964. points[0].subtractInPlace(meshPos);
  61965. points[1].subtractInPlace(meshPos);
  61966. boneNum++;
  61967. }
  61968. };
  61969. /** Update the viewer to sync with current skeleton state */
  61970. SkeletonViewer.prototype.update = function () {
  61971. if (this.autoUpdateBonesMatrices) {
  61972. this.skeleton.computeAbsoluteTransforms();
  61973. }
  61974. if (this.skeleton.bones[0].length === undefined) {
  61975. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61976. }
  61977. else {
  61978. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61979. }
  61980. if (!this._debugMesh) {
  61981. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  61982. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61983. }
  61984. else {
  61985. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61986. }
  61987. this._debugMesh.position.copyFrom(this.mesh.position);
  61988. this._debugMesh.color = this.color;
  61989. };
  61990. /** Release associated resources */
  61991. SkeletonViewer.prototype.dispose = function () {
  61992. if (this._debugMesh) {
  61993. this.isEnabled = false;
  61994. this._debugMesh.dispose();
  61995. this._debugMesh = null;
  61996. }
  61997. };
  61998. return SkeletonViewer;
  61999. }());
  62000. Debug.SkeletonViewer = SkeletonViewer;
  62001. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62002. })(BABYLON || (BABYLON = {}));
  62003. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62004. /**
  62005. * Module Debug contains the (visual) components to debug a scene correctly
  62006. */
  62007. var BABYLON;
  62008. (function (BABYLON) {
  62009. var Debug;
  62010. (function (Debug) {
  62011. /**
  62012. * The Axes viewer will show 3 axes in a specific point in space
  62013. */
  62014. var AxesViewer = /** @class */ (function () {
  62015. /**
  62016. * Creates a new AxesViewer
  62017. * @param scene defines the hosting scene
  62018. * @param scaleLines defines a number used to scale line length (1 by default)
  62019. */
  62020. function AxesViewer(scene, scaleLines) {
  62021. if (scaleLines === void 0) { scaleLines = 1; }
  62022. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62023. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62024. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62025. /**
  62026. * Gets or sets a number used to scale line length
  62027. */
  62028. this.scaleLines = 1;
  62029. this.scaleLines = scaleLines;
  62030. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62031. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62032. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62033. this._xmesh.renderingGroupId = 2;
  62034. this._ymesh.renderingGroupId = 2;
  62035. this._zmesh.renderingGroupId = 2;
  62036. this._xmesh.material.checkReadyOnlyOnce = true;
  62037. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62038. this._ymesh.material.checkReadyOnlyOnce = true;
  62039. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62040. this._zmesh.material.checkReadyOnlyOnce = true;
  62041. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62042. this.scene = scene;
  62043. }
  62044. /**
  62045. * Force the viewer to update
  62046. * @param position defines the position of the viewer
  62047. * @param xaxis defines the x axis of the viewer
  62048. * @param yaxis defines the y axis of the viewer
  62049. * @param zaxis defines the z axis of the viewer
  62050. */
  62051. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62052. var scaleLines = this.scaleLines;
  62053. if (this._xmesh) {
  62054. this._xmesh.position.copyFrom(position);
  62055. }
  62056. if (this._ymesh) {
  62057. this._ymesh.position.copyFrom(position);
  62058. }
  62059. if (this._zmesh) {
  62060. this._zmesh.position.copyFrom(position);
  62061. }
  62062. var point2 = this._xline[1];
  62063. point2.x = xaxis.x * scaleLines;
  62064. point2.y = xaxis.y * scaleLines;
  62065. point2.z = xaxis.z * scaleLines;
  62066. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62067. point2 = this._yline[1];
  62068. point2.x = yaxis.x * scaleLines;
  62069. point2.y = yaxis.y * scaleLines;
  62070. point2.z = yaxis.z * scaleLines;
  62071. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62072. point2 = this._zline[1];
  62073. point2.x = zaxis.x * scaleLines;
  62074. point2.y = zaxis.y * scaleLines;
  62075. point2.z = zaxis.z * scaleLines;
  62076. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62077. };
  62078. /** Releases resources */
  62079. AxesViewer.prototype.dispose = function () {
  62080. if (this._xmesh) {
  62081. this._xmesh.dispose();
  62082. }
  62083. if (this._ymesh) {
  62084. this._ymesh.dispose();
  62085. }
  62086. if (this._zmesh) {
  62087. this._zmesh.dispose();
  62088. }
  62089. this._xmesh = null;
  62090. this._ymesh = null;
  62091. this._zmesh = null;
  62092. this.scene = null;
  62093. };
  62094. return AxesViewer;
  62095. }());
  62096. Debug.AxesViewer = AxesViewer;
  62097. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62098. })(BABYLON || (BABYLON = {}));
  62099. //# sourceMappingURL=babylon.axesViewer.js.map
  62100. var BABYLON;
  62101. (function (BABYLON) {
  62102. var Debug;
  62103. (function (Debug) {
  62104. /**
  62105. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62106. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62107. */
  62108. var BoneAxesViewer = /** @class */ (function (_super) {
  62109. __extends(BoneAxesViewer, _super);
  62110. /**
  62111. * Creates a new BoneAxesViewer
  62112. * @param scene defines the hosting scene
  62113. * @param bone defines the target bone
  62114. * @param mesh defines the target mesh
  62115. * @param scaleLines defines a scaling factor for line length (1 by default)
  62116. */
  62117. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62118. if (scaleLines === void 0) { scaleLines = 1; }
  62119. var _this = _super.call(this, scene, scaleLines) || this;
  62120. /** Gets current position */
  62121. _this.pos = BABYLON.Vector3.Zero();
  62122. /** Gets direction of X axis */
  62123. _this.xaxis = BABYLON.Vector3.Zero();
  62124. /** Gets direction of Y axis */
  62125. _this.yaxis = BABYLON.Vector3.Zero();
  62126. /** Gets direction of Z axis */
  62127. _this.zaxis = BABYLON.Vector3.Zero();
  62128. _this.mesh = mesh;
  62129. _this.bone = bone;
  62130. return _this;
  62131. }
  62132. /**
  62133. * Force the viewer to update
  62134. */
  62135. BoneAxesViewer.prototype.update = function () {
  62136. if (!this.mesh || !this.bone) {
  62137. return;
  62138. }
  62139. var bone = this.bone;
  62140. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62141. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62142. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62143. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62144. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62145. };
  62146. /** Releases resources */
  62147. BoneAxesViewer.prototype.dispose = function () {
  62148. if (this.mesh) {
  62149. this.mesh = null;
  62150. this.bone = null;
  62151. _super.prototype.dispose.call(this);
  62152. }
  62153. };
  62154. return BoneAxesViewer;
  62155. }(Debug.AxesViewer));
  62156. Debug.BoneAxesViewer = BoneAxesViewer;
  62157. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62158. })(BABYLON || (BABYLON = {}));
  62159. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62160. var BABYLON;
  62161. (function (BABYLON) {
  62162. var RayHelper = /** @class */ (function () {
  62163. function RayHelper(ray) {
  62164. this.ray = ray;
  62165. }
  62166. RayHelper.CreateAndShow = function (ray, scene, color) {
  62167. var helper = new RayHelper(ray);
  62168. helper.show(scene, color);
  62169. return helper;
  62170. };
  62171. RayHelper.prototype.show = function (scene, color) {
  62172. if (!this._renderFunction && this.ray) {
  62173. var ray = this.ray;
  62174. this._renderFunction = this._render.bind(this);
  62175. this._scene = scene;
  62176. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62177. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62178. if (this._renderFunction) {
  62179. this._scene.registerBeforeRender(this._renderFunction);
  62180. }
  62181. }
  62182. if (color && this._renderLine) {
  62183. this._renderLine.color.copyFrom(color);
  62184. }
  62185. };
  62186. RayHelper.prototype.hide = function () {
  62187. if (this._renderFunction && this._scene) {
  62188. this._scene.unregisterBeforeRender(this._renderFunction);
  62189. this._scene = null;
  62190. this._renderFunction = null;
  62191. if (this._renderLine) {
  62192. this._renderLine.dispose();
  62193. this._renderLine = null;
  62194. }
  62195. this._renderPoints = [];
  62196. }
  62197. };
  62198. RayHelper.prototype._render = function () {
  62199. var ray = this.ray;
  62200. if (!ray) {
  62201. return;
  62202. }
  62203. var point = this._renderPoints[1];
  62204. var len = Math.min(ray.length, 1000000);
  62205. point.copyFrom(ray.direction);
  62206. point.scaleInPlace(len);
  62207. point.addInPlace(ray.origin);
  62208. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62209. };
  62210. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62211. this._attachedToMesh = mesh;
  62212. var ray = this.ray;
  62213. if (!ray) {
  62214. return;
  62215. }
  62216. if (!ray.direction) {
  62217. ray.direction = BABYLON.Vector3.Zero();
  62218. }
  62219. if (!ray.origin) {
  62220. ray.origin = BABYLON.Vector3.Zero();
  62221. }
  62222. if (length) {
  62223. ray.length = length;
  62224. }
  62225. if (!meshSpaceOrigin) {
  62226. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62227. }
  62228. if (!meshSpaceDirection) {
  62229. // -1 so that this will work with Mesh.lookAt
  62230. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62231. }
  62232. if (!this._meshSpaceDirection) {
  62233. this._meshSpaceDirection = meshSpaceDirection.clone();
  62234. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62235. }
  62236. else {
  62237. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62238. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62239. }
  62240. if (!this._updateToMeshFunction) {
  62241. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62242. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62243. }
  62244. this._updateToMesh();
  62245. };
  62246. RayHelper.prototype.detachFromMesh = function () {
  62247. if (this._attachedToMesh) {
  62248. if (this._updateToMeshFunction) {
  62249. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62250. }
  62251. this._attachedToMesh = null;
  62252. this._updateToMeshFunction = null;
  62253. }
  62254. };
  62255. RayHelper.prototype._updateToMesh = function () {
  62256. var ray = this.ray;
  62257. if (!this._attachedToMesh || !ray) {
  62258. return;
  62259. }
  62260. if (this._attachedToMesh._isDisposed) {
  62261. this.detachFromMesh();
  62262. return;
  62263. }
  62264. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62265. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62266. };
  62267. RayHelper.prototype.dispose = function () {
  62268. this.hide();
  62269. this.detachFromMesh();
  62270. this.ray = null;
  62271. };
  62272. return RayHelper;
  62273. }());
  62274. BABYLON.RayHelper = RayHelper;
  62275. })(BABYLON || (BABYLON = {}));
  62276. //# sourceMappingURL=babylon.rayHelper.js.map
  62277. var BABYLON;
  62278. (function (BABYLON) {
  62279. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62280. get: function () {
  62281. if (!this._debugLayer) {
  62282. this._debugLayer = new DebugLayer(this);
  62283. }
  62284. return this._debugLayer;
  62285. },
  62286. enumerable: true,
  62287. configurable: true
  62288. });
  62289. var DebugLayer = /** @class */ (function () {
  62290. function DebugLayer(scene) {
  62291. var _this = this;
  62292. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62293. this.onPropertyChangedObservable = new BABYLON.Observable();
  62294. this._scene = scene;
  62295. this._scene.onDisposeObservable.add(function () {
  62296. // Debug layer
  62297. if (_this._scene._debugLayer) {
  62298. _this._scene._debugLayer.hide();
  62299. }
  62300. });
  62301. }
  62302. /** Creates the inspector window. */
  62303. DebugLayer.prototype._createInspector = function (config) {
  62304. if (config === void 0) { config = {}; }
  62305. var popup = config.popup || false;
  62306. var initialTab = config.initialTab || 0;
  62307. var parentElement = config.parentElement || null;
  62308. if (!this._inspector) {
  62309. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62310. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62311. } // else nothing to do as instance is already created
  62312. };
  62313. DebugLayer.prototype.isVisible = function () {
  62314. if (!this._inspector) {
  62315. return false;
  62316. }
  62317. return true;
  62318. };
  62319. DebugLayer.prototype.hide = function () {
  62320. if (this._inspector) {
  62321. try {
  62322. this._inspector.dispose();
  62323. }
  62324. catch (e) {
  62325. // If the inspector has been removed directly from the inspector tool
  62326. }
  62327. this.onPropertyChangedObservable.clear();
  62328. this._inspector = null;
  62329. }
  62330. };
  62331. /**
  62332. *
  62333. * Launch the debugLayer.
  62334. *
  62335. * initialTab:
  62336. * | Value | Tab Name |
  62337. * | --- | --- |
  62338. * | 0 | Scene |
  62339. * | 1 | Console |
  62340. * | 2 | Stats |
  62341. * | 3 | Textures |
  62342. * | 4 | Mesh |
  62343. * | 5 | Light |
  62344. * | 6 | Material |
  62345. * | 7 | GLTF |
  62346. * | 8 | GUI |
  62347. * | 9 | Physics |
  62348. * | 10 | Camera |
  62349. * | 11 | Audio |
  62350. *
  62351. */
  62352. DebugLayer.prototype.show = function (config) {
  62353. if (config === void 0) { config = {}; }
  62354. if (typeof this.BJSINSPECTOR == 'undefined') {
  62355. // Load inspector and add it to the DOM
  62356. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62357. }
  62358. else {
  62359. // Otherwise creates the inspector
  62360. this._createInspector(config);
  62361. }
  62362. };
  62363. /**
  62364. * Gets the active tab
  62365. * @return the index of the active tab or -1 if the inspector is hidden
  62366. */
  62367. DebugLayer.prototype.getActiveTab = function () {
  62368. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62369. };
  62370. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62371. return DebugLayer;
  62372. }());
  62373. BABYLON.DebugLayer = DebugLayer;
  62374. })(BABYLON || (BABYLON = {}));
  62375. //# sourceMappingURL=babylon.debugLayer.js.map
  62376. var BABYLON;
  62377. (function (BABYLON) {
  62378. var Debug;
  62379. (function (Debug) {
  62380. /**
  62381. * Used to show the physics impostor around the specific mesh
  62382. */
  62383. var PhysicsViewer = /** @class */ (function () {
  62384. /**
  62385. * Creates a new PhysicsViewer
  62386. * @param scene defines the hosting scene
  62387. */
  62388. function PhysicsViewer(scene) {
  62389. /** @hidden */
  62390. this._impostors = [];
  62391. /** @hidden */
  62392. this._meshes = [];
  62393. /** @hidden */
  62394. this._numMeshes = 0;
  62395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62396. var physicEngine = this._scene.getPhysicsEngine();
  62397. if (physicEngine) {
  62398. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62399. }
  62400. }
  62401. /** @hidden */
  62402. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62403. var plugin = this._physicsEnginePlugin;
  62404. for (var i = 0; i < this._numMeshes; i++) {
  62405. var impostor = this._impostors[i];
  62406. if (!impostor) {
  62407. continue;
  62408. }
  62409. if (impostor.isDisposed) {
  62410. this.hideImpostor(this._impostors[i--]);
  62411. }
  62412. else {
  62413. var mesh = this._meshes[i];
  62414. if (mesh && plugin) {
  62415. plugin.syncMeshWithImpostor(mesh, impostor);
  62416. }
  62417. }
  62418. }
  62419. };
  62420. /**
  62421. * Renders a specified physic impostor
  62422. * @param impostor defines the impostor to render
  62423. */
  62424. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62425. if (!this._scene) {
  62426. return;
  62427. }
  62428. for (var i = 0; i < this._numMeshes; i++) {
  62429. if (this._impostors[i] == impostor) {
  62430. return;
  62431. }
  62432. }
  62433. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62434. if (debugMesh) {
  62435. this._impostors[this._numMeshes] = impostor;
  62436. this._meshes[this._numMeshes] = debugMesh;
  62437. if (this._numMeshes === 0) {
  62438. this._renderFunction = this._updateDebugMeshes.bind(this);
  62439. this._scene.registerBeforeRender(this._renderFunction);
  62440. }
  62441. this._numMeshes++;
  62442. }
  62443. };
  62444. /**
  62445. * Hides a specified physic impostor
  62446. * @param impostor defines the impostor to hide
  62447. */
  62448. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62449. if (!impostor || !this._scene) {
  62450. return;
  62451. }
  62452. var removed = false;
  62453. for (var i = 0; i < this._numMeshes; i++) {
  62454. if (this._impostors[i] == impostor) {
  62455. var mesh = this._meshes[i];
  62456. if (!mesh) {
  62457. continue;
  62458. }
  62459. this._scene.removeMesh(mesh);
  62460. mesh.dispose();
  62461. this._numMeshes--;
  62462. if (this._numMeshes > 0) {
  62463. this._meshes[i] = this._meshes[this._numMeshes];
  62464. this._impostors[i] = this._impostors[this._numMeshes];
  62465. this._meshes[this._numMeshes] = null;
  62466. this._impostors[this._numMeshes] = null;
  62467. }
  62468. else {
  62469. this._meshes[0] = null;
  62470. this._impostors[0] = null;
  62471. }
  62472. removed = true;
  62473. break;
  62474. }
  62475. }
  62476. if (removed && this._numMeshes === 0) {
  62477. this._scene.unregisterBeforeRender(this._renderFunction);
  62478. }
  62479. };
  62480. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62481. if (!this._debugMaterial) {
  62482. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62483. this._debugMaterial.wireframe = true;
  62484. }
  62485. return this._debugMaterial;
  62486. };
  62487. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62488. if (!this._debugBoxMesh) {
  62489. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62490. this._debugBoxMesh.renderingGroupId = 1;
  62491. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62492. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62493. scene.removeMesh(this._debugBoxMesh);
  62494. }
  62495. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62496. };
  62497. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62498. if (!this._debugSphereMesh) {
  62499. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62500. this._debugSphereMesh.renderingGroupId = 1;
  62501. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62502. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62503. scene.removeMesh(this._debugSphereMesh);
  62504. }
  62505. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62506. };
  62507. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62508. var mesh = null;
  62509. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62510. mesh = this._getDebugBoxMesh(scene);
  62511. impostor.getBoxSizeToRef(mesh.scaling);
  62512. }
  62513. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62514. mesh = this._getDebugSphereMesh(scene);
  62515. var radius = impostor.getRadius();
  62516. mesh.scaling.x = radius * 2;
  62517. mesh.scaling.y = radius * 2;
  62518. mesh.scaling.z = radius * 2;
  62519. }
  62520. return mesh;
  62521. };
  62522. /** Releases all resources */
  62523. PhysicsViewer.prototype.dispose = function () {
  62524. for (var i = 0; i < this._numMeshes; i++) {
  62525. this.hideImpostor(this._impostors[i]);
  62526. }
  62527. if (this._debugBoxMesh) {
  62528. this._debugBoxMesh.dispose();
  62529. }
  62530. if (this._debugSphereMesh) {
  62531. this._debugSphereMesh.dispose();
  62532. }
  62533. if (this._debugMaterial) {
  62534. this._debugMaterial.dispose();
  62535. }
  62536. this._impostors.length = 0;
  62537. this._scene = null;
  62538. this._physicsEnginePlugin = null;
  62539. };
  62540. return PhysicsViewer;
  62541. }());
  62542. Debug.PhysicsViewer = PhysicsViewer;
  62543. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62544. })(BABYLON || (BABYLON = {}));
  62545. //# sourceMappingURL=babylon.physicsViewer.js.map
  62546. var BABYLON;
  62547. (function (BABYLON) {
  62548. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62549. get: function () {
  62550. return this._forceShowBoundingBoxes || false;
  62551. },
  62552. set: function (value) {
  62553. this._forceShowBoundingBoxes = value;
  62554. // Lazyly creates a BB renderer if needed.
  62555. if (value) {
  62556. this.getBoundingBoxRenderer();
  62557. }
  62558. },
  62559. enumerable: true,
  62560. configurable: true
  62561. });
  62562. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62563. if (!this._boundingBoxRenderer) {
  62564. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62565. }
  62566. return this._boundingBoxRenderer;
  62567. };
  62568. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62569. get: function () {
  62570. return this._showBoundingBox || false;
  62571. },
  62572. set: function (value) {
  62573. this._showBoundingBox = value;
  62574. // Lazyly creates a BB renderer if needed.
  62575. if (value) {
  62576. this.getScene().getBoundingBoxRenderer();
  62577. }
  62578. },
  62579. enumerable: true,
  62580. configurable: true
  62581. });
  62582. var BoundingBoxRenderer = /** @class */ (function () {
  62583. function BoundingBoxRenderer(scene) {
  62584. /**
  62585. * The component name helpfull to identify the component in the list of scene components.
  62586. */
  62587. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62588. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62589. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62590. this.showBackLines = true;
  62591. this.renderList = new BABYLON.SmartArray(32);
  62592. this._vertexBuffers = {};
  62593. this.scene = scene;
  62594. scene._addComponent(this);
  62595. }
  62596. /**
  62597. * Registers the component in a given scene
  62598. */
  62599. BoundingBoxRenderer.prototype.register = function () {
  62600. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62601. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62602. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62603. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62604. };
  62605. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62606. if (mesh.showSubMeshesBoundingBox) {
  62607. var boundingInfo = subMesh.getBoundingInfo();
  62608. if (boundingInfo !== null && boundingInfo !== undefined) {
  62609. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62610. this.renderList.push(boundingInfo.boundingBox);
  62611. }
  62612. }
  62613. };
  62614. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62615. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62616. var boundingInfo = sourceMesh.getBoundingInfo();
  62617. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62618. this.renderList.push(boundingInfo.boundingBox);
  62619. }
  62620. };
  62621. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62622. if (this._colorShader) {
  62623. return;
  62624. }
  62625. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62626. attributes: [BABYLON.VertexBuffer.PositionKind],
  62627. uniforms: ["world", "viewProjection", "color"]
  62628. });
  62629. var engine = this.scene.getEngine();
  62630. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62631. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62632. this._createIndexBuffer();
  62633. };
  62634. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62635. var engine = this.scene.getEngine();
  62636. 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]);
  62637. };
  62638. /**
  62639. * Rebuilds the elements related to this component in case of
  62640. * context lost for instance.
  62641. */
  62642. BoundingBoxRenderer.prototype.rebuild = function () {
  62643. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62644. if (vb) {
  62645. vb._rebuild();
  62646. }
  62647. this._createIndexBuffer();
  62648. };
  62649. BoundingBoxRenderer.prototype.reset = function () {
  62650. this.renderList.reset();
  62651. };
  62652. /**
  62653. * Render the bounding boxes of a specific rendering group
  62654. * @param renderingGroupId defines the rendering group to render
  62655. */
  62656. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62657. if (this.renderList.length === 0) {
  62658. return;
  62659. }
  62660. this._prepareRessources();
  62661. if (!this._colorShader.isReady()) {
  62662. return;
  62663. }
  62664. var engine = this.scene.getEngine();
  62665. engine.setDepthWrite(false);
  62666. this._colorShader._preBind();
  62667. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62668. var boundingBox = this.renderList.data[boundingBoxIndex];
  62669. if (boundingBox._tag !== renderingGroupId) {
  62670. continue;
  62671. }
  62672. var min = boundingBox.minimum;
  62673. var max = boundingBox.maximum;
  62674. var diff = max.subtract(min);
  62675. var median = min.add(diff.scale(0.5));
  62676. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62677. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62678. .multiply(boundingBox.getWorldMatrix());
  62679. // VBOs
  62680. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62681. if (this.showBackLines) {
  62682. // Back
  62683. engine.setDepthFunctionToGreaterOrEqual();
  62684. this.scene.resetCachedMaterial();
  62685. this._colorShader.setColor4("color", this.backColor.toColor4());
  62686. this._colorShader.bind(worldMatrix);
  62687. // Draw order
  62688. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62689. }
  62690. // Front
  62691. engine.setDepthFunctionToLess();
  62692. this.scene.resetCachedMaterial();
  62693. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62694. this._colorShader.bind(worldMatrix);
  62695. // Draw order
  62696. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62697. }
  62698. this._colorShader.unbind();
  62699. engine.setDepthFunctionToLessOrEqual();
  62700. engine.setDepthWrite(true);
  62701. };
  62702. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62703. this._prepareRessources();
  62704. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62705. return;
  62706. }
  62707. var engine = this.scene.getEngine();
  62708. engine.setDepthWrite(false);
  62709. engine.setColorWrite(false);
  62710. this._colorShader._preBind();
  62711. var boundingBox = mesh._boundingInfo.boundingBox;
  62712. var min = boundingBox.minimum;
  62713. var max = boundingBox.maximum;
  62714. var diff = max.subtract(min);
  62715. var median = min.add(diff.scale(0.5));
  62716. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62717. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62718. .multiply(boundingBox.getWorldMatrix());
  62719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62720. engine.setDepthFunctionToLess();
  62721. this.scene.resetCachedMaterial();
  62722. this._colorShader.bind(worldMatrix);
  62723. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62724. this._colorShader.unbind();
  62725. engine.setDepthFunctionToLessOrEqual();
  62726. engine.setDepthWrite(true);
  62727. engine.setColorWrite(true);
  62728. };
  62729. BoundingBoxRenderer.prototype.dispose = function () {
  62730. if (!this._colorShader) {
  62731. return;
  62732. }
  62733. this.renderList.dispose();
  62734. this._colorShader.dispose();
  62735. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62736. if (buffer) {
  62737. buffer.dispose();
  62738. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62739. }
  62740. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  62741. };
  62742. return BoundingBoxRenderer;
  62743. }());
  62744. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62745. })(BABYLON || (BABYLON = {}));
  62746. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62747. var BABYLON;
  62748. (function (BABYLON) {
  62749. BABYLON.Engine.prototype.createTransformFeedback = function () {
  62750. return this._gl.createTransformFeedback();
  62751. };
  62752. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  62753. this._gl.deleteTransformFeedback(value);
  62754. };
  62755. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  62756. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  62757. };
  62758. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  62759. if (usePoints === void 0) { usePoints = true; }
  62760. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  62761. };
  62762. BABYLON.Engine.prototype.endTransformFeedback = function () {
  62763. this._gl.endTransformFeedback();
  62764. };
  62765. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  62766. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  62767. };
  62768. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  62769. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  62770. };
  62771. })(BABYLON || (BABYLON = {}));
  62772. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  62773. var BABYLON;
  62774. (function (BABYLON) {
  62775. /**
  62776. * This represents a GPU particle system in Babylon
  62777. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  62778. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  62779. */
  62780. var GPUParticleSystem = /** @class */ (function (_super) {
  62781. __extends(GPUParticleSystem, _super);
  62782. /**
  62783. * Instantiates a GPU particle system.
  62784. * 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.
  62785. * @param name The name of the particle system
  62786. * @param options The options used to create the system
  62787. * @param scene The scene the particle system belongs to
  62788. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  62789. */
  62790. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  62791. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62792. var _this = _super.call(this, name) || this;
  62793. /**
  62794. * The layer mask we are rendering the particles through.
  62795. */
  62796. _this.layerMask = 0x0FFFFFFF;
  62797. _this._accumulatedCount = 0;
  62798. _this._targetIndex = 0;
  62799. _this._currentRenderId = -1;
  62800. _this._started = false;
  62801. _this._stopped = false;
  62802. _this._timeDelta = 0;
  62803. _this._attributesStrideSize = 21;
  62804. _this._actualFrame = 0;
  62805. _this._rawTextureWidth = 256;
  62806. /**
  62807. * An event triggered when the system is disposed.
  62808. */
  62809. _this.onDisposeObservable = new BABYLON.Observable();
  62810. /**
  62811. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  62812. * to override the particles.
  62813. */
  62814. _this.forceDepthWrite = false;
  62815. _this._preWarmDone = false;
  62816. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62817. // Setup the default processing configuration to the scene.
  62818. _this._attachImageProcessingConfiguration(null);
  62819. _this._engine = _this._scene.getEngine();
  62820. if (!options.randomTextureSize) {
  62821. delete options.randomTextureSize;
  62822. }
  62823. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  62824. var optionsAsNumber = options;
  62825. if (isFinite(optionsAsNumber)) {
  62826. fullOptions.capacity = optionsAsNumber;
  62827. }
  62828. _this._capacity = fullOptions.capacity;
  62829. _this._activeCount = fullOptions.capacity;
  62830. _this._currentActiveCount = 0;
  62831. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  62832. _this._scene.particleSystems.push(_this);
  62833. _this._updateEffectOptions = {
  62834. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  62835. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  62836. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  62837. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  62838. uniformBuffersNames: [],
  62839. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  62840. defines: "",
  62841. fallbacks: null,
  62842. onCompiled: null,
  62843. onError: null,
  62844. indexParameters: null,
  62845. maxSimultaneousLights: 0,
  62846. transformFeedbackVaryings: []
  62847. };
  62848. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  62849. // Random data
  62850. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  62851. var d = [];
  62852. for (var i = 0; i < maxTextureSize; ++i) {
  62853. d.push(Math.random());
  62854. d.push(Math.random());
  62855. d.push(Math.random());
  62856. d.push(Math.random());
  62857. }
  62858. _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);
  62859. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62860. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62861. d = [];
  62862. for (var i = 0; i < maxTextureSize; ++i) {
  62863. d.push(Math.random());
  62864. d.push(Math.random());
  62865. d.push(Math.random());
  62866. d.push(Math.random());
  62867. }
  62868. _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);
  62869. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62870. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62871. _this._randomTextureSize = maxTextureSize;
  62872. return _this;
  62873. }
  62874. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  62875. /**
  62876. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  62877. */
  62878. get: function () {
  62879. if (!BABYLON.Engine.LastCreatedEngine) {
  62880. return false;
  62881. }
  62882. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  62883. },
  62884. enumerable: true,
  62885. configurable: true
  62886. });
  62887. /**
  62888. * Gets the maximum number of particles active at the same time.
  62889. * @returns The max number of active particles.
  62890. */
  62891. GPUParticleSystem.prototype.getCapacity = function () {
  62892. return this._capacity;
  62893. };
  62894. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  62895. /**
  62896. * Gets or set the number of active particles
  62897. */
  62898. get: function () {
  62899. return this._activeCount;
  62900. },
  62901. set: function (value) {
  62902. this._activeCount = Math.min(value, this._capacity);
  62903. },
  62904. enumerable: true,
  62905. configurable: true
  62906. });
  62907. /**
  62908. * Is this system ready to be used/rendered
  62909. * @return true if the system is ready
  62910. */
  62911. GPUParticleSystem.prototype.isReady = function () {
  62912. if (!this._updateEffect) {
  62913. this._recreateUpdateEffect();
  62914. this._recreateRenderEffect();
  62915. return false;
  62916. }
  62917. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62918. return false;
  62919. }
  62920. return true;
  62921. };
  62922. /**
  62923. * Gets if the system has been started. (Note: this will still be true after stop is called)
  62924. * @returns True if it has been started, otherwise false.
  62925. */
  62926. GPUParticleSystem.prototype.isStarted = function () {
  62927. return this._started;
  62928. };
  62929. /**
  62930. * Starts the particle system and begins to emit
  62931. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  62932. */
  62933. GPUParticleSystem.prototype.start = function (delay) {
  62934. var _this = this;
  62935. if (delay === void 0) { delay = this.startDelay; }
  62936. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  62937. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  62938. }
  62939. if (delay) {
  62940. setTimeout(function () {
  62941. _this.start(0);
  62942. }, delay);
  62943. return;
  62944. }
  62945. this._started = true;
  62946. this._stopped = false;
  62947. this._preWarmDone = false;
  62948. };
  62949. /**
  62950. * Stops the particle system.
  62951. */
  62952. GPUParticleSystem.prototype.stop = function () {
  62953. this._stopped = true;
  62954. };
  62955. /**
  62956. * Remove all active particles
  62957. */
  62958. GPUParticleSystem.prototype.reset = function () {
  62959. this._releaseBuffers();
  62960. this._releaseVAOs();
  62961. this._currentActiveCount = 0;
  62962. this._targetIndex = 0;
  62963. };
  62964. /**
  62965. * Returns the string "GPUParticleSystem"
  62966. * @returns a string containing the class name
  62967. */
  62968. GPUParticleSystem.prototype.getClassName = function () {
  62969. return "GPUParticleSystem";
  62970. };
  62971. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  62972. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  62973. this._releaseBuffers();
  62974. return this;
  62975. };
  62976. /**
  62977. * Adds a new color gradient
  62978. * @param gradient defines the gradient to use (between 0 and 1)
  62979. * @param color1 defines the color to affect to the specified gradient
  62980. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  62981. * @returns the current particle system
  62982. */
  62983. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  62984. if (!this._colorGradients) {
  62985. this._colorGradients = [];
  62986. }
  62987. var colorGradient = new BABYLON.ColorGradient();
  62988. colorGradient.gradient = gradient;
  62989. colorGradient.color1 = color1;
  62990. this._colorGradients.push(colorGradient);
  62991. this._colorGradients.sort(function (a, b) {
  62992. if (a.gradient < b.gradient) {
  62993. return -1;
  62994. }
  62995. else if (a.gradient > b.gradient) {
  62996. return 1;
  62997. }
  62998. return 0;
  62999. });
  63000. if (this._colorGradientsTexture) {
  63001. this._colorGradientsTexture.dispose();
  63002. this._colorGradientsTexture = null;
  63003. }
  63004. this._releaseBuffers();
  63005. return this;
  63006. };
  63007. /**
  63008. * Remove a specific color gradient
  63009. * @param gradient defines the gradient to remove
  63010. * @returns the current particle system
  63011. */
  63012. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63013. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63014. this._colorGradientsTexture = null;
  63015. return this;
  63016. };
  63017. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63018. var valueGradient = new BABYLON.FactorGradient();
  63019. valueGradient.gradient = gradient;
  63020. valueGradient.factor1 = factor;
  63021. factorGradients.push(valueGradient);
  63022. factorGradients.sort(function (a, b) {
  63023. if (a.gradient < b.gradient) {
  63024. return -1;
  63025. }
  63026. else if (a.gradient > b.gradient) {
  63027. return 1;
  63028. }
  63029. return 0;
  63030. });
  63031. this._releaseBuffers();
  63032. };
  63033. /**
  63034. * Adds a new size gradient
  63035. * @param gradient defines the gradient to use (between 0 and 1)
  63036. * @param factor defines the size factor to affect to the specified gradient
  63037. * @returns the current particle system
  63038. */
  63039. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63040. if (!this._sizeGradients) {
  63041. this._sizeGradients = [];
  63042. }
  63043. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63044. if (this._sizeGradientsTexture) {
  63045. this._sizeGradientsTexture.dispose();
  63046. this._sizeGradientsTexture = null;
  63047. }
  63048. this._releaseBuffers();
  63049. return this;
  63050. };
  63051. /**
  63052. * Remove a specific size gradient
  63053. * @param gradient defines the gradient to remove
  63054. * @returns the current particle system
  63055. */
  63056. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63057. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63058. this._sizeGradientsTexture = null;
  63059. return this;
  63060. };
  63061. /**
  63062. * Adds a new angular speed gradient
  63063. * @param gradient defines the gradient to use (between 0 and 1)
  63064. * @param factor defines the angular speed to affect to the specified gradient
  63065. * @returns the current particle system
  63066. */
  63067. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63068. if (!this._angularSpeedGradients) {
  63069. this._angularSpeedGradients = [];
  63070. }
  63071. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63072. if (this._angularSpeedGradientsTexture) {
  63073. this._angularSpeedGradientsTexture.dispose();
  63074. this._angularSpeedGradientsTexture = null;
  63075. }
  63076. this._releaseBuffers();
  63077. return this;
  63078. };
  63079. /**
  63080. * Remove a specific angular speed gradient
  63081. * @param gradient defines the gradient to remove
  63082. * @returns the current particle system
  63083. */
  63084. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63085. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63086. this._angularSpeedGradientsTexture = null;
  63087. return this;
  63088. };
  63089. /**
  63090. * Adds a new velocity gradient
  63091. * @param gradient defines the gradient to use (between 0 and 1)
  63092. * @param factor defines the velocity to affect to the specified gradient
  63093. * @returns the current particle system
  63094. */
  63095. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63096. if (!this._velocityGradients) {
  63097. this._velocityGradients = [];
  63098. }
  63099. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63100. if (this._velocityGradientsTexture) {
  63101. this._velocityGradientsTexture.dispose();
  63102. this._velocityGradientsTexture = null;
  63103. }
  63104. this._releaseBuffers();
  63105. return this;
  63106. };
  63107. /**
  63108. * Remove a specific velocity gradient
  63109. * @param gradient defines the gradient to remove
  63110. * @returns the current particle system
  63111. */
  63112. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63113. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63114. this._velocityGradientsTexture = null;
  63115. return this;
  63116. };
  63117. /**
  63118. * Adds a new limit velocity gradient
  63119. * @param gradient defines the gradient to use (between 0 and 1)
  63120. * @param factor defines the limit velocity value to affect to the specified gradient
  63121. * @returns the current particle system
  63122. */
  63123. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63124. if (!this._limitVelocityGradients) {
  63125. this._limitVelocityGradients = [];
  63126. }
  63127. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63128. if (this._limitVelocityGradientsTexture) {
  63129. this._limitVelocityGradientsTexture.dispose();
  63130. this._limitVelocityGradientsTexture = null;
  63131. }
  63132. this._releaseBuffers();
  63133. return this;
  63134. };
  63135. /**
  63136. * Remove a specific limit velocity gradient
  63137. * @param gradient defines the gradient to remove
  63138. * @returns the current particle system
  63139. */
  63140. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63141. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63142. this._limitVelocityGradientsTexture = null;
  63143. return this;
  63144. };
  63145. /**
  63146. * Adds a new drag gradient
  63147. * @param gradient defines the gradient to use (between 0 and 1)
  63148. * @param factor defines the drag value to affect to the specified gradient
  63149. * @returns the current particle system
  63150. */
  63151. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63152. if (!this._dragGradients) {
  63153. this._dragGradients = [];
  63154. }
  63155. this._addFactorGradient(this._dragGradients, gradient, factor);
  63156. if (this._dragGradientsTexture) {
  63157. this._dragGradientsTexture.dispose();
  63158. this._dragGradientsTexture = null;
  63159. }
  63160. this._releaseBuffers();
  63161. return this;
  63162. };
  63163. /**
  63164. * Remove a specific drag gradient
  63165. * @param gradient defines the gradient to remove
  63166. * @returns the current particle system
  63167. */
  63168. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63169. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63170. this._dragGradientsTexture = null;
  63171. return this;
  63172. };
  63173. /**
  63174. * Not supported by GPUParticleSystem
  63175. * @param gradient defines the gradient to use (between 0 and 1)
  63176. * @param factor defines the emit rate value to affect to the specified gradient
  63177. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63178. * @returns the current particle system
  63179. */
  63180. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63181. // Do nothing as emit rate is not supported by GPUParticleSystem
  63182. return this;
  63183. };
  63184. /**
  63185. * Not supported by GPUParticleSystem
  63186. * @param gradient defines the gradient to remove
  63187. * @returns the current particle system
  63188. */
  63189. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63190. // Do nothing as emit rate is not supported by GPUParticleSystem
  63191. return this;
  63192. };
  63193. /**
  63194. * Not supported by GPUParticleSystem
  63195. * @param gradient defines the gradient to use (between 0 and 1)
  63196. * @param factor defines the start size value to affect to the specified gradient
  63197. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63198. * @returns the current particle system
  63199. */
  63200. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63201. // Do nothing as start size is not supported by GPUParticleSystem
  63202. return this;
  63203. };
  63204. /**
  63205. * Not supported by GPUParticleSystem
  63206. * @param gradient defines the gradient to remove
  63207. * @returns the current particle system
  63208. */
  63209. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63210. // Do nothing as start size is not supported by GPUParticleSystem
  63211. return this;
  63212. };
  63213. /**
  63214. * Not supported by GPUParticleSystem
  63215. * @param gradient defines the gradient to use (between 0 and 1)
  63216. * @param min defines the color remap minimal range
  63217. * @param max defines the color remap maximal range
  63218. * @returns the current particle system
  63219. */
  63220. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63221. // Do nothing as start size is not supported by GPUParticleSystem
  63222. return this;
  63223. };
  63224. /**
  63225. * Not supported by GPUParticleSystem
  63226. * @param gradient defines the gradient to remove
  63227. * @returns the current particle system
  63228. */
  63229. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63230. // Do nothing as start size is not supported by GPUParticleSystem
  63231. return this;
  63232. };
  63233. /**
  63234. * Not supported by GPUParticleSystem
  63235. * @param gradient defines the gradient to use (between 0 and 1)
  63236. * @param min defines the alpha remap minimal range
  63237. * @param max defines the alpha remap maximal range
  63238. * @returns the current particle system
  63239. */
  63240. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63241. // Do nothing as start size is not supported by GPUParticleSystem
  63242. return this;
  63243. };
  63244. /**
  63245. * Not supported by GPUParticleSystem
  63246. * @param gradient defines the gradient to remove
  63247. * @returns the current particle system
  63248. */
  63249. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63250. // Do nothing as start size is not supported by GPUParticleSystem
  63251. return this;
  63252. };
  63253. /**
  63254. * Not supported by GPUParticleSystem
  63255. * @param gradient defines the gradient to use (between 0 and 1)
  63256. * @param color defines the color to affect to the specified gradient
  63257. * @returns the current particle system
  63258. */
  63259. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63260. //Not supported by GPUParticleSystem
  63261. return this;
  63262. };
  63263. /**
  63264. * Not supported by GPUParticleSystem
  63265. * @param gradient defines the gradient to remove
  63266. * @returns the current particle system
  63267. */
  63268. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63269. //Not supported by GPUParticleSystem
  63270. return this;
  63271. };
  63272. /**
  63273. * Not supported by GPUParticleSystem
  63274. * @returns the list of ramp gradients
  63275. */
  63276. GPUParticleSystem.prototype.getRampGradients = function () {
  63277. return null;
  63278. };
  63279. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63280. /**
  63281. * Not supported by GPUParticleSystem
  63282. * Gets or sets a boolean indicating that ramp gradients must be used
  63283. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63284. */
  63285. get: function () {
  63286. //Not supported by GPUParticleSystem
  63287. return false;
  63288. },
  63289. set: function (value) {
  63290. //Not supported by GPUParticleSystem
  63291. },
  63292. enumerable: true,
  63293. configurable: true
  63294. });
  63295. GPUParticleSystem.prototype._reset = function () {
  63296. this._releaseBuffers();
  63297. };
  63298. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63299. var updateVertexBuffers = {};
  63300. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63301. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63302. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63303. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63304. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63305. var offset = 12;
  63306. if (!this._colorGradientsTexture) {
  63307. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63308. offset += 4;
  63309. }
  63310. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63311. offset += 3;
  63312. if (!this._isBillboardBased) {
  63313. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63314. offset += 3;
  63315. }
  63316. if (this._angularSpeedGradientsTexture) {
  63317. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63318. offset += 1;
  63319. }
  63320. else {
  63321. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63322. offset += 2;
  63323. }
  63324. if (this._isAnimationSheetEnabled) {
  63325. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63326. offset += 1;
  63327. if (this.spriteRandomStartCell) {
  63328. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63329. offset += 1;
  63330. }
  63331. }
  63332. if (this.noiseTexture) {
  63333. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63334. offset += 3;
  63335. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63336. offset += 3;
  63337. }
  63338. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63339. this._engine.bindArrayBuffer(null);
  63340. return vao;
  63341. };
  63342. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63343. var renderVertexBuffers = {};
  63344. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63345. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63346. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63347. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63348. var offset = 12;
  63349. if (!this._colorGradientsTexture) {
  63350. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63351. offset += 4;
  63352. }
  63353. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63354. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63355. }
  63356. offset += 3; // Direction
  63357. if (!this._isBillboardBased) {
  63358. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63359. offset += 3;
  63360. }
  63361. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63362. if (this._angularSpeedGradientsTexture) {
  63363. offset++;
  63364. }
  63365. else {
  63366. offset += 2;
  63367. }
  63368. if (this._isAnimationSheetEnabled) {
  63369. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63370. offset += 1;
  63371. if (this.spriteRandomStartCell) {
  63372. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63373. offset += 1;
  63374. }
  63375. }
  63376. if (this.noiseTexture) {
  63377. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63378. offset += 3;
  63379. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63380. offset += 3;
  63381. }
  63382. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63383. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63384. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63385. this._engine.bindArrayBuffer(null);
  63386. return vao;
  63387. };
  63388. GPUParticleSystem.prototype._initialize = function (force) {
  63389. if (force === void 0) { force = false; }
  63390. if (this._buffer0 && !force) {
  63391. return;
  63392. }
  63393. var engine = this._scene.getEngine();
  63394. var data = new Array();
  63395. if (!this.isBillboardBased) {
  63396. this._attributesStrideSize += 3;
  63397. }
  63398. if (this._colorGradientsTexture) {
  63399. this._attributesStrideSize -= 4;
  63400. }
  63401. if (this._angularSpeedGradientsTexture) {
  63402. this._attributesStrideSize -= 1;
  63403. }
  63404. if (this._isAnimationSheetEnabled) {
  63405. this._attributesStrideSize += 1;
  63406. if (this.spriteRandomStartCell) {
  63407. this._attributesStrideSize += 1;
  63408. }
  63409. }
  63410. if (this.noiseTexture) {
  63411. this._attributesStrideSize += 6;
  63412. }
  63413. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63414. // position
  63415. data.push(0.0);
  63416. data.push(0.0);
  63417. data.push(0.0);
  63418. // Age and life
  63419. data.push(0.0); // create the particle as a dead one to create a new one at start
  63420. data.push(0.0);
  63421. // Seed
  63422. data.push(Math.random());
  63423. data.push(Math.random());
  63424. data.push(Math.random());
  63425. data.push(Math.random());
  63426. // Size
  63427. data.push(0.0);
  63428. data.push(0.0);
  63429. data.push(0.0);
  63430. if (!this._colorGradientsTexture) {
  63431. // color
  63432. data.push(0.0);
  63433. data.push(0.0);
  63434. data.push(0.0);
  63435. data.push(0.0);
  63436. }
  63437. // direction
  63438. data.push(0.0);
  63439. data.push(0.0);
  63440. data.push(0.0);
  63441. if (!this.isBillboardBased) {
  63442. // initialDirection
  63443. data.push(0.0);
  63444. data.push(0.0);
  63445. data.push(0.0);
  63446. }
  63447. // angle
  63448. data.push(0.0);
  63449. if (!this._angularSpeedGradientsTexture) {
  63450. data.push(0.0);
  63451. }
  63452. if (this._isAnimationSheetEnabled) {
  63453. data.push(0.0);
  63454. if (this.spriteRandomStartCell) {
  63455. data.push(0.0);
  63456. }
  63457. }
  63458. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63459. data.push(Math.random());
  63460. data.push(Math.random());
  63461. data.push(Math.random());
  63462. data.push(Math.random());
  63463. data.push(Math.random());
  63464. data.push(Math.random());
  63465. }
  63466. }
  63467. // Sprite data
  63468. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63469. -0.5, 0.5, 0, 1,
  63470. -0.5, -0.5, 0, 0,
  63471. 0.5, -0.5, 1, 0]);
  63472. // Buffers
  63473. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63474. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63475. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63476. // Update VAO
  63477. this._updateVAO = [];
  63478. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63479. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63480. // Render VAO
  63481. this._renderVAO = [];
  63482. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63483. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63484. // Links
  63485. this._sourceBuffer = this._buffer0;
  63486. this._targetBuffer = this._buffer1;
  63487. };
  63488. /** @hidden */
  63489. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63490. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63491. if (this._isBillboardBased) {
  63492. defines += "\n#define BILLBOARD";
  63493. }
  63494. if (this._colorGradientsTexture) {
  63495. defines += "\n#define COLORGRADIENTS";
  63496. }
  63497. if (this._sizeGradientsTexture) {
  63498. defines += "\n#define SIZEGRADIENTS";
  63499. }
  63500. if (this._angularSpeedGradientsTexture) {
  63501. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63502. }
  63503. if (this._velocityGradientsTexture) {
  63504. defines += "\n#define VELOCITYGRADIENTS";
  63505. }
  63506. if (this._limitVelocityGradientsTexture) {
  63507. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63508. }
  63509. if (this._dragGradientsTexture) {
  63510. defines += "\n#define DRAGGRADIENTS";
  63511. }
  63512. if (this.isAnimationSheetEnabled) {
  63513. defines += "\n#define ANIMATESHEET";
  63514. if (this.spriteRandomStartCell) {
  63515. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63516. }
  63517. }
  63518. if (this.noiseTexture) {
  63519. defines += "\n#define NOISE";
  63520. }
  63521. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63522. return;
  63523. }
  63524. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63525. if (!this._colorGradientsTexture) {
  63526. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63527. }
  63528. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63529. if (!this._isBillboardBased) {
  63530. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63531. }
  63532. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63533. if (this.isAnimationSheetEnabled) {
  63534. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63535. if (this.spriteRandomStartCell) {
  63536. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63537. }
  63538. }
  63539. if (this.noiseTexture) {
  63540. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63541. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63542. }
  63543. this._updateEffectOptions.defines = defines;
  63544. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63545. };
  63546. /** @hidden */
  63547. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63548. var defines = "";
  63549. if (this._scene.clipPlane) {
  63550. defines = "\n#define CLIPPLANE";
  63551. }
  63552. if (this._scene.clipPlane2) {
  63553. defines = "\n#define CLIPPLANE2";
  63554. }
  63555. if (this._scene.clipPlane3) {
  63556. defines = "\n#define CLIPPLANE3";
  63557. }
  63558. if (this._scene.clipPlane4) {
  63559. defines = "\n#define CLIPPLANE4";
  63560. }
  63561. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63562. defines = "\n#define BLENDMULTIPLYMODE";
  63563. }
  63564. if (this._isBillboardBased) {
  63565. defines += "\n#define BILLBOARD";
  63566. switch (this.billboardMode) {
  63567. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63568. defines += "\n#define BILLBOARDY";
  63569. break;
  63570. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63571. defines += "\n#define BILLBOARDSTRETCHED";
  63572. break;
  63573. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63574. default:
  63575. break;
  63576. }
  63577. }
  63578. if (this._colorGradientsTexture) {
  63579. defines += "\n#define COLORGRADIENTS";
  63580. }
  63581. if (this.isAnimationSheetEnabled) {
  63582. defines += "\n#define ANIMATESHEET";
  63583. }
  63584. if (this._imageProcessingConfiguration) {
  63585. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63586. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63587. }
  63588. if (this._renderEffect && this._renderEffect.defines === defines) {
  63589. return;
  63590. }
  63591. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63592. var samplers = ["textureSampler", "colorGradientSampler"];
  63593. if (BABYLON.ImageProcessingConfiguration) {
  63594. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63595. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63596. }
  63597. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63598. };
  63599. /**
  63600. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63601. * @param preWarm defines if we are in the pre-warmimg phase
  63602. */
  63603. GPUParticleSystem.prototype.animate = function (preWarm) {
  63604. if (preWarm === void 0) { preWarm = false; }
  63605. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63606. this._actualFrame += this._timeDelta;
  63607. if (!this._stopped) {
  63608. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63609. this.stop();
  63610. }
  63611. }
  63612. };
  63613. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63614. var texture = this[textureName];
  63615. if (!factorGradients || !factorGradients.length || texture) {
  63616. return;
  63617. }
  63618. var data = new Float32Array(this._rawTextureWidth);
  63619. for (var x = 0; x < this._rawTextureWidth; x++) {
  63620. var ratio = x / this._rawTextureWidth;
  63621. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63622. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63623. });
  63624. }
  63625. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63626. };
  63627. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63628. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63629. };
  63630. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63631. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63632. };
  63633. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63634. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63635. };
  63636. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63637. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63638. };
  63639. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63640. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63641. };
  63642. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63643. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63644. return;
  63645. }
  63646. var data = new Uint8Array(this._rawTextureWidth * 4);
  63647. var tmpColor = BABYLON.Tmp.Color4[0];
  63648. for (var x = 0; x < this._rawTextureWidth; x++) {
  63649. var ratio = x / this._rawTextureWidth;
  63650. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63651. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63652. data[x * 4] = tmpColor.r * 255;
  63653. data[x * 4 + 1] = tmpColor.g * 255;
  63654. data[x * 4 + 2] = tmpColor.b * 255;
  63655. data[x * 4 + 3] = tmpColor.a * 255;
  63656. });
  63657. }
  63658. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63659. };
  63660. /**
  63661. * Renders the particle system in its current state
  63662. * @param preWarm defines if the system should only update the particles but not render them
  63663. * @returns the current number of particles
  63664. */
  63665. GPUParticleSystem.prototype.render = function (preWarm) {
  63666. if (preWarm === void 0) { preWarm = false; }
  63667. if (!this._started) {
  63668. return 0;
  63669. }
  63670. this._createColorGradientTexture();
  63671. this._createSizeGradientTexture();
  63672. this._createAngularSpeedGradientTexture();
  63673. this._createVelocityGradientTexture();
  63674. this._createLimitVelocityGradientTexture();
  63675. this._createDragGradientTexture();
  63676. this._recreateUpdateEffect();
  63677. this._recreateRenderEffect();
  63678. if (!this.isReady()) {
  63679. return 0;
  63680. }
  63681. if (!preWarm) {
  63682. if (!this._preWarmDone && this.preWarmCycles) {
  63683. for (var index = 0; index < this.preWarmCycles; index++) {
  63684. this.animate(true);
  63685. this.render(true);
  63686. }
  63687. this._preWarmDone = true;
  63688. }
  63689. if (this._currentRenderId === this._scene.getRenderId()) {
  63690. return 0;
  63691. }
  63692. this._currentRenderId = this._scene.getRenderId();
  63693. }
  63694. // Get everything ready to render
  63695. this._initialize();
  63696. this._accumulatedCount += this.emitRate * this._timeDelta;
  63697. if (this._accumulatedCount > 1) {
  63698. var intPart = this._accumulatedCount | 0;
  63699. this._accumulatedCount -= intPart;
  63700. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  63701. }
  63702. if (!this._currentActiveCount) {
  63703. return 0;
  63704. }
  63705. // Enable update effect
  63706. this._engine.enableEffect(this._updateEffect);
  63707. this._engine.setState(false);
  63708. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  63709. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  63710. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  63711. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  63712. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  63713. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  63714. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  63715. if (!this._colorGradientsTexture) {
  63716. this._updateEffect.setDirectColor4("color1", this.color1);
  63717. this._updateEffect.setDirectColor4("color2", this.color2);
  63718. }
  63719. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  63720. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  63721. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  63722. this._updateEffect.setVector3("gravity", this.gravity);
  63723. if (this._sizeGradientsTexture) {
  63724. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  63725. }
  63726. if (this._angularSpeedGradientsTexture) {
  63727. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  63728. }
  63729. if (this._velocityGradientsTexture) {
  63730. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  63731. }
  63732. if (this._limitVelocityGradientsTexture) {
  63733. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  63734. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  63735. }
  63736. if (this._dragGradientsTexture) {
  63737. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  63738. }
  63739. if (this.particleEmitterType) {
  63740. this.particleEmitterType.applyToShader(this._updateEffect);
  63741. }
  63742. if (this._isAnimationSheetEnabled) {
  63743. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  63744. }
  63745. if (this.noiseTexture) {
  63746. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  63747. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  63748. }
  63749. var emitterWM;
  63750. if (this.emitter.position) {
  63751. var emitterMesh = this.emitter;
  63752. emitterWM = emitterMesh.getWorldMatrix();
  63753. }
  63754. else {
  63755. var emitterPosition = this.emitter;
  63756. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  63757. }
  63758. this._updateEffect.setMatrix("emitterWM", emitterWM);
  63759. // Bind source VAO
  63760. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  63761. // Update
  63762. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  63763. this._engine.setRasterizerState(false);
  63764. this._engine.beginTransformFeedback(true);
  63765. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  63766. this._engine.endTransformFeedback();
  63767. this._engine.setRasterizerState(true);
  63768. this._engine.bindTransformFeedbackBuffer(null);
  63769. if (!preWarm) {
  63770. // Enable render effect
  63771. this._engine.enableEffect(this._renderEffect);
  63772. var viewMatrix = this._scene.getViewMatrix();
  63773. this._renderEffect.setMatrix("view", viewMatrix);
  63774. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  63775. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  63776. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  63777. if (this._colorGradientsTexture) {
  63778. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  63779. }
  63780. else {
  63781. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  63782. }
  63783. if (this._isAnimationSheetEnabled && this.particleTexture) {
  63784. var baseSize = this.particleTexture.getBaseSize();
  63785. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  63786. }
  63787. if (this._isBillboardBased) {
  63788. var camera = this._scene.activeCamera;
  63789. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  63790. }
  63791. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  63792. var invView = viewMatrix.clone();
  63793. invView.invert();
  63794. this._renderEffect.setMatrix("invView", invView);
  63795. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  63796. }
  63797. // image processing
  63798. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  63799. this._imageProcessingConfiguration.bind(this._renderEffect);
  63800. }
  63801. // Draw order
  63802. switch (this.blendMode) {
  63803. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  63804. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  63805. break;
  63806. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  63807. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  63808. break;
  63809. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  63810. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  63811. break;
  63812. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  63813. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  63814. break;
  63815. }
  63816. if (this.forceDepthWrite) {
  63817. this._engine.setDepthWrite(true);
  63818. }
  63819. // Bind source VAO
  63820. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  63821. // Render
  63822. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  63823. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63824. }
  63825. // Switch VAOs
  63826. this._targetIndex++;
  63827. if (this._targetIndex === 2) {
  63828. this._targetIndex = 0;
  63829. }
  63830. // Switch buffers
  63831. var tmpBuffer = this._sourceBuffer;
  63832. this._sourceBuffer = this._targetBuffer;
  63833. this._targetBuffer = tmpBuffer;
  63834. return this._currentActiveCount;
  63835. };
  63836. /**
  63837. * Rebuilds the particle system
  63838. */
  63839. GPUParticleSystem.prototype.rebuild = function () {
  63840. this._initialize(true);
  63841. };
  63842. GPUParticleSystem.prototype._releaseBuffers = function () {
  63843. if (this._buffer0) {
  63844. this._buffer0.dispose();
  63845. this._buffer0 = null;
  63846. }
  63847. if (this._buffer1) {
  63848. this._buffer1.dispose();
  63849. this._buffer1 = null;
  63850. }
  63851. if (this._spriteBuffer) {
  63852. this._spriteBuffer.dispose();
  63853. this._spriteBuffer = null;
  63854. }
  63855. };
  63856. GPUParticleSystem.prototype._releaseVAOs = function () {
  63857. if (!this._updateVAO) {
  63858. return;
  63859. }
  63860. for (var index = 0; index < this._updateVAO.length; index++) {
  63861. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  63862. }
  63863. this._updateVAO = [];
  63864. for (var index = 0; index < this._renderVAO.length; index++) {
  63865. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  63866. }
  63867. this._renderVAO = [];
  63868. };
  63869. /**
  63870. * Disposes the particle system and free the associated resources
  63871. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  63872. */
  63873. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  63874. if (disposeTexture === void 0) { disposeTexture = true; }
  63875. var index = this._scene.particleSystems.indexOf(this);
  63876. if (index > -1) {
  63877. this._scene.particleSystems.splice(index, 1);
  63878. }
  63879. this._releaseBuffers();
  63880. this._releaseVAOs();
  63881. if (this._colorGradientsTexture) {
  63882. this._colorGradientsTexture.dispose();
  63883. this._colorGradientsTexture = null;
  63884. }
  63885. if (this._sizeGradientsTexture) {
  63886. this._sizeGradientsTexture.dispose();
  63887. this._sizeGradientsTexture = null;
  63888. }
  63889. if (this._angularSpeedGradientsTexture) {
  63890. this._angularSpeedGradientsTexture.dispose();
  63891. this._angularSpeedGradientsTexture = null;
  63892. }
  63893. if (this._velocityGradientsTexture) {
  63894. this._velocityGradientsTexture.dispose();
  63895. this._velocityGradientsTexture = null;
  63896. }
  63897. if (this._limitVelocityGradientsTexture) {
  63898. this._limitVelocityGradientsTexture.dispose();
  63899. this._limitVelocityGradientsTexture = null;
  63900. }
  63901. if (this._dragGradientsTexture) {
  63902. this._dragGradientsTexture.dispose();
  63903. this._dragGradientsTexture = null;
  63904. }
  63905. if (this._randomTexture) {
  63906. this._randomTexture.dispose();
  63907. this._randomTexture = null;
  63908. }
  63909. if (this._randomTexture2) {
  63910. this._randomTexture2.dispose();
  63911. this._randomTexture2 = null;
  63912. }
  63913. if (disposeTexture && this.particleTexture) {
  63914. this.particleTexture.dispose();
  63915. this.particleTexture = null;
  63916. }
  63917. if (disposeTexture && this.noiseTexture) {
  63918. this.noiseTexture.dispose();
  63919. this.noiseTexture = null;
  63920. }
  63921. // Callback
  63922. this.onDisposeObservable.notifyObservers(this);
  63923. this.onDisposeObservable.clear();
  63924. };
  63925. /**
  63926. * Clones the particle system.
  63927. * @param name The name of the cloned object
  63928. * @param newEmitter The new emitter to use
  63929. * @returns the cloned particle system
  63930. */
  63931. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  63932. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  63933. BABYLON.Tools.DeepCopy(this, result);
  63934. if (newEmitter === undefined) {
  63935. newEmitter = this.emitter;
  63936. }
  63937. result.emitter = newEmitter;
  63938. if (this.particleTexture) {
  63939. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  63940. }
  63941. return result;
  63942. };
  63943. /**
  63944. * Serializes the particle system to a JSON object.
  63945. * @returns the JSON object
  63946. */
  63947. GPUParticleSystem.prototype.serialize = function () {
  63948. var serializationObject = {};
  63949. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  63950. serializationObject.activeParticleCount = this.activeParticleCount;
  63951. return serializationObject;
  63952. };
  63953. /**
  63954. * Parses a JSON object to create a GPU particle system.
  63955. * @param parsedParticleSystem The JSON object to parse
  63956. * @param scene The scene to create the particle system in
  63957. * @param rootUrl The root url to use to load external dependencies like texture
  63958. * @returns the parsed GPU particle system
  63959. */
  63960. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  63961. var name = parsedParticleSystem.name;
  63962. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  63963. if (parsedParticleSystem.activeParticleCount) {
  63964. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  63965. }
  63966. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  63967. return particleSystem;
  63968. };
  63969. return GPUParticleSystem;
  63970. }(BABYLON.BaseParticleSystem));
  63971. BABYLON.GPUParticleSystem = GPUParticleSystem;
  63972. })(BABYLON || (BABYLON = {}));
  63973. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  63974. var BABYLON;
  63975. (function (BABYLON) {
  63976. /**
  63977. * Represents one particle of a solid particle system.
  63978. */
  63979. var SolidParticle = /** @class */ (function () {
  63980. /**
  63981. * Creates a Solid Particle object.
  63982. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  63983. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  63984. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  63985. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  63986. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  63987. * @param shapeId (integer) is the model shape identifier in the SPS.
  63988. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  63989. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  63990. */
  63991. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  63992. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  63993. /**
  63994. * particle global index
  63995. */
  63996. this.idx = 0;
  63997. /**
  63998. * The color of the particle
  63999. */
  64000. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64001. /**
  64002. * The world space position of the particle.
  64003. */
  64004. this.position = BABYLON.Vector3.Zero();
  64005. /**
  64006. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64007. */
  64008. this.rotation = BABYLON.Vector3.Zero();
  64009. /**
  64010. * The scaling of the particle.
  64011. */
  64012. this.scaling = BABYLON.Vector3.One();
  64013. /**
  64014. * The uvs of the particle.
  64015. */
  64016. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64017. /**
  64018. * The current speed of the particle.
  64019. */
  64020. this.velocity = BABYLON.Vector3.Zero();
  64021. /**
  64022. * The pivot point in the particle local space.
  64023. */
  64024. this.pivot = BABYLON.Vector3.Zero();
  64025. /**
  64026. * Must the particle be translated from its pivot point in its local space ?
  64027. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64028. * Default : false
  64029. */
  64030. this.translateFromPivot = false;
  64031. /**
  64032. * Is the particle active or not ?
  64033. */
  64034. this.alive = true;
  64035. /**
  64036. * Is the particle visible or not ?
  64037. */
  64038. this.isVisible = true;
  64039. /**
  64040. * Index of this particle in the global "positions" array (Internal use)
  64041. * @hidden
  64042. */
  64043. this._pos = 0;
  64044. /**
  64045. * @hidden Index of this particle in the global "indices" array (Internal use)
  64046. */
  64047. this._ind = 0;
  64048. /**
  64049. * ModelShape id of this particle
  64050. */
  64051. this.shapeId = 0;
  64052. /**
  64053. * Index of the particle in its shape id (Internal use)
  64054. */
  64055. this.idxInShape = 0;
  64056. /**
  64057. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64058. */
  64059. this._stillInvisible = false;
  64060. /**
  64061. * @hidden Last computed particle rotation matrix
  64062. */
  64063. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64064. /**
  64065. * Parent particle Id, if any.
  64066. * Default null.
  64067. */
  64068. this.parentId = null;
  64069. /**
  64070. * @hidden Internal global position in the SPS.
  64071. */
  64072. this._globalPosition = BABYLON.Vector3.Zero();
  64073. this.idx = particleIndex;
  64074. this._pos = positionIndex;
  64075. this._ind = indiceIndex;
  64076. this._model = model;
  64077. this.shapeId = shapeId;
  64078. this.idxInShape = idxInShape;
  64079. this._sps = sps;
  64080. if (modelBoundingInfo) {
  64081. this._modelBoundingInfo = modelBoundingInfo;
  64082. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64083. }
  64084. }
  64085. Object.defineProperty(SolidParticle.prototype, "scale", {
  64086. /**
  64087. * Legacy support, changed scale to scaling
  64088. */
  64089. get: function () {
  64090. return this.scaling;
  64091. },
  64092. /**
  64093. * Legacy support, changed scale to scaling
  64094. */
  64095. set: function (scale) {
  64096. this.scaling = scale;
  64097. },
  64098. enumerable: true,
  64099. configurable: true
  64100. });
  64101. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64102. /**
  64103. * Legacy support, changed quaternion to rotationQuaternion
  64104. */
  64105. get: function () {
  64106. return this.rotationQuaternion;
  64107. },
  64108. /**
  64109. * Legacy support, changed quaternion to rotationQuaternion
  64110. */
  64111. set: function (q) {
  64112. this.rotationQuaternion = q;
  64113. },
  64114. enumerable: true,
  64115. configurable: true
  64116. });
  64117. /**
  64118. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64119. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64120. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64121. * @returns true if it intersects
  64122. */
  64123. SolidParticle.prototype.intersectsMesh = function (target) {
  64124. if (!this._boundingInfo || !target._boundingInfo) {
  64125. return false;
  64126. }
  64127. if (this._sps._bSphereOnly) {
  64128. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64129. }
  64130. return this._boundingInfo.intersects(target._boundingInfo, false);
  64131. };
  64132. return SolidParticle;
  64133. }());
  64134. BABYLON.SolidParticle = SolidParticle;
  64135. /**
  64136. * Represents the shape of the model used by one particle of a solid particle system.
  64137. * SPS internal tool, don't use it manually.
  64138. */
  64139. var ModelShape = /** @class */ (function () {
  64140. /**
  64141. * 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.
  64142. * SPS internal tool, don't use it manually.
  64143. * @hidden
  64144. */
  64145. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64146. /**
  64147. * length of the shape in the model indices array (internal use)
  64148. * @hidden
  64149. */
  64150. this._indicesLength = 0;
  64151. this.shapeID = id;
  64152. this._shape = shape;
  64153. this._indicesLength = indicesLength;
  64154. this._shapeUV = shapeUV;
  64155. this._positionFunction = posFunction;
  64156. this._vertexFunction = vtxFunction;
  64157. }
  64158. return ModelShape;
  64159. }());
  64160. BABYLON.ModelShape = ModelShape;
  64161. /**
  64162. * Represents a Depth Sorted Particle in the solid particle system.
  64163. */
  64164. var DepthSortedParticle = /** @class */ (function () {
  64165. function DepthSortedParticle() {
  64166. /**
  64167. * Index of the particle in the "indices" array
  64168. */
  64169. this.ind = 0;
  64170. /**
  64171. * Length of the particle shape in the "indices" array
  64172. */
  64173. this.indicesLength = 0;
  64174. /**
  64175. * Squared distance from the particle to the camera
  64176. */
  64177. this.sqDistance = 0.0;
  64178. }
  64179. return DepthSortedParticle;
  64180. }());
  64181. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64182. })(BABYLON || (BABYLON = {}));
  64183. //# sourceMappingURL=babylon.solidParticle.js.map
  64184. var BABYLON;
  64185. (function (BABYLON) {
  64186. /**
  64187. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64188. *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.
  64189. * The SPS is also a particle system. It provides some methods to manage the particles.
  64190. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64191. *
  64192. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64193. */
  64194. var SolidParticleSystem = /** @class */ (function () {
  64195. /**
  64196. * Creates a SPS (Solid Particle System) object.
  64197. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64198. * @param scene (Scene) is the scene in which the SPS is added.
  64199. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64200. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64201. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64202. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64203. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64204. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64205. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64206. */
  64207. function SolidParticleSystem(name, scene, options) {
  64208. /**
  64209. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64210. * Example : var p = SPS.particles[i];
  64211. */
  64212. this.particles = new Array();
  64213. /**
  64214. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64215. */
  64216. this.nbParticles = 0;
  64217. /**
  64218. * If the particles must ever face the camera (default false). Useful for planar particles.
  64219. */
  64220. this.billboard = false;
  64221. /**
  64222. * Recompute normals when adding a shape
  64223. */
  64224. this.recomputeNormals = true;
  64225. /**
  64226. * This a counter ofr your own usage. It's not set by any SPS functions.
  64227. */
  64228. this.counter = 0;
  64229. /**
  64230. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64231. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64232. */
  64233. this.vars = {};
  64234. /**
  64235. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64236. * @hidden
  64237. */
  64238. this._bSphereOnly = false;
  64239. /**
  64240. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64241. * @hidden
  64242. */
  64243. this._bSphereRadiusFactor = 1.0;
  64244. this._positions = new Array();
  64245. this._indices = new Array();
  64246. this._normals = new Array();
  64247. this._colors = new Array();
  64248. this._uvs = new Array();
  64249. this._index = 0; // indices index
  64250. this._updatable = true;
  64251. this._pickable = false;
  64252. this._isVisibilityBoxLocked = false;
  64253. this._alwaysVisible = false;
  64254. this._depthSort = false;
  64255. this._shapeCounter = 0;
  64256. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64257. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64258. this._computeParticleColor = true;
  64259. this._computeParticleTexture = true;
  64260. this._computeParticleRotation = true;
  64261. this._computeParticleVertex = false;
  64262. this._computeBoundingBox = false;
  64263. this._depthSortParticles = true;
  64264. this._cam_axisZ = BABYLON.Vector3.Zero();
  64265. this._cam_axisY = BABYLON.Vector3.Zero();
  64266. this._cam_axisX = BABYLON.Vector3.Zero();
  64267. this._axisZ = BABYLON.Axis.Z;
  64268. this._camDir = BABYLON.Vector3.Zero();
  64269. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64270. this._rotMatrix = new BABYLON.Matrix();
  64271. this._invertMatrix = new BABYLON.Matrix();
  64272. this._rotated = BABYLON.Vector3.Zero();
  64273. this._quaternion = new BABYLON.Quaternion();
  64274. this._vertex = BABYLON.Vector3.Zero();
  64275. this._normal = BABYLON.Vector3.Zero();
  64276. this._yaw = 0.0;
  64277. this._pitch = 0.0;
  64278. this._roll = 0.0;
  64279. this._halfroll = 0.0;
  64280. this._halfpitch = 0.0;
  64281. this._halfyaw = 0.0;
  64282. this._sinRoll = 0.0;
  64283. this._cosRoll = 0.0;
  64284. this._sinPitch = 0.0;
  64285. this._cosPitch = 0.0;
  64286. this._sinYaw = 0.0;
  64287. this._cosYaw = 0.0;
  64288. this._mustUnrotateFixedNormals = false;
  64289. this._minimum = BABYLON.Vector3.Zero();
  64290. this._maximum = BABYLON.Vector3.Zero();
  64291. this._minBbox = BABYLON.Vector3.Zero();
  64292. this._maxBbox = BABYLON.Vector3.Zero();
  64293. this._particlesIntersect = false;
  64294. this._depthSortFunction = function (p1, p2) {
  64295. return (p2.sqDistance - p1.sqDistance);
  64296. };
  64297. this._needs32Bits = false;
  64298. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64299. this._scaledPivot = BABYLON.Vector3.Zero();
  64300. this._particleHasParent = false;
  64301. this.name = name;
  64302. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64303. this._camera = scene.activeCamera;
  64304. this._pickable = options ? options.isPickable : false;
  64305. this._depthSort = options ? options.enableDepthSort : false;
  64306. this._particlesIntersect = options ? options.particleIntersection : false;
  64307. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64308. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64309. if (options && options.updatable !== undefined) {
  64310. this._updatable = options.updatable;
  64311. }
  64312. else {
  64313. this._updatable = true;
  64314. }
  64315. if (this._pickable) {
  64316. this.pickedParticles = [];
  64317. }
  64318. if (this._depthSort) {
  64319. this.depthSortedParticles = [];
  64320. }
  64321. }
  64322. /**
  64323. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64324. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64325. * @returns the created mesh
  64326. */
  64327. SolidParticleSystem.prototype.buildMesh = function () {
  64328. if (this.nbParticles === 0) {
  64329. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64330. this.addShape(triangle, 1);
  64331. triangle.dispose();
  64332. }
  64333. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64334. this._positions32 = new Float32Array(this._positions);
  64335. this._uvs32 = new Float32Array(this._uvs);
  64336. this._colors32 = new Float32Array(this._colors);
  64337. if (this.recomputeNormals) {
  64338. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64339. }
  64340. this._normals32 = new Float32Array(this._normals);
  64341. this._fixedNormal32 = new Float32Array(this._normals);
  64342. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64343. this._unrotateFixedNormals();
  64344. }
  64345. var vertexData = new BABYLON.VertexData();
  64346. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64347. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64348. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64349. if (this._uvs32.length > 0) {
  64350. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64351. }
  64352. if (this._colors32.length > 0) {
  64353. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64354. }
  64355. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64356. vertexData.applyToMesh(mesh, this._updatable);
  64357. this.mesh = mesh;
  64358. this.mesh.isPickable = this._pickable;
  64359. // free memory
  64360. if (!this._depthSort) {
  64361. this._indices = null;
  64362. }
  64363. this._positions = null;
  64364. this._normals = null;
  64365. this._uvs = null;
  64366. this._colors = null;
  64367. if (!this._updatable) {
  64368. this.particles.length = 0;
  64369. }
  64370. return mesh;
  64371. };
  64372. /**
  64373. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64374. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64375. * Thus the particles generated from `digest()` have their property `position` set yet.
  64376. * @param mesh ( Mesh ) is the mesh to be digested
  64377. * @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
  64378. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64379. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64380. * @returns the current SPS
  64381. */
  64382. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64383. var size = (options && options.facetNb) || 1;
  64384. var number = (options && options.number) || 0;
  64385. var delta = (options && options.delta) || 0;
  64386. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64387. var meshInd = mesh.getIndices();
  64388. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64389. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64390. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64391. var f = 0; // facet counter
  64392. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64393. // compute size from number
  64394. if (number) {
  64395. number = (number > totalFacets) ? totalFacets : number;
  64396. size = Math.round(totalFacets / number);
  64397. delta = 0;
  64398. }
  64399. else {
  64400. size = (size > totalFacets) ? totalFacets : size;
  64401. }
  64402. var facetPos = []; // submesh positions
  64403. var facetInd = []; // submesh indices
  64404. var facetUV = []; // submesh UV
  64405. var facetCol = []; // submesh colors
  64406. var barycenter = BABYLON.Vector3.Zero();
  64407. var sizeO = size;
  64408. while (f < totalFacets) {
  64409. size = sizeO + Math.floor((1 + delta) * Math.random());
  64410. if (f > totalFacets - size) {
  64411. size = totalFacets - f;
  64412. }
  64413. // reset temp arrays
  64414. facetPos.length = 0;
  64415. facetInd.length = 0;
  64416. facetUV.length = 0;
  64417. facetCol.length = 0;
  64418. // iterate over "size" facets
  64419. var fi = 0;
  64420. for (var j = f * 3; j < (f + size) * 3; j++) {
  64421. facetInd.push(fi);
  64422. var i = meshInd[j];
  64423. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64424. if (meshUV) {
  64425. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64426. }
  64427. if (meshCol) {
  64428. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64429. }
  64430. fi++;
  64431. }
  64432. // create a model shape for each single particle
  64433. var idx = this.nbParticles;
  64434. var shape = this._posToShape(facetPos);
  64435. var shapeUV = this._uvsToShapeUV(facetUV);
  64436. // compute the barycenter of the shape
  64437. var v;
  64438. for (v = 0; v < shape.length; v++) {
  64439. barycenter.addInPlace(shape[v]);
  64440. }
  64441. barycenter.scaleInPlace(1 / shape.length);
  64442. // shift the shape from its barycenter to the origin
  64443. for (v = 0; v < shape.length; v++) {
  64444. shape[v].subtractInPlace(barycenter);
  64445. }
  64446. var bInfo;
  64447. if (this._particlesIntersect) {
  64448. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64449. }
  64450. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64451. // add the particle in the SPS
  64452. var currentPos = this._positions.length;
  64453. var currentInd = this._indices.length;
  64454. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64455. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64456. // initialize the particle position
  64457. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64458. this._index += shape.length;
  64459. idx++;
  64460. this.nbParticles++;
  64461. this._shapeCounter++;
  64462. f += size;
  64463. }
  64464. return this;
  64465. };
  64466. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64467. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64468. var index = 0;
  64469. var idx = 0;
  64470. for (var p = 0; p < this.particles.length; p++) {
  64471. this._particle = this.particles[p];
  64472. this._shape = this._particle._model._shape;
  64473. if (this._particle.rotationQuaternion) {
  64474. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64475. }
  64476. else {
  64477. this._yaw = this._particle.rotation.y;
  64478. this._pitch = this._particle.rotation.x;
  64479. this._roll = this._particle.rotation.z;
  64480. this._quaternionRotationYPR();
  64481. }
  64482. this._quaternionToRotationMatrix();
  64483. this._rotMatrix.invertToRef(this._invertMatrix);
  64484. for (var pt = 0; pt < this._shape.length; pt++) {
  64485. idx = index + pt * 3;
  64486. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64487. this._fixedNormal32[idx] = this._normal.x;
  64488. this._fixedNormal32[idx + 1] = this._normal.y;
  64489. this._fixedNormal32[idx + 2] = this._normal.z;
  64490. }
  64491. index = idx + 3;
  64492. }
  64493. };
  64494. //reset copy
  64495. SolidParticleSystem.prototype._resetCopy = function () {
  64496. this._copy.position.x = 0;
  64497. this._copy.position.y = 0;
  64498. this._copy.position.z = 0;
  64499. this._copy.rotation.x = 0;
  64500. this._copy.rotation.y = 0;
  64501. this._copy.rotation.z = 0;
  64502. this._copy.rotationQuaternion = null;
  64503. this._copy.scaling.x = 1.0;
  64504. this._copy.scaling.y = 1.0;
  64505. this._copy.scaling.z = 1.0;
  64506. this._copy.uvs.x = 0;
  64507. this._copy.uvs.y = 0;
  64508. this._copy.uvs.z = 1.0;
  64509. this._copy.uvs.w = 1.0;
  64510. this._copy.color = null;
  64511. this._copy.translateFromPivot = false;
  64512. };
  64513. // _meshBuilder : inserts the shape model in the global SPS mesh
  64514. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64515. var i;
  64516. var u = 0;
  64517. var c = 0;
  64518. var n = 0;
  64519. this._resetCopy();
  64520. if (options && options.positionFunction) { // call to custom positionFunction
  64521. options.positionFunction(this._copy, idx, idxInShape);
  64522. this._mustUnrotateFixedNormals = true;
  64523. }
  64524. if (this._copy.rotationQuaternion) {
  64525. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64526. }
  64527. else {
  64528. this._yaw = this._copy.rotation.y;
  64529. this._pitch = this._copy.rotation.x;
  64530. this._roll = this._copy.rotation.z;
  64531. this._quaternionRotationYPR();
  64532. }
  64533. this._quaternionToRotationMatrix();
  64534. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64535. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64536. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64537. if (this._copy.translateFromPivot) {
  64538. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64539. }
  64540. else {
  64541. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64542. }
  64543. for (i = 0; i < shape.length; i++) {
  64544. this._vertex.x = shape[i].x;
  64545. this._vertex.y = shape[i].y;
  64546. this._vertex.z = shape[i].z;
  64547. if (options && options.vertexFunction) {
  64548. options.vertexFunction(this._copy, this._vertex, i);
  64549. }
  64550. this._vertex.x *= this._copy.scaling.x;
  64551. this._vertex.y *= this._copy.scaling.y;
  64552. this._vertex.z *= this._copy.scaling.z;
  64553. this._vertex.x -= this._scaledPivot.x;
  64554. this._vertex.y -= this._scaledPivot.y;
  64555. this._vertex.z -= this._scaledPivot.z;
  64556. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64557. this._rotated.addInPlace(this._pivotBackTranslation);
  64558. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64559. if (meshUV) {
  64560. 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);
  64561. u += 2;
  64562. }
  64563. if (this._copy.color) {
  64564. this._color = this._copy.color;
  64565. }
  64566. else if (meshCol && meshCol[c] !== undefined) {
  64567. this._color.r = meshCol[c];
  64568. this._color.g = meshCol[c + 1];
  64569. this._color.b = meshCol[c + 2];
  64570. this._color.a = meshCol[c + 3];
  64571. }
  64572. else {
  64573. this._color.r = 1.0;
  64574. this._color.g = 1.0;
  64575. this._color.b = 1.0;
  64576. this._color.a = 1.0;
  64577. }
  64578. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64579. c += 4;
  64580. if (!this.recomputeNormals && meshNor) {
  64581. this._normal.x = meshNor[n];
  64582. this._normal.y = meshNor[n + 1];
  64583. this._normal.z = meshNor[n + 2];
  64584. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64585. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64586. n += 3;
  64587. }
  64588. }
  64589. for (i = 0; i < meshInd.length; i++) {
  64590. var current_ind = p + meshInd[i];
  64591. indices.push(current_ind);
  64592. if (current_ind > 65535) {
  64593. this._needs32Bits = true;
  64594. }
  64595. }
  64596. if (this._pickable) {
  64597. var nbfaces = meshInd.length / 3;
  64598. for (i = 0; i < nbfaces; i++) {
  64599. this.pickedParticles.push({ idx: idx, faceId: i });
  64600. }
  64601. }
  64602. if (this._depthSort) {
  64603. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64604. }
  64605. return this._copy;
  64606. };
  64607. // returns a shape array from positions array
  64608. SolidParticleSystem.prototype._posToShape = function (positions) {
  64609. var shape = [];
  64610. for (var i = 0; i < positions.length; i += 3) {
  64611. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64612. }
  64613. return shape;
  64614. };
  64615. // returns a shapeUV array from a Vector4 uvs
  64616. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64617. var shapeUV = [];
  64618. if (uvs) {
  64619. for (var i = 0; i < uvs.length; i++)
  64620. shapeUV.push(uvs[i]);
  64621. }
  64622. return shapeUV;
  64623. };
  64624. // adds a new particle object in the particles array
  64625. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64626. if (bInfo === void 0) { bInfo = null; }
  64627. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64628. this.particles.push(sp);
  64629. return sp;
  64630. };
  64631. /**
  64632. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64633. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64634. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64635. * @param nb (positive integer) the number of particles to be created from this model
  64636. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64637. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64638. * @returns the number of shapes in the system
  64639. */
  64640. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64641. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64642. var meshInd = mesh.getIndices();
  64643. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64644. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64645. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64646. var bbInfo;
  64647. if (this._particlesIntersect) {
  64648. bbInfo = mesh.getBoundingInfo();
  64649. }
  64650. var shape = this._posToShape(meshPos);
  64651. var shapeUV = this._uvsToShapeUV(meshUV);
  64652. var posfunc = options ? options.positionFunction : null;
  64653. var vtxfunc = options ? options.vertexFunction : null;
  64654. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64655. // particles
  64656. var sp;
  64657. var currentCopy;
  64658. var idx = this.nbParticles;
  64659. for (var i = 0; i < nb; i++) {
  64660. var currentPos = this._positions.length;
  64661. var currentInd = this._indices.length;
  64662. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64663. if (this._updatable) {
  64664. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64665. sp.position.copyFrom(currentCopy.position);
  64666. sp.rotation.copyFrom(currentCopy.rotation);
  64667. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64668. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64669. }
  64670. if (currentCopy.color && sp.color) {
  64671. sp.color.copyFrom(currentCopy.color);
  64672. }
  64673. sp.scaling.copyFrom(currentCopy.scaling);
  64674. sp.uvs.copyFrom(currentCopy.uvs);
  64675. }
  64676. this._index += shape.length;
  64677. idx++;
  64678. }
  64679. this.nbParticles += nb;
  64680. this._shapeCounter++;
  64681. return this._shapeCounter - 1;
  64682. };
  64683. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  64684. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  64685. this._resetCopy();
  64686. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  64687. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  64688. }
  64689. if (this._copy.rotationQuaternion) {
  64690. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64691. }
  64692. else {
  64693. this._yaw = this._copy.rotation.y;
  64694. this._pitch = this._copy.rotation.x;
  64695. this._roll = this._copy.rotation.z;
  64696. this._quaternionRotationYPR();
  64697. }
  64698. this._quaternionToRotationMatrix();
  64699. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64700. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64701. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64702. if (this._copy.translateFromPivot) {
  64703. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64704. }
  64705. else {
  64706. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64707. }
  64708. this._shape = particle._model._shape;
  64709. for (var pt = 0; pt < this._shape.length; pt++) {
  64710. this._vertex.x = this._shape[pt].x;
  64711. this._vertex.y = this._shape[pt].y;
  64712. this._vertex.z = this._shape[pt].z;
  64713. if (particle._model._vertexFunction) {
  64714. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  64715. }
  64716. this._vertex.x *= this._copy.scaling.x;
  64717. this._vertex.y *= this._copy.scaling.y;
  64718. this._vertex.z *= this._copy.scaling.z;
  64719. this._vertex.x -= this._scaledPivot.x;
  64720. this._vertex.y -= this._scaledPivot.y;
  64721. this._vertex.z -= this._scaledPivot.z;
  64722. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64723. this._rotated.addInPlace(this._pivotBackTranslation);
  64724. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  64725. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  64726. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  64727. }
  64728. particle.position.x = 0.0;
  64729. particle.position.y = 0.0;
  64730. particle.position.z = 0.0;
  64731. particle.rotation.x = 0.0;
  64732. particle.rotation.y = 0.0;
  64733. particle.rotation.z = 0.0;
  64734. particle.rotationQuaternion = null;
  64735. particle.scaling.x = 1.0;
  64736. particle.scaling.y = 1.0;
  64737. particle.scaling.z = 1.0;
  64738. particle.uvs.x = 0.0;
  64739. particle.uvs.y = 0.0;
  64740. particle.uvs.z = 1.0;
  64741. particle.uvs.w = 1.0;
  64742. particle.pivot.x = 0.0;
  64743. particle.pivot.y = 0.0;
  64744. particle.pivot.z = 0.0;
  64745. particle.translateFromPivot = false;
  64746. particle.parentId = null;
  64747. };
  64748. /**
  64749. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  64750. * @returns the SPS.
  64751. */
  64752. SolidParticleSystem.prototype.rebuildMesh = function () {
  64753. for (var p = 0; p < this.particles.length; p++) {
  64754. this._rebuildParticle(this.particles[p]);
  64755. }
  64756. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64757. return this;
  64758. };
  64759. /**
  64760. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  64761. * This method calls `updateParticle()` for each particle of the SPS.
  64762. * For an animated SPS, it is usually called within the render loop.
  64763. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  64764. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  64765. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  64766. * @returns the SPS.
  64767. */
  64768. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  64769. if (start === void 0) { start = 0; }
  64770. if (end === void 0) { end = this.nbParticles - 1; }
  64771. if (update === void 0) { update = true; }
  64772. if (!this._updatable) {
  64773. return this;
  64774. }
  64775. // custom beforeUpdate
  64776. this.beforeUpdateParticles(start, end, update);
  64777. this._cam_axisX.x = 1.0;
  64778. this._cam_axisX.y = 0.0;
  64779. this._cam_axisX.z = 0.0;
  64780. this._cam_axisY.x = 0.0;
  64781. this._cam_axisY.y = 1.0;
  64782. this._cam_axisY.z = 0.0;
  64783. this._cam_axisZ.x = 0.0;
  64784. this._cam_axisZ.y = 0.0;
  64785. this._cam_axisZ.z = 1.0;
  64786. // cases when the World Matrix is to be computed first
  64787. if (this.billboard || this._depthSort) {
  64788. this.mesh.computeWorldMatrix(true);
  64789. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  64790. }
  64791. // if the particles will always face the camera
  64792. if (this.billboard) {
  64793. // compute the camera position and un-rotate it by the current mesh rotation
  64794. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  64795. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  64796. this._cam_axisZ.normalize();
  64797. // same for camera up vector extracted from the cam view matrix
  64798. var view = this._camera.getViewMatrix(true);
  64799. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  64800. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  64801. this._cam_axisY.normalize();
  64802. this._cam_axisX.normalize();
  64803. }
  64804. // if depthSort, compute the camera global position in the mesh local system
  64805. if (this._depthSort) {
  64806. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  64807. }
  64808. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  64809. var idx = 0; // current position index in the global array positions32
  64810. var index = 0; // position start index in the global array positions32 of the current particle
  64811. var colidx = 0; // current color index in the global array colors32
  64812. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  64813. var uvidx = 0; // current uv index in the global array uvs32
  64814. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  64815. var pt = 0; // current index in the particle model shape
  64816. if (this.mesh.isFacetDataEnabled) {
  64817. this._computeBoundingBox = true;
  64818. }
  64819. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  64820. if (this._computeBoundingBox) {
  64821. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  64822. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  64823. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  64824. }
  64825. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  64826. if (this.mesh._boundingInfo) {
  64827. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  64828. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  64829. }
  64830. }
  64831. }
  64832. // particle loop
  64833. index = this.particles[start]._pos;
  64834. var vpos = (index / 3) | 0;
  64835. colorIndex = vpos * 4;
  64836. uvIndex = vpos * 2;
  64837. for (var p = start; p <= end; p++) {
  64838. this._particle = this.particles[p];
  64839. this._shape = this._particle._model._shape;
  64840. this._shapeUV = this._particle._model._shapeUV;
  64841. // call to custom user function to update the particle properties
  64842. this.updateParticle(this._particle);
  64843. // camera-particle distance for depth sorting
  64844. if (this._depthSort && this._depthSortParticles) {
  64845. var dsp = this.depthSortedParticles[p];
  64846. dsp.ind = this._particle._ind;
  64847. dsp.indicesLength = this._particle._model._indicesLength;
  64848. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  64849. }
  64850. // skip the computations for inactive or already invisible particles
  64851. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  64852. // increment indexes for the next particle
  64853. pt = this._shape.length;
  64854. index += pt * 3;
  64855. colorIndex += pt * 4;
  64856. uvIndex += pt * 2;
  64857. continue;
  64858. }
  64859. if (this._particle.isVisible) {
  64860. this._particle._stillInvisible = false; // un-mark permanent invisibility
  64861. this._particleHasParent = (this._particle.parentId !== null);
  64862. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64863. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64864. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64865. // particle rotation matrix
  64866. if (this.billboard) {
  64867. this._particle.rotation.x = 0.0;
  64868. this._particle.rotation.y = 0.0;
  64869. }
  64870. if (this._computeParticleRotation || this.billboard) {
  64871. if (this._particle.rotationQuaternion) {
  64872. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64873. }
  64874. else {
  64875. this._yaw = this._particle.rotation.y;
  64876. this._pitch = this._particle.rotation.x;
  64877. this._roll = this._particle.rotation.z;
  64878. this._quaternionRotationYPR();
  64879. }
  64880. this._quaternionToRotationMatrix();
  64881. }
  64882. if (this._particleHasParent) {
  64883. this._parent = this.particles[this._particle.parentId];
  64884. 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];
  64885. 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];
  64886. 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];
  64887. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  64888. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  64889. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  64890. if (this._computeParticleRotation || this.billboard) {
  64891. 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];
  64892. 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];
  64893. 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];
  64894. 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];
  64895. 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];
  64896. 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];
  64897. 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];
  64898. 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];
  64899. 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];
  64900. }
  64901. }
  64902. else {
  64903. this._particle._globalPosition.x = this._particle.position.x;
  64904. this._particle._globalPosition.y = this._particle.position.y;
  64905. this._particle._globalPosition.z = this._particle.position.z;
  64906. if (this._computeParticleRotation || this.billboard) {
  64907. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  64908. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  64909. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  64910. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  64911. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  64912. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  64913. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  64914. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  64915. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  64916. }
  64917. }
  64918. if (this._particle.translateFromPivot) {
  64919. this._pivotBackTranslation.x = 0.0;
  64920. this._pivotBackTranslation.y = 0.0;
  64921. this._pivotBackTranslation.z = 0.0;
  64922. }
  64923. else {
  64924. this._pivotBackTranslation.x = this._scaledPivot.x;
  64925. this._pivotBackTranslation.y = this._scaledPivot.y;
  64926. this._pivotBackTranslation.z = this._scaledPivot.z;
  64927. }
  64928. // particle vertex loop
  64929. for (pt = 0; pt < this._shape.length; pt++) {
  64930. idx = index + pt * 3;
  64931. colidx = colorIndex + pt * 4;
  64932. uvidx = uvIndex + pt * 2;
  64933. this._vertex.x = this._shape[pt].x;
  64934. this._vertex.y = this._shape[pt].y;
  64935. this._vertex.z = this._shape[pt].z;
  64936. if (this._computeParticleVertex) {
  64937. this.updateParticleVertex(this._particle, this._vertex, pt);
  64938. }
  64939. // positions
  64940. this._vertex.x *= this._particle.scaling.x;
  64941. this._vertex.y *= this._particle.scaling.y;
  64942. this._vertex.z *= this._particle.scaling.z;
  64943. this._vertex.x -= this._scaledPivot.x;
  64944. this._vertex.y -= this._scaledPivot.y;
  64945. this._vertex.z -= this._scaledPivot.z;
  64946. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64947. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64948. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64949. this._rotated.x += this._pivotBackTranslation.x;
  64950. this._rotated.y += this._pivotBackTranslation.y;
  64951. this._rotated.z += this._pivotBackTranslation.z;
  64952. 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;
  64953. 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;
  64954. 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;
  64955. if (this._computeBoundingBox) {
  64956. if (this._positions32[idx] < this._minimum.x) {
  64957. this._minimum.x = this._positions32[idx];
  64958. }
  64959. if (this._positions32[idx] > this._maximum.x) {
  64960. this._maximum.x = this._positions32[idx];
  64961. }
  64962. if (this._positions32[idx + 1] < this._minimum.y) {
  64963. this._minimum.y = this._positions32[idx + 1];
  64964. }
  64965. if (this._positions32[idx + 1] > this._maximum.y) {
  64966. this._maximum.y = this._positions32[idx + 1];
  64967. }
  64968. if (this._positions32[idx + 2] < this._minimum.z) {
  64969. this._minimum.z = this._positions32[idx + 2];
  64970. }
  64971. if (this._positions32[idx + 2] > this._maximum.z) {
  64972. this._maximum.z = this._positions32[idx + 2];
  64973. }
  64974. }
  64975. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  64976. if (!this._computeParticleVertex) {
  64977. this._normal.x = this._fixedNormal32[idx];
  64978. this._normal.y = this._fixedNormal32[idx + 1];
  64979. this._normal.z = this._fixedNormal32[idx + 2];
  64980. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  64981. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  64982. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  64983. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  64984. 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;
  64985. 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;
  64986. }
  64987. if (this._computeParticleColor && this._particle.color) {
  64988. this._colors32[colidx] = this._particle.color.r;
  64989. this._colors32[colidx + 1] = this._particle.color.g;
  64990. this._colors32[colidx + 2] = this._particle.color.b;
  64991. this._colors32[colidx + 3] = this._particle.color.a;
  64992. }
  64993. if (this._computeParticleTexture) {
  64994. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  64995. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  64996. }
  64997. }
  64998. }
  64999. // particle just set invisible : scaled to zero and positioned at the origin
  65000. else {
  65001. this._particle._stillInvisible = true; // mark the particle as invisible
  65002. for (pt = 0; pt < this._shape.length; pt++) {
  65003. idx = index + pt * 3;
  65004. colidx = colorIndex + pt * 4;
  65005. uvidx = uvIndex + pt * 2;
  65006. this._positions32[idx] = 0.0;
  65007. this._positions32[idx + 1] = 0.0;
  65008. this._positions32[idx + 2] = 0.0;
  65009. this._normals32[idx] = 0.0;
  65010. this._normals32[idx + 1] = 0.0;
  65011. this._normals32[idx + 2] = 0.0;
  65012. if (this._computeParticleColor && this._particle.color) {
  65013. this._colors32[colidx] = this._particle.color.r;
  65014. this._colors32[colidx + 1] = this._particle.color.g;
  65015. this._colors32[colidx + 2] = this._particle.color.b;
  65016. this._colors32[colidx + 3] = this._particle.color.a;
  65017. }
  65018. if (this._computeParticleTexture) {
  65019. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65020. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65021. }
  65022. }
  65023. }
  65024. // if the particle intersections must be computed : update the bbInfo
  65025. if (this._particlesIntersect) {
  65026. var bInfo = this._particle._boundingInfo;
  65027. var bBox = bInfo.boundingBox;
  65028. var bSphere = bInfo.boundingSphere;
  65029. if (!this._bSphereOnly) {
  65030. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65031. for (var b = 0; b < bBox.vectors.length; b++) {
  65032. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65033. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65034. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65035. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65036. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65037. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65038. 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;
  65039. 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;
  65040. 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;
  65041. }
  65042. bBox._update(this.mesh._worldMatrix);
  65043. }
  65044. // place and scale the particle bouding sphere in the SPS local system, then update it
  65045. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65046. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65047. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65048. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65049. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65050. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65051. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65052. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65053. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65054. 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));
  65055. bSphere._update(this.mesh._worldMatrix);
  65056. }
  65057. // increment indexes for the next particle
  65058. index = idx + 3;
  65059. colorIndex = colidx + 4;
  65060. uvIndex = uvidx + 2;
  65061. }
  65062. // if the VBO must be updated
  65063. if (update) {
  65064. if (this._computeParticleColor) {
  65065. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65066. }
  65067. if (this._computeParticleTexture) {
  65068. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65069. }
  65070. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65071. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65072. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65073. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65074. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65075. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65076. for (var i = 0; i < this._normals32.length; i++) {
  65077. this._fixedNormal32[i] = this._normals32[i];
  65078. }
  65079. }
  65080. if (!this.mesh.areNormalsFrozen) {
  65081. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65082. }
  65083. }
  65084. if (this._depthSort && this._depthSortParticles) {
  65085. this.depthSortedParticles.sort(this._depthSortFunction);
  65086. var dspl = this.depthSortedParticles.length;
  65087. var sorted = 0;
  65088. var lind = 0;
  65089. var sind = 0;
  65090. var sid = 0;
  65091. for (sorted = 0; sorted < dspl; sorted++) {
  65092. lind = this.depthSortedParticles[sorted].indicesLength;
  65093. sind = this.depthSortedParticles[sorted].ind;
  65094. for (var i = 0; i < lind; i++) {
  65095. this._indices32[sid] = this._indices[sind + i];
  65096. sid++;
  65097. }
  65098. }
  65099. this.mesh.updateIndices(this._indices32);
  65100. }
  65101. }
  65102. if (this._computeBoundingBox) {
  65103. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65104. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65105. }
  65106. this.afterUpdateParticles(start, end, update);
  65107. return this;
  65108. };
  65109. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65110. this._halfroll = this._roll * 0.5;
  65111. this._halfpitch = this._pitch * 0.5;
  65112. this._halfyaw = this._yaw * 0.5;
  65113. this._sinRoll = Math.sin(this._halfroll);
  65114. this._cosRoll = Math.cos(this._halfroll);
  65115. this._sinPitch = Math.sin(this._halfpitch);
  65116. this._cosPitch = Math.cos(this._halfpitch);
  65117. this._sinYaw = Math.sin(this._halfyaw);
  65118. this._cosYaw = Math.cos(this._halfyaw);
  65119. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65120. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65121. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65122. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65123. };
  65124. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65125. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65126. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65127. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65128. this._rotMatrix.m[3] = 0;
  65129. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65130. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65131. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65132. this._rotMatrix.m[7] = 0;
  65133. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65134. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65135. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65136. this._rotMatrix.m[11] = 0;
  65137. this._rotMatrix.m[12] = 0;
  65138. this._rotMatrix.m[13] = 0;
  65139. this._rotMatrix.m[14] = 0;
  65140. this._rotMatrix.m[15] = 1.0;
  65141. };
  65142. /**
  65143. * Disposes the SPS.
  65144. */
  65145. SolidParticleSystem.prototype.dispose = function () {
  65146. this.mesh.dispose();
  65147. this.vars = null;
  65148. // drop references to internal big arrays for the GC
  65149. this._positions = null;
  65150. this._indices = null;
  65151. this._normals = null;
  65152. this._uvs = null;
  65153. this._colors = null;
  65154. this._indices32 = null;
  65155. this._positions32 = null;
  65156. this._normals32 = null;
  65157. this._fixedNormal32 = null;
  65158. this._uvs32 = null;
  65159. this._colors32 = null;
  65160. this.pickedParticles = null;
  65161. };
  65162. /**
  65163. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65164. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65165. * @returns the SPS.
  65166. */
  65167. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65168. if (!this._isVisibilityBoxLocked) {
  65169. this.mesh.refreshBoundingInfo();
  65170. }
  65171. return this;
  65172. };
  65173. /**
  65174. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65175. * @param size the size (float) of the visibility box
  65176. * note : this doesn't lock the SPS mesh bounding box.
  65177. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65178. */
  65179. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65180. var vis = size / 2;
  65181. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65182. };
  65183. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65184. /**
  65185. * Gets whether the SPS as always visible or not
  65186. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65187. */
  65188. get: function () {
  65189. return this._alwaysVisible;
  65190. },
  65191. /**
  65192. * Sets the SPS as always visible or not
  65193. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65194. */
  65195. set: function (val) {
  65196. this._alwaysVisible = val;
  65197. this.mesh.alwaysSelectAsActiveMesh = val;
  65198. },
  65199. enumerable: true,
  65200. configurable: true
  65201. });
  65202. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65203. /**
  65204. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65205. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65206. */
  65207. get: function () {
  65208. return this._isVisibilityBoxLocked;
  65209. },
  65210. /**
  65211. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65212. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65213. */
  65214. set: function (val) {
  65215. this._isVisibilityBoxLocked = val;
  65216. var boundingInfo = this.mesh.getBoundingInfo();
  65217. boundingInfo.isLocked = val;
  65218. },
  65219. enumerable: true,
  65220. configurable: true
  65221. });
  65222. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65223. /**
  65224. * Gets if `setParticles()` computes the particle rotations or not.
  65225. * Default value : true. The SPS is faster when it's set to false.
  65226. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65227. */
  65228. get: function () {
  65229. return this._computeParticleRotation;
  65230. },
  65231. /**
  65232. * Tells to `setParticles()` to compute the particle rotations or not.
  65233. * Default value : true. The SPS is faster when it's set to false.
  65234. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65235. */
  65236. set: function (val) {
  65237. this._computeParticleRotation = val;
  65238. },
  65239. enumerable: true,
  65240. configurable: true
  65241. });
  65242. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65243. /**
  65244. * Gets if `setParticles()` computes the particle colors or not.
  65245. * Default value : true. The SPS is faster when it's set to false.
  65246. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65247. */
  65248. get: function () {
  65249. return this._computeParticleColor;
  65250. },
  65251. /**
  65252. * Tells to `setParticles()` to compute the particle colors or not.
  65253. * Default value : true. The SPS is faster when it's set to false.
  65254. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65255. */
  65256. set: function (val) {
  65257. this._computeParticleColor = val;
  65258. },
  65259. enumerable: true,
  65260. configurable: true
  65261. });
  65262. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65263. /**
  65264. * Gets if `setParticles()` computes the particle textures or not.
  65265. * Default value : true. The SPS is faster when it's set to false.
  65266. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65267. */
  65268. get: function () {
  65269. return this._computeParticleTexture;
  65270. },
  65271. set: function (val) {
  65272. this._computeParticleTexture = val;
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65278. /**
  65279. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65280. * Default value : false. The SPS is faster when it's set to false.
  65281. * Note : the particle custom vertex positions aren't stored values.
  65282. */
  65283. get: function () {
  65284. return this._computeParticleVertex;
  65285. },
  65286. /**
  65287. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65288. * Default value : false. The SPS is faster when it's set to false.
  65289. * Note : the particle custom vertex positions aren't stored values.
  65290. */
  65291. set: function (val) {
  65292. this._computeParticleVertex = val;
  65293. },
  65294. enumerable: true,
  65295. configurable: true
  65296. });
  65297. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65298. /**
  65299. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65300. */
  65301. get: function () {
  65302. return this._computeBoundingBox;
  65303. },
  65304. /**
  65305. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65306. */
  65307. set: function (val) {
  65308. this._computeBoundingBox = val;
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65314. /**
  65315. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65316. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65317. * Default : `true`
  65318. */
  65319. get: function () {
  65320. return this._depthSortParticles;
  65321. },
  65322. /**
  65323. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65324. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65325. * Default : `true`
  65326. */
  65327. set: function (val) {
  65328. this._depthSortParticles = val;
  65329. },
  65330. enumerable: true,
  65331. configurable: true
  65332. });
  65333. // =======================================================================
  65334. // Particle behavior logic
  65335. // these following methods may be overwritten by the user to fit his needs
  65336. /**
  65337. * This function does nothing. It may be overwritten to set all the particle first values.
  65338. * The SPS doesn't call this function, you may have to call it by your own.
  65339. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65340. */
  65341. SolidParticleSystem.prototype.initParticles = function () {
  65342. };
  65343. /**
  65344. * This function does nothing. It may be overwritten to recycle a particle.
  65345. * The SPS doesn't call this function, you may have to call it by your own.
  65346. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65347. * @param particle The particle to recycle
  65348. * @returns the recycled particle
  65349. */
  65350. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65351. return particle;
  65352. };
  65353. /**
  65354. * Updates a particle : this function should be overwritten by the user.
  65355. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65356. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65357. * @example : just set a particle position or velocity and recycle conditions
  65358. * @param particle The particle to update
  65359. * @returns the updated particle
  65360. */
  65361. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65362. return particle;
  65363. };
  65364. /**
  65365. * Updates a vertex of a particle : it can be overwritten by the user.
  65366. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65367. * @param particle the current particle
  65368. * @param vertex the current index of the current particle
  65369. * @param pt the index of the current vertex in the particle shape
  65370. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65371. * @example : just set a vertex particle position
  65372. * @returns the updated vertex
  65373. */
  65374. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65375. return vertex;
  65376. };
  65377. /**
  65378. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65379. * This does nothing and may be overwritten by the user.
  65380. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65381. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65382. * @param update the boolean update value actually passed to setParticles()
  65383. */
  65384. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65385. };
  65386. /**
  65387. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65388. * This will be passed three parameters.
  65389. * This does nothing and may be overwritten by the user.
  65390. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65391. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65392. * @param update the boolean update value actually passed to setParticles()
  65393. */
  65394. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65395. };
  65396. return SolidParticleSystem;
  65397. }());
  65398. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65399. })(BABYLON || (BABYLON = {}));
  65400. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65401. var BABYLON;
  65402. (function (BABYLON) {
  65403. /**
  65404. * Class containing static functions to help procedurally build meshes
  65405. */
  65406. var MeshBuilder = /** @class */ (function () {
  65407. function MeshBuilder() {
  65408. }
  65409. MeshBuilder.updateSideOrientation = function (orientation) {
  65410. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65411. return BABYLON.Mesh.DOUBLESIDE;
  65412. }
  65413. if (orientation === undefined || orientation === null) {
  65414. return BABYLON.Mesh.FRONTSIDE;
  65415. }
  65416. return orientation;
  65417. };
  65418. /**
  65419. * Creates a box mesh
  65420. * * The parameter `size` sets the size (float) of each box side (default 1)
  65421. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65422. * * 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)
  65423. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65424. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65425. * * 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
  65426. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65427. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65428. * @param name defines the name of the mesh
  65429. * @param options defines the options used to create the mesh
  65430. * @param scene defines the hosting scene
  65431. * @returns the box mesh
  65432. */
  65433. MeshBuilder.CreateBox = function (name, options, scene) {
  65434. if (scene === void 0) { scene = null; }
  65435. var box = new BABYLON.Mesh(name, scene);
  65436. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65437. box._originalBuilderSideOrientation = options.sideOrientation;
  65438. var vertexData = BABYLON.VertexData.CreateBox(options);
  65439. vertexData.applyToMesh(box, options.updatable);
  65440. return box;
  65441. };
  65442. /**
  65443. * Creates a sphere mesh
  65444. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65445. * * 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`)
  65446. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65447. * * 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
  65448. * * 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)
  65449. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65450. * * 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
  65451. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65452. * @param name defines the name of the mesh
  65453. * @param options defines the options used to create the mesh
  65454. * @param scene defines the hosting scene
  65455. * @returns the sphere mesh
  65456. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65457. */
  65458. MeshBuilder.CreateSphere = function (name, options, scene) {
  65459. var sphere = new BABYLON.Mesh(name, scene);
  65460. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65461. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65462. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65463. vertexData.applyToMesh(sphere, options.updatable);
  65464. return sphere;
  65465. };
  65466. /**
  65467. * Creates a plane polygonal mesh. By default, this is a disc
  65468. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65469. * * 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
  65470. * * 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
  65471. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65472. * * 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
  65473. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65474. * @param name defines the name of the mesh
  65475. * @param options defines the options used to create the mesh
  65476. * @param scene defines the hosting scene
  65477. * @returns the plane polygonal mesh
  65478. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65479. */
  65480. MeshBuilder.CreateDisc = function (name, options, scene) {
  65481. if (scene === void 0) { scene = null; }
  65482. var disc = new BABYLON.Mesh(name, scene);
  65483. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65484. disc._originalBuilderSideOrientation = options.sideOrientation;
  65485. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65486. vertexData.applyToMesh(disc, options.updatable);
  65487. return disc;
  65488. };
  65489. /**
  65490. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65491. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65492. * * 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`)
  65493. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65494. * * 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
  65495. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65496. * * 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
  65497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65498. * @param name defines the name of the mesh
  65499. * @param options defines the options used to create the mesh
  65500. * @param scene defines the hosting scene
  65501. * @returns the icosahedron mesh
  65502. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65503. */
  65504. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65505. var sphere = new BABYLON.Mesh(name, scene);
  65506. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65507. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65508. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65509. vertexData.applyToMesh(sphere, options.updatable);
  65510. return sphere;
  65511. };
  65512. ;
  65513. /**
  65514. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65515. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65516. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65517. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65518. * * 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
  65519. * * 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
  65520. * * 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
  65521. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65522. * * 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
  65523. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65524. * * 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
  65525. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65526. * * 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
  65527. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65528. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65529. * @param name defines the name of the mesh
  65530. * @param options defines the options used to create the mesh
  65531. * @param scene defines the hosting scene
  65532. * @returns the ribbon mesh
  65533. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65534. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65535. */
  65536. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65537. if (scene === void 0) { scene = null; }
  65538. var pathArray = options.pathArray;
  65539. var closeArray = options.closeArray;
  65540. var closePath = options.closePath;
  65541. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65542. var instance = options.instance;
  65543. var updatable = options.updatable;
  65544. if (instance) { // existing ribbon instance update
  65545. // positionFunction : ribbon case
  65546. // only pathArray and sideOrientation parameters are taken into account for positions update
  65547. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65548. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65549. var positionFunction = function (positions) {
  65550. var minlg = pathArray[0].length;
  65551. var i = 0;
  65552. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65553. for (var si = 1; si <= ns; si++) {
  65554. for (var p = 0; p < pathArray.length; p++) {
  65555. var path = pathArray[p];
  65556. var l = path.length;
  65557. minlg = (minlg < l) ? minlg : l;
  65558. var j = 0;
  65559. while (j < minlg) {
  65560. positions[i] = path[j].x;
  65561. positions[i + 1] = path[j].y;
  65562. positions[i + 2] = path[j].z;
  65563. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65564. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65565. }
  65566. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65567. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65568. }
  65569. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65570. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65571. }
  65572. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65573. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65574. }
  65575. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65576. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65577. }
  65578. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65579. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65580. }
  65581. j++;
  65582. i += 3;
  65583. }
  65584. if (instance._closePath) {
  65585. positions[i] = path[0].x;
  65586. positions[i + 1] = path[0].y;
  65587. positions[i + 2] = path[0].z;
  65588. i += 3;
  65589. }
  65590. }
  65591. }
  65592. };
  65593. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65594. positionFunction(positions);
  65595. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65596. instance._boundingInfo.update(instance._worldMatrix);
  65597. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65598. if (options.colors) {
  65599. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65600. for (var c = 0; c < options.colors.length; c++) {
  65601. colors[c * 4] = options.colors[c].r;
  65602. colors[c * 4 + 1] = options.colors[c].g;
  65603. colors[c * 4 + 2] = options.colors[c].b;
  65604. colors[c * 4 + 3] = options.colors[c].a;
  65605. }
  65606. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65607. }
  65608. if (options.uvs) {
  65609. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65610. for (var i = 0; i < options.uvs.length; i++) {
  65611. uvs[i * 2] = options.uvs[i].x;
  65612. uvs[i * 2 + 1] = options.uvs[i].y;
  65613. }
  65614. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65615. }
  65616. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65617. var indices = instance.getIndices();
  65618. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65619. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65620. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65621. if (instance._closePath) {
  65622. var indexFirst = 0;
  65623. var indexLast = 0;
  65624. for (var p = 0; p < pathArray.length; p++) {
  65625. indexFirst = instance._idx[p] * 3;
  65626. if (p + 1 < pathArray.length) {
  65627. indexLast = (instance._idx[p + 1] - 1) * 3;
  65628. }
  65629. else {
  65630. indexLast = normals.length - 3;
  65631. }
  65632. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65633. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65634. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65635. normals[indexLast] = normals[indexFirst];
  65636. normals[indexLast + 1] = normals[indexFirst + 1];
  65637. normals[indexLast + 2] = normals[indexFirst + 2];
  65638. }
  65639. }
  65640. if (!(instance.areNormalsFrozen)) {
  65641. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65642. }
  65643. }
  65644. return instance;
  65645. }
  65646. else { // new ribbon creation
  65647. var ribbon = new BABYLON.Mesh(name, scene);
  65648. ribbon._originalBuilderSideOrientation = sideOrientation;
  65649. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65650. if (closePath) {
  65651. ribbon._idx = vertexData._idx;
  65652. }
  65653. ribbon._closePath = closePath;
  65654. ribbon._closeArray = closeArray;
  65655. vertexData.applyToMesh(ribbon, updatable);
  65656. return ribbon;
  65657. }
  65658. };
  65659. /**
  65660. * Creates a cylinder or a cone mesh
  65661. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65662. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65663. * * 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.
  65664. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65665. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65666. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65667. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65668. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65669. * * 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).
  65670. * * 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
  65671. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65672. * * 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
  65673. * * 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.
  65674. * * If `enclose` is false, a ring surface is one element.
  65675. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65676. * * 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
  65677. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65678. * * 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
  65679. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65680. * @param name defines the name of the mesh
  65681. * @param options defines the options used to create the mesh
  65682. * @param scene defines the hosting scene
  65683. * @returns the cylinder mesh
  65684. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  65685. */
  65686. MeshBuilder.CreateCylinder = function (name, options, scene) {
  65687. var cylinder = new BABYLON.Mesh(name, scene);
  65688. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65689. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  65690. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  65691. vertexData.applyToMesh(cylinder, options.updatable);
  65692. return cylinder;
  65693. };
  65694. /**
  65695. * Creates a torus mesh
  65696. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  65697. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  65698. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  65699. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65700. * * 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
  65701. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65702. * @param name defines the name of the mesh
  65703. * @param options defines the options used to create the mesh
  65704. * @param scene defines the hosting scene
  65705. * @returns the torus mesh
  65706. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  65707. */
  65708. MeshBuilder.CreateTorus = function (name, options, scene) {
  65709. var torus = new BABYLON.Mesh(name, scene);
  65710. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65711. torus._originalBuilderSideOrientation = options.sideOrientation;
  65712. var vertexData = BABYLON.VertexData.CreateTorus(options);
  65713. vertexData.applyToMesh(torus, options.updatable);
  65714. return torus;
  65715. };
  65716. /**
  65717. * Creates a torus knot mesh
  65718. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  65719. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  65720. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  65721. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  65722. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65723. * * 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
  65724. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65725. * @param name defines the name of the mesh
  65726. * @param options defines the options used to create the mesh
  65727. * @param scene defines the hosting scene
  65728. * @returns the torus knot mesh
  65729. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  65730. */
  65731. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  65732. var torusKnot = new BABYLON.Mesh(name, scene);
  65733. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65734. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  65735. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  65736. vertexData.applyToMesh(torusKnot, options.updatable);
  65737. return torusKnot;
  65738. };
  65739. /**
  65740. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  65741. * * 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
  65742. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  65743. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  65744. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  65745. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  65746. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  65747. * * 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
  65748. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  65749. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65750. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  65751. * @param name defines the name of the new line system
  65752. * @param options defines the options used to create the line system
  65753. * @param scene defines the hosting scene
  65754. * @returns a new line system mesh
  65755. */
  65756. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  65757. var instance = options.instance;
  65758. var lines = options.lines;
  65759. var colors = options.colors;
  65760. if (instance) { // lines update
  65761. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65762. var vertexColor;
  65763. var lineColors;
  65764. if (colors) {
  65765. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65766. }
  65767. var i = 0;
  65768. var c = 0;
  65769. for (var l = 0; l < lines.length; l++) {
  65770. var points = lines[l];
  65771. for (var p = 0; p < points.length; p++) {
  65772. positions[i] = points[p].x;
  65773. positions[i + 1] = points[p].y;
  65774. positions[i + 2] = points[p].z;
  65775. if (colors && vertexColor) {
  65776. lineColors = colors[l];
  65777. vertexColor[c] = lineColors[p].r;
  65778. vertexColor[c + 1] = lineColors[p].g;
  65779. vertexColor[c + 2] = lineColors[p].b;
  65780. vertexColor[c + 3] = lineColors[p].a;
  65781. c += 4;
  65782. }
  65783. i += 3;
  65784. }
  65785. }
  65786. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65787. if (colors && vertexColor) {
  65788. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  65789. }
  65790. return instance;
  65791. }
  65792. // line system creation
  65793. var useVertexColor = (colors) ? true : false;
  65794. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  65795. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  65796. vertexData.applyToMesh(lineSystem, options.updatable);
  65797. return lineSystem;
  65798. };
  65799. /**
  65800. * Creates a line mesh
  65801. * 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
  65802. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65803. * * The parameter `points` is an array successive Vector3
  65804. * * 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
  65805. * * The optional parameter `colors` is an array of successive Color4, one per line point
  65806. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  65807. * * When updating an instance, remember that only point positions can change, not the number of points
  65808. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65809. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  65810. * @param name defines the name of the new line system
  65811. * @param options defines the options used to create the line system
  65812. * @param scene defines the hosting scene
  65813. * @returns a new line mesh
  65814. */
  65815. MeshBuilder.CreateLines = function (name, options, scene) {
  65816. if (scene === void 0) { scene = null; }
  65817. var colors = (options.colors) ? [options.colors] : null;
  65818. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  65819. return lines;
  65820. };
  65821. /**
  65822. * Creates a dashed line mesh
  65823. * * 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
  65824. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65825. * * The parameter `points` is an array successive Vector3
  65826. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  65827. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  65828. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  65829. * * 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
  65830. * * When updating an instance, remember that only point positions can change, not the number of points
  65831. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65832. * @param name defines the name of the mesh
  65833. * @param options defines the options used to create the mesh
  65834. * @param scene defines the hosting scene
  65835. * @returns the dashed line mesh
  65836. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  65837. */
  65838. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  65839. if (scene === void 0) { scene = null; }
  65840. var points = options.points;
  65841. var instance = options.instance;
  65842. var gapSize = options.gapSize || 1;
  65843. var dashSize = options.dashSize || 3;
  65844. if (instance) { // dashed lines update
  65845. var positionFunction = function (positions) {
  65846. var curvect = BABYLON.Vector3.Zero();
  65847. var nbSeg = positions.length / 6;
  65848. var lg = 0;
  65849. var nb = 0;
  65850. var shft = 0;
  65851. var dashshft = 0;
  65852. var curshft = 0;
  65853. var p = 0;
  65854. var i = 0;
  65855. var j = 0;
  65856. for (i = 0; i < points.length - 1; i++) {
  65857. points[i + 1].subtractToRef(points[i], curvect);
  65858. lg += curvect.length();
  65859. }
  65860. shft = lg / nbSeg;
  65861. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  65862. for (i = 0; i < points.length - 1; i++) {
  65863. points[i + 1].subtractToRef(points[i], curvect);
  65864. nb = Math.floor(curvect.length() / shft);
  65865. curvect.normalize();
  65866. j = 0;
  65867. while (j < nb && p < positions.length) {
  65868. curshft = shft * j;
  65869. positions[p] = points[i].x + curshft * curvect.x;
  65870. positions[p + 1] = points[i].y + curshft * curvect.y;
  65871. positions[p + 2] = points[i].z + curshft * curvect.z;
  65872. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  65873. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  65874. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  65875. p += 6;
  65876. j++;
  65877. }
  65878. }
  65879. while (p < positions.length) {
  65880. positions[p] = points[i].x;
  65881. positions[p + 1] = points[i].y;
  65882. positions[p + 2] = points[i].z;
  65883. p += 3;
  65884. }
  65885. };
  65886. instance.updateMeshPositions(positionFunction, false);
  65887. return instance;
  65888. }
  65889. // dashed lines creation
  65890. var dashedLines = new BABYLON.LinesMesh(name, scene);
  65891. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  65892. vertexData.applyToMesh(dashedLines, options.updatable);
  65893. dashedLines.dashSize = dashSize;
  65894. dashedLines.gapSize = gapSize;
  65895. return dashedLines;
  65896. };
  65897. /**
  65898. * 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.
  65899. * * 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.
  65900. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65901. * * 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.
  65902. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  65903. * * 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
  65904. * * 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
  65905. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  65906. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65907. * * 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
  65908. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  65909. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65910. * @param name defines the name of the mesh
  65911. * @param options defines the options used to create the mesh
  65912. * @param scene defines the hosting scene
  65913. * @returns the extruded shape mesh
  65914. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65915. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65916. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65917. */
  65918. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  65919. if (scene === void 0) { scene = null; }
  65920. var path = options.path;
  65921. var shape = options.shape;
  65922. var scale = options.scale || 1;
  65923. var rotation = options.rotation || 0;
  65924. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65925. var updatable = options.updatable;
  65926. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65927. var instance = options.instance || null;
  65928. var invertUV = options.invertUV || false;
  65929. 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);
  65930. };
  65931. /**
  65932. * Creates an custom extruded shape mesh.
  65933. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65934. * * 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.
  65935. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65936. * * 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
  65937. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  65938. * * 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
  65939. * * It must returns a float value that will be the scale value applied to the shape on each path point
  65940. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  65941. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  65942. * * 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
  65943. * * 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
  65944. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  65945. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65946. * * 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
  65947. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65948. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65949. * @param name defines the name of the mesh
  65950. * @param options defines the options used to create the mesh
  65951. * @param scene defines the hosting scene
  65952. * @returns the custom extruded shape mesh
  65953. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  65954. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65955. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65956. */
  65957. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  65958. var path = options.path;
  65959. var shape = options.shape;
  65960. var scaleFunction = options.scaleFunction || (function () { return 1; });
  65961. var rotationFunction = options.rotationFunction || (function () { return 0; });
  65962. var ribbonCloseArray = options.ribbonCloseArray || false;
  65963. var ribbonClosePath = options.ribbonClosePath || false;
  65964. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65965. var updatable = options.updatable;
  65966. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65967. var instance = options.instance;
  65968. var invertUV = options.invertUV || false;
  65969. 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);
  65970. };
  65971. /**
  65972. * Creates lathe mesh.
  65973. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  65974. * * 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
  65975. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  65976. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  65977. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  65978. * * 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
  65979. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  65980. * * 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
  65981. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65982. * * 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
  65983. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65984. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65985. * @param name defines the name of the mesh
  65986. * @param options defines the options used to create the mesh
  65987. * @param scene defines the hosting scene
  65988. * @returns the lathe mesh
  65989. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  65990. */
  65991. MeshBuilder.CreateLathe = function (name, options, scene) {
  65992. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  65993. var closed = (options.closed === undefined) ? true : options.closed;
  65994. var shape = options.shape;
  65995. var radius = options.radius || 1;
  65996. var tessellation = options.tessellation || 64;
  65997. var clip = options.clip || 0;
  65998. var updatable = options.updatable;
  65999. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66000. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66001. var pi2 = Math.PI * 2;
  66002. var paths = new Array();
  66003. var invertUV = options.invertUV || false;
  66004. var i = 0;
  66005. var p = 0;
  66006. var step = pi2 / tessellation * arc;
  66007. var rotated;
  66008. var path = new Array();
  66009. for (i = 0; i <= tessellation - clip; i++) {
  66010. var path = [];
  66011. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66012. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66013. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66014. }
  66015. for (p = 0; p < shape.length; p++) {
  66016. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66017. path.push(rotated);
  66018. }
  66019. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66020. 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));
  66021. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66022. }
  66023. paths.push(path);
  66024. }
  66025. // lathe ribbon
  66026. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66027. return lathe;
  66028. };
  66029. /**
  66030. * Creates a plane mesh
  66031. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66032. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66033. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66034. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66035. * * 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
  66036. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66037. * @param name defines the name of the mesh
  66038. * @param options defines the options used to create the mesh
  66039. * @param scene defines the hosting scene
  66040. * @returns the plane mesh
  66041. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66042. */
  66043. MeshBuilder.CreatePlane = function (name, options, scene) {
  66044. var plane = new BABYLON.Mesh(name, scene);
  66045. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66046. plane._originalBuilderSideOrientation = options.sideOrientation;
  66047. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66048. vertexData.applyToMesh(plane, options.updatable);
  66049. if (options.sourcePlane) {
  66050. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66051. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66052. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66053. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66054. plane.rotate(vectorProduct, product);
  66055. }
  66056. }
  66057. return plane;
  66058. };
  66059. /**
  66060. * Creates a ground mesh
  66061. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66062. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66064. * @param name defines the name of the mesh
  66065. * @param options defines the options used to create the mesh
  66066. * @param scene defines the hosting scene
  66067. * @returns the ground mesh
  66068. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66069. */
  66070. MeshBuilder.CreateGround = function (name, options, scene) {
  66071. var ground = new BABYLON.GroundMesh(name, scene);
  66072. ground._setReady(false);
  66073. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66074. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66075. ground._width = options.width || 1;
  66076. ground._height = options.height || 1;
  66077. ground._maxX = ground._width / 2;
  66078. ground._maxZ = ground._height / 2;
  66079. ground._minX = -ground._maxX;
  66080. ground._minZ = -ground._maxZ;
  66081. var vertexData = BABYLON.VertexData.CreateGround(options);
  66082. vertexData.applyToMesh(ground, options.updatable);
  66083. ground._setReady(true);
  66084. return ground;
  66085. };
  66086. /**
  66087. * Creates a tiled ground mesh
  66088. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66089. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66090. * * 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
  66091. * * 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
  66092. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66093. * @param name defines the name of the mesh
  66094. * @param options defines the options used to create the mesh
  66095. * @param scene defines the hosting scene
  66096. * @returns the tiled ground mesh
  66097. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66098. */
  66099. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66100. var tiledGround = new BABYLON.Mesh(name, scene);
  66101. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66102. vertexData.applyToMesh(tiledGround, options.updatable);
  66103. return tiledGround;
  66104. };
  66105. /**
  66106. * Creates a ground mesh from a height map
  66107. * * The parameter `url` sets the URL of the height map image resource.
  66108. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66109. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66110. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66111. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66112. * * 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.
  66113. * * 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).
  66114. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66115. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66116. * @param name defines the name of the mesh
  66117. * @param url defines the url to the height map
  66118. * @param options defines the options used to create the mesh
  66119. * @param scene defines the hosting scene
  66120. * @returns the ground mesh
  66121. * @see http://doc.babylonjs.com/babylon101/height_map
  66122. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66123. */
  66124. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66125. var width = options.width || 10.0;
  66126. var height = options.height || 10.0;
  66127. var subdivisions = options.subdivisions || 1 | 0;
  66128. var minHeight = options.minHeight || 0.0;
  66129. var maxHeight = options.maxHeight || 1.0;
  66130. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66131. var alphaFilter = options.alphaFilter || 0.0;
  66132. var updatable = options.updatable;
  66133. var onReady = options.onReady;
  66134. var ground = new BABYLON.GroundMesh(name, scene);
  66135. ground._subdivisionsX = subdivisions;
  66136. ground._subdivisionsY = subdivisions;
  66137. ground._width = width;
  66138. ground._height = height;
  66139. ground._maxX = ground._width / 2.0;
  66140. ground._maxZ = ground._height / 2.0;
  66141. ground._minX = -ground._maxX;
  66142. ground._minZ = -ground._maxZ;
  66143. ground._setReady(false);
  66144. var onload = function (img) {
  66145. // Getting height map data
  66146. var canvas = document.createElement("canvas");
  66147. var context = canvas.getContext("2d");
  66148. if (!context) {
  66149. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66150. }
  66151. if (scene.isDisposed) {
  66152. return;
  66153. }
  66154. var bufferWidth = img.width;
  66155. var bufferHeight = img.height;
  66156. canvas.width = bufferWidth;
  66157. canvas.height = bufferHeight;
  66158. context.drawImage(img, 0, 0);
  66159. // Create VertexData from map data
  66160. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66161. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66162. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66163. width: width, height: height,
  66164. subdivisions: subdivisions,
  66165. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66166. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66167. alphaFilter: alphaFilter
  66168. });
  66169. vertexData.applyToMesh(ground, updatable);
  66170. //execute ready callback, if set
  66171. if (onReady) {
  66172. onReady(ground);
  66173. }
  66174. ground._setReady(true);
  66175. };
  66176. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66177. return ground;
  66178. };
  66179. /**
  66180. * Creates a polygon mesh
  66181. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66182. * * 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
  66183. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66184. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66185. * * 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)
  66186. * * Remember you can only change the shape positions, not their number when updating a polygon
  66187. * @param name defines the name of the mesh
  66188. * @param options defines the options used to create the mesh
  66189. * @param scene defines the hosting scene
  66190. * @returns the polygon mesh
  66191. */
  66192. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66194. var shape = options.shape;
  66195. var holes = options.holes || [];
  66196. var depth = options.depth || 0;
  66197. var contours = [];
  66198. var hole = [];
  66199. for (var i = 0; i < shape.length; i++) {
  66200. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66201. }
  66202. var epsilon = 0.00000001;
  66203. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66204. contours.pop();
  66205. }
  66206. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66207. for (var hNb = 0; hNb < holes.length; hNb++) {
  66208. hole = [];
  66209. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66210. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66211. }
  66212. polygonTriangulation.addHole(hole);
  66213. }
  66214. var polygon = polygonTriangulation.build(options.updatable, depth);
  66215. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66216. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66217. vertexData.applyToMesh(polygon, options.updatable);
  66218. return polygon;
  66219. };
  66220. ;
  66221. /**
  66222. * Creates an extruded polygon mesh, with depth in the Y direction.
  66223. * * 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)
  66224. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66225. * @param name defines the name of the mesh
  66226. * @param options defines the options used to create the mesh
  66227. * @param scene defines the hosting scene
  66228. * @returns the polygon mesh
  66229. */
  66230. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66231. return MeshBuilder.CreatePolygon(name, options, scene);
  66232. };
  66233. ;
  66234. /**
  66235. * Creates a tube mesh.
  66236. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66237. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66238. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66239. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66240. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66241. * * 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)
  66242. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66243. * * 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
  66244. * * 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
  66245. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66246. * * 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
  66247. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66248. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66249. * @param name defines the name of the mesh
  66250. * @param options defines the options used to create the mesh
  66251. * @param scene defines the hosting scene
  66252. * @returns the tube mesh
  66253. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66254. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66255. */
  66256. MeshBuilder.CreateTube = function (name, options, scene) {
  66257. var path = options.path;
  66258. var instance = options.instance;
  66259. var radius = 1.0;
  66260. if (instance) {
  66261. radius = instance.radius;
  66262. }
  66263. if (options.radius !== undefined) {
  66264. radius = options.radius;
  66265. }
  66266. ;
  66267. var tessellation = options.tessellation || 64 | 0;
  66268. var radiusFunction = options.radiusFunction || null;
  66269. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66270. var invertUV = options.invertUV || false;
  66271. var updatable = options.updatable;
  66272. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66273. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66274. // tube geometry
  66275. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66276. var tangents = path3D.getTangents();
  66277. var normals = path3D.getNormals();
  66278. var distances = path3D.getDistances();
  66279. var pi2 = Math.PI * 2;
  66280. var step = pi2 / tessellation * arc;
  66281. var returnRadius = function () { return radius; };
  66282. var radiusFunctionFinal = radiusFunction || returnRadius;
  66283. var circlePath;
  66284. var rad;
  66285. var normal;
  66286. var rotated;
  66287. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66288. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66289. for (var i = 0; i < path.length; i++) {
  66290. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66291. circlePath = Array(); // current circle array
  66292. normal = normals[i]; // current normal
  66293. for (var t = 0; t < tessellation; t++) {
  66294. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66295. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66296. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66297. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66298. circlePath[t] = rotated;
  66299. }
  66300. circlePaths[index] = circlePath;
  66301. index++;
  66302. }
  66303. // cap
  66304. var capPath = function (nbPoints, pathIndex) {
  66305. var pointCap = Array();
  66306. for (var i = 0; i < nbPoints; i++) {
  66307. pointCap.push(path[pathIndex]);
  66308. }
  66309. return pointCap;
  66310. };
  66311. switch (cap) {
  66312. case BABYLON.Mesh.NO_CAP:
  66313. break;
  66314. case BABYLON.Mesh.CAP_START:
  66315. circlePaths[0] = capPath(tessellation, 0);
  66316. circlePaths[1] = circlePaths[2].slice(0);
  66317. break;
  66318. case BABYLON.Mesh.CAP_END:
  66319. circlePaths[index] = circlePaths[index - 1].slice(0);
  66320. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66321. break;
  66322. case BABYLON.Mesh.CAP_ALL:
  66323. circlePaths[0] = capPath(tessellation, 0);
  66324. circlePaths[1] = circlePaths[2].slice(0);
  66325. circlePaths[index] = circlePaths[index - 1].slice(0);
  66326. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66327. break;
  66328. default:
  66329. break;
  66330. }
  66331. return circlePaths;
  66332. };
  66333. var path3D;
  66334. var pathArray;
  66335. if (instance) { // tube update
  66336. var arc = options.arc || instance.arc;
  66337. path3D = (instance.path3D).update(path);
  66338. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66339. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66340. instance.path3D = path3D;
  66341. instance.pathArray = pathArray;
  66342. instance.arc = arc;
  66343. instance.radius = radius;
  66344. return instance;
  66345. }
  66346. // tube creation
  66347. path3D = new BABYLON.Path3D(path);
  66348. var newPathArray = new Array();
  66349. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66350. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66351. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66352. tube.pathArray = pathArray;
  66353. tube.path3D = path3D;
  66354. tube.tessellation = tessellation;
  66355. tube.cap = cap;
  66356. tube.arc = options.arc;
  66357. tube.radius = radius;
  66358. return tube;
  66359. };
  66360. /**
  66361. * Creates a polyhedron mesh
  66362. * * 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
  66363. * * The parameter `size` (positive float, default 1) sets the polygon size
  66364. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66365. * * 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`
  66366. * * 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
  66367. * * 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)`)
  66368. * * 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
  66369. * * 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
  66370. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66371. * * 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
  66372. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66373. * @param name defines the name of the mesh
  66374. * @param options defines the options used to create the mesh
  66375. * @param scene defines the hosting scene
  66376. * @returns the polyhedron mesh
  66377. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66378. */
  66379. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66380. var polyhedron = new BABYLON.Mesh(name, scene);
  66381. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66382. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66383. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66384. vertexData.applyToMesh(polyhedron, options.updatable);
  66385. return polyhedron;
  66386. };
  66387. /**
  66388. * Creates a decal mesh.
  66389. * 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
  66390. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66391. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66392. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66393. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66394. * @param name defines the name of the mesh
  66395. * @param sourceMesh defines the mesh where the decal must be applied
  66396. * @param options defines the options used to create the mesh
  66397. * @param scene defines the hosting scene
  66398. * @returns the decal mesh
  66399. * @see http://doc.babylonjs.com/how_to/decals
  66400. */
  66401. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66402. var indices = sourceMesh.getIndices();
  66403. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66404. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66405. var position = options.position || BABYLON.Vector3.Zero();
  66406. var normal = options.normal || BABYLON.Vector3.Up();
  66407. var size = options.size || BABYLON.Vector3.One();
  66408. var angle = options.angle || 0;
  66409. // Getting correct rotation
  66410. if (!normal) {
  66411. var target = new BABYLON.Vector3(0, 0, 1);
  66412. var camera = sourceMesh.getScene().activeCamera;
  66413. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66414. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66415. }
  66416. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66417. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66418. var pitch = Math.atan2(normal.y, len);
  66419. // Matrix
  66420. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66421. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66422. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66423. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66424. var vertexData = new BABYLON.VertexData();
  66425. vertexData.indices = [];
  66426. vertexData.positions = [];
  66427. vertexData.normals = [];
  66428. vertexData.uvs = [];
  66429. var currentVertexDataIndex = 0;
  66430. var extractDecalVector3 = function (indexId) {
  66431. var result = new BABYLON.PositionNormalVertex();
  66432. if (!indices || !positions || !normals) {
  66433. return result;
  66434. }
  66435. var vertexId = indices[indexId];
  66436. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66437. // Send vector to decal local world
  66438. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66439. // Get normal
  66440. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66441. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66442. return result;
  66443. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66444. var clip = function (vertices, axis) {
  66445. if (vertices.length === 0) {
  66446. return vertices;
  66447. }
  66448. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66449. var clipVertices = function (v0, v1) {
  66450. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66451. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66452. };
  66453. var result = new Array();
  66454. for (var index = 0; index < vertices.length; index += 3) {
  66455. var v1Out;
  66456. var v2Out;
  66457. var v3Out;
  66458. var total = 0;
  66459. var nV1 = null;
  66460. var nV2 = null;
  66461. var nV3 = null;
  66462. var nV4 = null;
  66463. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66464. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66465. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66466. v1Out = d1 > 0;
  66467. v2Out = d2 > 0;
  66468. v3Out = d3 > 0;
  66469. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66470. switch (total) {
  66471. case 0:
  66472. result.push(vertices[index]);
  66473. result.push(vertices[index + 1]);
  66474. result.push(vertices[index + 2]);
  66475. break;
  66476. case 1:
  66477. if (v1Out) {
  66478. nV1 = vertices[index + 1];
  66479. nV2 = vertices[index + 2];
  66480. nV3 = clipVertices(vertices[index], nV1);
  66481. nV4 = clipVertices(vertices[index], nV2);
  66482. }
  66483. if (v2Out) {
  66484. nV1 = vertices[index];
  66485. nV2 = vertices[index + 2];
  66486. nV3 = clipVertices(vertices[index + 1], nV1);
  66487. nV4 = clipVertices(vertices[index + 1], nV2);
  66488. result.push(nV3);
  66489. result.push(nV2.clone());
  66490. result.push(nV1.clone());
  66491. result.push(nV2.clone());
  66492. result.push(nV3.clone());
  66493. result.push(nV4);
  66494. break;
  66495. }
  66496. if (v3Out) {
  66497. nV1 = vertices[index];
  66498. nV2 = vertices[index + 1];
  66499. nV3 = clipVertices(vertices[index + 2], nV1);
  66500. nV4 = clipVertices(vertices[index + 2], nV2);
  66501. }
  66502. if (nV1 && nV2 && nV3 && nV4) {
  66503. result.push(nV1.clone());
  66504. result.push(nV2.clone());
  66505. result.push(nV3);
  66506. result.push(nV4);
  66507. result.push(nV3.clone());
  66508. result.push(nV2.clone());
  66509. }
  66510. break;
  66511. case 2:
  66512. if (!v1Out) {
  66513. nV1 = vertices[index].clone();
  66514. nV2 = clipVertices(nV1, vertices[index + 1]);
  66515. nV3 = clipVertices(nV1, vertices[index + 2]);
  66516. result.push(nV1);
  66517. result.push(nV2);
  66518. result.push(nV3);
  66519. }
  66520. if (!v2Out) {
  66521. nV1 = vertices[index + 1].clone();
  66522. nV2 = clipVertices(nV1, vertices[index + 2]);
  66523. nV3 = clipVertices(nV1, vertices[index]);
  66524. result.push(nV1);
  66525. result.push(nV2);
  66526. result.push(nV3);
  66527. }
  66528. if (!v3Out) {
  66529. nV1 = vertices[index + 2].clone();
  66530. nV2 = clipVertices(nV1, vertices[index]);
  66531. nV3 = clipVertices(nV1, vertices[index + 1]);
  66532. result.push(nV1);
  66533. result.push(nV2);
  66534. result.push(nV3);
  66535. }
  66536. break;
  66537. case 3:
  66538. break;
  66539. }
  66540. }
  66541. return result;
  66542. };
  66543. for (var index = 0; index < indices.length; index += 3) {
  66544. var faceVertices = new Array();
  66545. faceVertices.push(extractDecalVector3(index));
  66546. faceVertices.push(extractDecalVector3(index + 1));
  66547. faceVertices.push(extractDecalVector3(index + 2));
  66548. // Clip
  66549. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66550. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66551. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66552. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66553. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66554. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66555. if (faceVertices.length === 0) {
  66556. continue;
  66557. }
  66558. // Add UVs and get back to world
  66559. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66560. var vertex = faceVertices[vIndex];
  66561. //TODO check for Int32Array | Uint32Array | Uint16Array
  66562. vertexData.indices.push(currentVertexDataIndex);
  66563. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66564. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66565. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66566. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66567. currentVertexDataIndex++;
  66568. }
  66569. }
  66570. // Return mesh
  66571. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66572. vertexData.applyToMesh(decal);
  66573. decal.position = position.clone();
  66574. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66575. return decal;
  66576. };
  66577. // Privates
  66578. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66579. // extrusion geometry
  66580. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66581. var tangents = path3D.getTangents();
  66582. var normals = path3D.getNormals();
  66583. var binormals = path3D.getBinormals();
  66584. var distances = path3D.getDistances();
  66585. var angle = 0;
  66586. var returnScale = function () { return scale !== null ? scale : 1; };
  66587. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66588. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66589. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66590. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66591. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66592. for (var i = 0; i < curve.length; i++) {
  66593. var shapePath = new Array();
  66594. var angleStep = rotate(i, distances[i]);
  66595. var scaleRatio = scl(i, distances[i]);
  66596. for (var p = 0; p < shape.length; p++) {
  66597. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66598. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66599. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66600. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66601. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66602. shapePath[p] = rotated;
  66603. }
  66604. shapePaths[index] = shapePath;
  66605. angle += angleStep;
  66606. index++;
  66607. }
  66608. // cap
  66609. var capPath = function (shapePath) {
  66610. var pointCap = Array();
  66611. var barycenter = BABYLON.Vector3.Zero();
  66612. var i;
  66613. for (i = 0; i < shapePath.length; i++) {
  66614. barycenter.addInPlace(shapePath[i]);
  66615. }
  66616. barycenter.scaleInPlace(1.0 / shapePath.length);
  66617. for (i = 0; i < shapePath.length; i++) {
  66618. pointCap.push(barycenter);
  66619. }
  66620. return pointCap;
  66621. };
  66622. switch (cap) {
  66623. case BABYLON.Mesh.NO_CAP:
  66624. break;
  66625. case BABYLON.Mesh.CAP_START:
  66626. shapePaths[0] = capPath(shapePaths[2]);
  66627. shapePaths[1] = shapePaths[2];
  66628. break;
  66629. case BABYLON.Mesh.CAP_END:
  66630. shapePaths[index] = shapePaths[index - 1];
  66631. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66632. break;
  66633. case BABYLON.Mesh.CAP_ALL:
  66634. shapePaths[0] = capPath(shapePaths[2]);
  66635. shapePaths[1] = shapePaths[2];
  66636. shapePaths[index] = shapePaths[index - 1];
  66637. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66638. break;
  66639. default:
  66640. break;
  66641. }
  66642. return shapePaths;
  66643. };
  66644. var path3D;
  66645. var pathArray;
  66646. if (instance) { // instance update
  66647. path3D = (instance.path3D).update(curve);
  66648. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66649. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66650. return instance;
  66651. }
  66652. // extruded shape creation
  66653. path3D = new BABYLON.Path3D(curve);
  66654. var newShapePaths = new Array();
  66655. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66656. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66657. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66658. extrudedGeneric.pathArray = pathArray;
  66659. extrudedGeneric.path3D = path3D;
  66660. extrudedGeneric.cap = cap;
  66661. return extrudedGeneric;
  66662. };
  66663. return MeshBuilder;
  66664. }());
  66665. BABYLON.MeshBuilder = MeshBuilder;
  66666. })(BABYLON || (BABYLON = {}));
  66667. //# sourceMappingURL=babylon.meshBuilder.js.map
  66668. var BABYLON;
  66669. (function (BABYLON) {
  66670. /**
  66671. * Draco compression (https://google.github.io/draco/)
  66672. *
  66673. * This class wraps the Draco module.
  66674. *
  66675. * **Encoder**
  66676. *
  66677. * The encoder is not currently implemented.
  66678. *
  66679. * **Decoder**
  66680. *
  66681. * 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.
  66682. *
  66683. * To update the configuration, use the following code:
  66684. * ```javascript
  66685. * BABYLON.DracoCompression.Configuration = {
  66686. * decoder: {
  66687. * wasmUrl: "<url to the WebAssembly library>",
  66688. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  66689. * fallbackUrl: "<url to the fallback JavaScript library>",
  66690. * }
  66691. * };
  66692. * ```
  66693. *
  66694. * 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.
  66695. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  66696. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  66697. *
  66698. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  66699. * ```javascript
  66700. * var dracoCompression = new BABYLON.DracoCompression();
  66701. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  66702. * [BABYLON.VertexBuffer.PositionKind]: 0
  66703. * });
  66704. * ```
  66705. *
  66706. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  66707. */
  66708. var DracoCompression = /** @class */ (function () {
  66709. /**
  66710. * Constructor
  66711. */
  66712. function DracoCompression() {
  66713. }
  66714. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  66715. /**
  66716. * Returns true if the decoder is available.
  66717. */
  66718. get: function () {
  66719. if (typeof DracoDecoderModule !== "undefined") {
  66720. return true;
  66721. }
  66722. var decoder = DracoCompression.Configuration.decoder;
  66723. if (decoder) {
  66724. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66725. return true;
  66726. }
  66727. if (decoder.fallbackUrl) {
  66728. return true;
  66729. }
  66730. }
  66731. return false;
  66732. },
  66733. enumerable: true,
  66734. configurable: true
  66735. });
  66736. /**
  66737. * Stop all async operations and release resources.
  66738. */
  66739. DracoCompression.prototype.dispose = function () {
  66740. };
  66741. /**
  66742. * Decode Draco compressed mesh data to vertex data.
  66743. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  66744. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  66745. * @returns A promise that resolves with the decoded vertex data
  66746. */
  66747. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  66748. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  66749. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  66750. var module = wrappedModule.module;
  66751. var vertexData = new BABYLON.VertexData();
  66752. var buffer = new module.DecoderBuffer();
  66753. buffer.Init(dataView, dataView.byteLength);
  66754. var decoder = new module.Decoder();
  66755. var geometry;
  66756. var status;
  66757. try {
  66758. var type = decoder.GetEncodedGeometryType(buffer);
  66759. switch (type) {
  66760. case module.TRIANGULAR_MESH:
  66761. geometry = new module.Mesh();
  66762. status = decoder.DecodeBufferToMesh(buffer, geometry);
  66763. break;
  66764. case module.POINT_CLOUD:
  66765. geometry = new module.PointCloud();
  66766. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  66767. break;
  66768. default:
  66769. throw new Error("Invalid geometry type " + type);
  66770. }
  66771. if (!status.ok() || !geometry.ptr) {
  66772. throw new Error(status.error_msg());
  66773. }
  66774. var numPoints = geometry.num_points();
  66775. if (type === module.TRIANGULAR_MESH) {
  66776. var numFaces = geometry.num_faces();
  66777. var faceIndices = new module.DracoInt32Array();
  66778. try {
  66779. var indices = new Uint32Array(numFaces * 3);
  66780. for (var i = 0; i < numFaces; i++) {
  66781. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  66782. var offset = i * 3;
  66783. indices[offset + 0] = faceIndices.GetValue(0);
  66784. indices[offset + 1] = faceIndices.GetValue(1);
  66785. indices[offset + 2] = faceIndices.GetValue(2);
  66786. }
  66787. vertexData.indices = indices;
  66788. }
  66789. finally {
  66790. module.destroy(faceIndices);
  66791. }
  66792. }
  66793. for (var kind in attributes) {
  66794. var uniqueId = attributes[kind];
  66795. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  66796. var dracoData = new module.DracoFloat32Array();
  66797. try {
  66798. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  66799. var babylonData = new Float32Array(numPoints * attribute.num_components());
  66800. for (var i = 0; i < babylonData.length; i++) {
  66801. babylonData[i] = dracoData.GetValue(i);
  66802. }
  66803. vertexData.set(babylonData, kind);
  66804. }
  66805. finally {
  66806. module.destroy(dracoData);
  66807. }
  66808. }
  66809. }
  66810. finally {
  66811. if (geometry) {
  66812. module.destroy(geometry);
  66813. }
  66814. module.destroy(decoder);
  66815. module.destroy(buffer);
  66816. }
  66817. return vertexData;
  66818. });
  66819. };
  66820. DracoCompression._GetDecoderModule = function () {
  66821. if (!DracoCompression._DecoderModulePromise) {
  66822. var promise = null;
  66823. var config_1 = {};
  66824. if (typeof DracoDecoderModule !== "undefined") {
  66825. promise = Promise.resolve();
  66826. }
  66827. else {
  66828. var decoder = DracoCompression.Configuration.decoder;
  66829. if (decoder) {
  66830. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66831. promise = Promise.all([
  66832. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  66833. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  66834. config_1.wasmBinary = data;
  66835. })
  66836. ]);
  66837. }
  66838. else if (decoder.fallbackUrl) {
  66839. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  66840. }
  66841. }
  66842. }
  66843. if (!promise) {
  66844. throw new Error("Draco decoder module is not available");
  66845. }
  66846. DracoCompression._DecoderModulePromise = promise.then(function () {
  66847. return new Promise(function (resolve) {
  66848. config_1.onModuleLoaded = function (decoderModule) {
  66849. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  66850. resolve({ module: decoderModule });
  66851. };
  66852. DracoDecoderModule(config_1);
  66853. });
  66854. });
  66855. }
  66856. return DracoCompression._DecoderModulePromise;
  66857. };
  66858. DracoCompression._LoadScriptAsync = function (url) {
  66859. return new Promise(function (resolve, reject) {
  66860. BABYLON.Tools.LoadScript(url, function () {
  66861. resolve();
  66862. }, function (message) {
  66863. reject(new Error(message));
  66864. });
  66865. });
  66866. };
  66867. DracoCompression._LoadFileAsync = function (url) {
  66868. return new Promise(function (resolve, reject) {
  66869. BABYLON.Tools.LoadFile(url, function (data) {
  66870. resolve(data);
  66871. }, undefined, undefined, true, function (request, exception) {
  66872. reject(exception);
  66873. });
  66874. });
  66875. };
  66876. /**
  66877. * The configuration. Defaults to the following urls:
  66878. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  66879. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  66880. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66881. */
  66882. DracoCompression.Configuration = {
  66883. decoder: {
  66884. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  66885. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  66886. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66887. }
  66888. };
  66889. return DracoCompression;
  66890. }());
  66891. BABYLON.DracoCompression = DracoCompression;
  66892. })(BABYLON || (BABYLON = {}));
  66893. //# sourceMappingURL=babylon.dracoCompression.js.map
  66894. var BABYLON;
  66895. (function (BABYLON) {
  66896. // Sets the default audio engine to Babylon JS.
  66897. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  66898. /**
  66899. * This represents the default audio engine used in babylon.
  66900. * It is responsible to play, synchronize and analyse sounds throughout the application.
  66901. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66902. */
  66903. var AudioEngine = /** @class */ (function () {
  66904. /**
  66905. * Instantiates a new audio engine.
  66906. *
  66907. * There should be only one per page as some browsers restrict the number
  66908. * of audio contexts you can create.
  66909. * @param engine defines the hosting engine
  66910. */
  66911. function AudioEngine(engine) {
  66912. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  66913. var _this = this;
  66914. this._audioContext = null;
  66915. this._audioContextInitialized = false;
  66916. this._muteButtonDisplayed = false;
  66917. this._muteButton = null;
  66918. /**
  66919. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  66920. */
  66921. this.canUseWebAudio = false;
  66922. /**
  66923. * Defines if Babylon should emit a warning if WebAudio is not supported.
  66924. * @ignoreNaming
  66925. */
  66926. this.WarnedWebAudioUnsupported = false;
  66927. /**
  66928. * Gets whether or not mp3 are supported by your browser.
  66929. */
  66930. this.isMP3supported = false;
  66931. /**
  66932. * Gets whether or not ogg are supported by your browser.
  66933. */
  66934. this.isOGGsupported = false;
  66935. /**
  66936. * Gets whether audio has been unlocked on the device.
  66937. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  66938. * a user interaction has happened.
  66939. */
  66940. this.unlocked = false;
  66941. /**
  66942. * Defines if the audio engine relies on a custom unlocked button.
  66943. * In this case, the embedded button will not be displayed.
  66944. */
  66945. this.useCustomUnlockedButton = false;
  66946. /**
  66947. * Event raised when audio has been unlocked on the browser.
  66948. */
  66949. this.onAudioUnlockedObservable = new BABYLON.Observable();
  66950. /**
  66951. * Event raised when audio has been locked on the browser.
  66952. */
  66953. this.onAudioLockedObservable = new BABYLON.Observable();
  66954. this._onResize = function () {
  66955. _this._moveButtonToTopLeft();
  66956. };
  66957. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  66958. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  66959. this.canUseWebAudio = true;
  66960. }
  66961. var audioElem = document.createElement('audio');
  66962. this._engine = engine;
  66963. try {
  66964. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  66965. this.isMP3supported = true;
  66966. }
  66967. }
  66968. catch (e) {
  66969. // protect error during capability check.
  66970. }
  66971. try {
  66972. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  66973. this.isOGGsupported = true;
  66974. }
  66975. }
  66976. catch (e) {
  66977. // protect error during capability check.
  66978. }
  66979. }
  66980. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  66981. /**
  66982. * Gets the current AudioContext if available.
  66983. */
  66984. get: function () {
  66985. if (!this._audioContextInitialized) {
  66986. this._initializeAudioContext();
  66987. }
  66988. else {
  66989. if (!this.unlocked && !this._muteButtonDisplayed) {
  66990. this._displayMuteButton();
  66991. }
  66992. }
  66993. return this._audioContext;
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. /**
  66999. * Flags the audio engine in Locked state.
  67000. * This happens due to new browser policies preventing audio to autoplay.
  67001. */
  67002. AudioEngine.prototype.lock = function () {
  67003. this._triggerSuspendedState();
  67004. };
  67005. /**
  67006. * Unlocks the audio engine once a user action has been done on the dom.
  67007. * This is helpful to resume play once browser policies have been satisfied.
  67008. */
  67009. AudioEngine.prototype.unlock = function () {
  67010. this._triggerRunningState();
  67011. };
  67012. AudioEngine.prototype._resumeAudioContext = function () {
  67013. if (this._audioContext.resume) {
  67014. this._audioContext.resume();
  67015. }
  67016. };
  67017. AudioEngine.prototype._initializeAudioContext = function () {
  67018. var _this = this;
  67019. try {
  67020. if (this.canUseWebAudio) {
  67021. this._audioContext = new AudioContext();
  67022. // create a global volume gain node
  67023. this.masterGain = this._audioContext.createGain();
  67024. this.masterGain.gain.value = 1;
  67025. this.masterGain.connect(this._audioContext.destination);
  67026. this._audioContextInitialized = true;
  67027. if (this._audioContext.state === "running") {
  67028. this._triggerRunningState();
  67029. }
  67030. else {
  67031. if (!this._muteButtonDisplayed) {
  67032. this._displayMuteButton();
  67033. }
  67034. // 3 possible states: https://webaudio.github.io/web-audio-api/#BaseAudioContext
  67035. this._audioContext.addEventListener("statechange", function () {
  67036. if (_this._audioContext.state === "running") {
  67037. _this._triggerRunningState();
  67038. }
  67039. else {
  67040. _this._triggerSuspendedState();
  67041. }
  67042. });
  67043. }
  67044. }
  67045. }
  67046. catch (e) {
  67047. this.canUseWebAudio = false;
  67048. BABYLON.Tools.Error("Web Audio: " + e.message);
  67049. }
  67050. };
  67051. AudioEngine.prototype._triggerRunningState = function () {
  67052. this._resumeAudioContext();
  67053. this.unlocked = true;
  67054. if (this._muteButtonDisplayed) {
  67055. this._hideMuteButton();
  67056. }
  67057. // Notify users that the audio stack is unlocked/unmuted
  67058. this.onAudioUnlockedObservable.notifyObservers(this);
  67059. };
  67060. AudioEngine.prototype._triggerSuspendedState = function () {
  67061. this.unlocked = false;
  67062. this.onAudioLockedObservable.notifyObservers(this);
  67063. this._displayMuteButton();
  67064. };
  67065. AudioEngine.prototype._displayMuteButton = function () {
  67066. var _this = this;
  67067. if (this.useCustomUnlockedButton) {
  67068. return;
  67069. }
  67070. this._canvas = this._engine.getRenderingCanvas();
  67071. this._muteButton = document.createElement("BUTTON");
  67072. this._muteButton.className = "babylonUnmuteIcon";
  67073. this._muteButton.id = "babylonUnmuteIconBtn";
  67074. this._muteButton.title = "Unmute";
  67075. 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) }";
  67076. var style = document.createElement('style');
  67077. style.appendChild(document.createTextNode(css));
  67078. document.getElementsByTagName('head')[0].appendChild(style);
  67079. document.body.appendChild(this._muteButton);
  67080. this._moveButtonToTopLeft();
  67081. this._muteButton.addEventListener('mousedown', function () {
  67082. _this._triggerRunningState();
  67083. }, false);
  67084. this._muteButton.addEventListener('touchend', function () {
  67085. _this._triggerRunningState();
  67086. }, false);
  67087. this._muteButtonDisplayed = true;
  67088. window.addEventListener("resize", this._onResize);
  67089. };
  67090. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67091. if (this._canvas && this._muteButton) {
  67092. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67093. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67094. }
  67095. };
  67096. AudioEngine.prototype._hideMuteButton = function () {
  67097. if (this._muteButtonDisplayed && this._muteButton) {
  67098. document.body.removeChild(this._muteButton);
  67099. this._muteButtonDisplayed = false;
  67100. }
  67101. };
  67102. /**
  67103. * Destroy and release the resources associated with the audio ccontext.
  67104. */
  67105. AudioEngine.prototype.dispose = function () {
  67106. if (this.canUseWebAudio && this._audioContextInitialized) {
  67107. if (this._connectedAnalyser && this._audioContext) {
  67108. this._connectedAnalyser.stopDebugCanvas();
  67109. this._connectedAnalyser.dispose();
  67110. this.masterGain.disconnect();
  67111. this.masterGain.connect(this._audioContext.destination);
  67112. this._connectedAnalyser = null;
  67113. }
  67114. this.masterGain.gain.value = 1;
  67115. }
  67116. this.WarnedWebAudioUnsupported = false;
  67117. this._hideMuteButton();
  67118. window.removeEventListener("resize", this._onResize);
  67119. this.onAudioUnlockedObservable.clear();
  67120. this.onAudioLockedObservable.clear();
  67121. };
  67122. /**
  67123. * Gets the global volume sets on the master gain.
  67124. * @returns the global volume if set or -1 otherwise
  67125. */
  67126. AudioEngine.prototype.getGlobalVolume = function () {
  67127. if (this.canUseWebAudio && this._audioContextInitialized) {
  67128. return this.masterGain.gain.value;
  67129. }
  67130. else {
  67131. return -1;
  67132. }
  67133. };
  67134. /**
  67135. * Sets the global volume of your experience (sets on the master gain).
  67136. * @param newVolume Defines the new global volume of the application
  67137. */
  67138. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67139. if (this.canUseWebAudio && this._audioContextInitialized) {
  67140. this.masterGain.gain.value = newVolume;
  67141. }
  67142. };
  67143. /**
  67144. * Connect the audio engine to an audio analyser allowing some amazing
  67145. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67146. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67147. * @param analyser The analyser to connect to the engine
  67148. */
  67149. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67150. if (this._connectedAnalyser) {
  67151. this._connectedAnalyser.stopDebugCanvas();
  67152. }
  67153. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67154. this._connectedAnalyser = analyser;
  67155. this.masterGain.disconnect();
  67156. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67157. }
  67158. };
  67159. return AudioEngine;
  67160. }());
  67161. BABYLON.AudioEngine = AudioEngine;
  67162. })(BABYLON || (BABYLON = {}));
  67163. //# sourceMappingURL=babylon.audioEngine.js.map
  67164. var BABYLON;
  67165. (function (BABYLON) {
  67166. /**
  67167. * Defines a sound that can be played in the application.
  67168. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67169. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67170. */
  67171. var Sound = /** @class */ (function () {
  67172. /**
  67173. * Create a sound and attach it to a scene
  67174. * @param name Name of your sound
  67175. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67176. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67177. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67178. */
  67179. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67180. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67181. var _this = this;
  67182. /**
  67183. * Does the sound autoplay once loaded.
  67184. */
  67185. this.autoplay = false;
  67186. /**
  67187. * Does the sound loop after it finishes playing once.
  67188. */
  67189. this.loop = false;
  67190. /**
  67191. * Does the sound use a custom attenuation curve to simulate the falloff
  67192. * happening when the source gets further away from the camera.
  67193. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67194. */
  67195. this.useCustomAttenuation = false;
  67196. /**
  67197. * Does this sound enables spatial sound.
  67198. */
  67199. this.spatialSound = false;
  67200. this.refDistance = 1;
  67201. this.rolloffFactor = 1;
  67202. this.maxDistance = 100;
  67203. this.distanceModel = "linear";
  67204. this._panningModel = "equalpower";
  67205. /**
  67206. * Observable event when the current playing sound finishes.
  67207. */
  67208. this.onEndedObservable = new BABYLON.Observable();
  67209. this._playbackRate = 1;
  67210. this._streaming = false;
  67211. this._startTime = 0;
  67212. this._startOffset = 0;
  67213. this._position = BABYLON.Vector3.Zero();
  67214. /** @hidden */
  67215. this._positionInEmitterSpace = false;
  67216. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67217. this._volume = 1;
  67218. this._isReadyToPlay = false;
  67219. this.isPlaying = false;
  67220. this.isPaused = false;
  67221. this._isDirectional = false;
  67222. // Used if you'd like to create a directional sound.
  67223. // If not set, the sound will be omnidirectional
  67224. this._coneInnerAngle = 360;
  67225. this._coneOuterAngle = 360;
  67226. this._coneOuterGain = 0;
  67227. this._isOutputConnected = false;
  67228. this._urlType = "Unknown";
  67229. this.name = name;
  67230. this._scene = scene;
  67231. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67232. if (!compo) {
  67233. compo = new BABYLON.AudioSceneComponent(scene);
  67234. scene._addComponent(compo);
  67235. }
  67236. this._readyToPlayCallback = readyToPlayCallback;
  67237. // Default custom attenuation function is a linear attenuation
  67238. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67239. if (currentDistance < maxDistance) {
  67240. return currentVolume * (1 - currentDistance / maxDistance);
  67241. }
  67242. else {
  67243. return 0;
  67244. }
  67245. };
  67246. if (options) {
  67247. this.autoplay = options.autoplay || false;
  67248. this.loop = options.loop || false;
  67249. // if volume === 0, we need another way to check this option
  67250. if (options.volume !== undefined) {
  67251. this._volume = options.volume;
  67252. }
  67253. this.spatialSound = options.spatialSound || false;
  67254. this.maxDistance = options.maxDistance || 100;
  67255. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67256. this.rolloffFactor = options.rolloffFactor || 1;
  67257. this.refDistance = options.refDistance || 1;
  67258. this.distanceModel = options.distanceModel || "linear";
  67259. this._playbackRate = options.playbackRate || 1;
  67260. this._streaming = options.streaming || false;
  67261. }
  67262. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67263. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67264. this._soundGain.gain.value = this._volume;
  67265. this._inputAudioNode = this._soundGain;
  67266. this._outputAudioNode = this._soundGain;
  67267. if (this.spatialSound) {
  67268. this._createSpatialParameters();
  67269. }
  67270. this._scene.mainSoundTrack.AddSound(this);
  67271. var validParameter = true;
  67272. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67273. if (urlOrArrayBuffer) {
  67274. try {
  67275. if (typeof (urlOrArrayBuffer) === "string") {
  67276. this._urlType = "String";
  67277. }
  67278. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67279. this._urlType = "ArrayBuffer";
  67280. }
  67281. else if (urlOrArrayBuffer instanceof MediaStream) {
  67282. this._urlType = "MediaStream";
  67283. }
  67284. else if (Array.isArray(urlOrArrayBuffer)) {
  67285. this._urlType = "Array";
  67286. }
  67287. var urls = [];
  67288. var codecSupportedFound = false;
  67289. switch (this._urlType) {
  67290. case "MediaStream":
  67291. this._streaming = true;
  67292. this._isReadyToPlay = true;
  67293. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67294. if (this.autoplay) {
  67295. this.play();
  67296. }
  67297. if (this._readyToPlayCallback) {
  67298. this._readyToPlayCallback();
  67299. }
  67300. break;
  67301. case "ArrayBuffer":
  67302. if (urlOrArrayBuffer.byteLength > 0) {
  67303. codecSupportedFound = true;
  67304. this._soundLoaded(urlOrArrayBuffer);
  67305. }
  67306. break;
  67307. case "String":
  67308. urls.push(urlOrArrayBuffer);
  67309. case "Array":
  67310. if (urls.length === 0)
  67311. urls = urlOrArrayBuffer;
  67312. // If we found a supported format, we load it immediately and stop the loop
  67313. for (var i = 0; i < urls.length; i++) {
  67314. var url = urls[i];
  67315. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67316. codecSupportedFound = true;
  67317. }
  67318. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67319. codecSupportedFound = true;
  67320. }
  67321. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67322. codecSupportedFound = true;
  67323. }
  67324. if (url.indexOf("blob:") !== -1) {
  67325. codecSupportedFound = true;
  67326. }
  67327. if (codecSupportedFound) {
  67328. // Loading sound using XHR2
  67329. if (!this._streaming) {
  67330. this._scene._loadFile(url, function (data) {
  67331. _this._soundLoaded(data);
  67332. }, undefined, true, true, function (exception) {
  67333. if (exception) {
  67334. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67335. }
  67336. BABYLON.Tools.Error("Sound creation aborted.");
  67337. _this._scene.mainSoundTrack.RemoveSound(_this);
  67338. });
  67339. }
  67340. // Streaming sound using HTML5 Audio tag
  67341. else {
  67342. this._htmlAudioElement = new Audio(url);
  67343. this._htmlAudioElement.controls = false;
  67344. this._htmlAudioElement.loop = this.loop;
  67345. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67346. this._htmlAudioElement.preload = "auto";
  67347. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67348. _this._isReadyToPlay = true;
  67349. if (_this.autoplay) {
  67350. _this.play();
  67351. }
  67352. if (_this._readyToPlayCallback) {
  67353. _this._readyToPlayCallback();
  67354. }
  67355. });
  67356. document.body.appendChild(this._htmlAudioElement);
  67357. this._htmlAudioElement.load();
  67358. }
  67359. break;
  67360. }
  67361. }
  67362. break;
  67363. default:
  67364. validParameter = false;
  67365. break;
  67366. }
  67367. if (!validParameter) {
  67368. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67369. }
  67370. else {
  67371. if (!codecSupportedFound) {
  67372. this._isReadyToPlay = true;
  67373. // Simulating a ready to play event to avoid breaking code path
  67374. if (this._readyToPlayCallback) {
  67375. window.setTimeout(function () {
  67376. if (_this._readyToPlayCallback) {
  67377. _this._readyToPlayCallback();
  67378. }
  67379. }, 1000);
  67380. }
  67381. }
  67382. }
  67383. }
  67384. catch (ex) {
  67385. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67386. this._scene.mainSoundTrack.RemoveSound(this);
  67387. }
  67388. }
  67389. }
  67390. else {
  67391. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67392. this._scene.mainSoundTrack.AddSound(this);
  67393. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67394. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67395. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67396. }
  67397. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67398. if (this._readyToPlayCallback) {
  67399. window.setTimeout(function () {
  67400. if (_this._readyToPlayCallback) {
  67401. _this._readyToPlayCallback();
  67402. }
  67403. }, 1000);
  67404. }
  67405. }
  67406. }
  67407. Sound.prototype.dispose = function () {
  67408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67409. if (this.isPlaying) {
  67410. this.stop();
  67411. }
  67412. this._isReadyToPlay = false;
  67413. if (this.soundTrackId === -1) {
  67414. this._scene.mainSoundTrack.RemoveSound(this);
  67415. }
  67416. else if (this._scene.soundTracks) {
  67417. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67418. }
  67419. if (this._soundGain) {
  67420. this._soundGain.disconnect();
  67421. this._soundGain = null;
  67422. }
  67423. if (this._soundPanner) {
  67424. this._soundPanner.disconnect();
  67425. this._soundPanner = null;
  67426. }
  67427. if (this._soundSource) {
  67428. this._soundSource.disconnect();
  67429. this._soundSource = null;
  67430. }
  67431. this._audioBuffer = null;
  67432. if (this._htmlAudioElement) {
  67433. this._htmlAudioElement.pause();
  67434. this._htmlAudioElement.src = "";
  67435. document.body.removeChild(this._htmlAudioElement);
  67436. }
  67437. if (this._streamingSource) {
  67438. this._streamingSource.disconnect();
  67439. }
  67440. if (this._connectedMesh && this._registerFunc) {
  67441. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67442. this._connectedMesh = null;
  67443. }
  67444. }
  67445. };
  67446. Sound.prototype.isReady = function () {
  67447. return this._isReadyToPlay;
  67448. };
  67449. Sound.prototype._soundLoaded = function (audioData) {
  67450. var _this = this;
  67451. if (!BABYLON.Engine.audioEngine.audioContext) {
  67452. return;
  67453. }
  67454. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67455. _this._audioBuffer = buffer;
  67456. _this._isReadyToPlay = true;
  67457. if (_this.autoplay) {
  67458. _this.play();
  67459. }
  67460. if (_this._readyToPlayCallback) {
  67461. _this._readyToPlayCallback();
  67462. }
  67463. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67464. };
  67465. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67466. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67467. this._audioBuffer = audioBuffer;
  67468. this._isReadyToPlay = true;
  67469. }
  67470. };
  67471. Sound.prototype.updateOptions = function (options) {
  67472. if (options) {
  67473. this.loop = options.loop || this.loop;
  67474. this.maxDistance = options.maxDistance || this.maxDistance;
  67475. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67476. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67477. this.refDistance = options.refDistance || this.refDistance;
  67478. this.distanceModel = options.distanceModel || this.distanceModel;
  67479. this._playbackRate = options.playbackRate || this._playbackRate;
  67480. this._updateSpatialParameters();
  67481. if (this.isPlaying) {
  67482. if (this._streaming && this._htmlAudioElement) {
  67483. this._htmlAudioElement.playbackRate = this._playbackRate;
  67484. }
  67485. else {
  67486. if (this._soundSource) {
  67487. this._soundSource.playbackRate.value = this._playbackRate;
  67488. }
  67489. }
  67490. }
  67491. }
  67492. };
  67493. Sound.prototype._createSpatialParameters = function () {
  67494. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67495. if (this._scene.headphone) {
  67496. this._panningModel = "HRTF";
  67497. }
  67498. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67499. this._updateSpatialParameters();
  67500. this._soundPanner.connect(this._outputAudioNode);
  67501. this._inputAudioNode = this._soundPanner;
  67502. }
  67503. };
  67504. Sound.prototype._updateSpatialParameters = function () {
  67505. if (this.spatialSound && this._soundPanner) {
  67506. if (this.useCustomAttenuation) {
  67507. // Tricks to disable in a way embedded Web Audio attenuation
  67508. this._soundPanner.distanceModel = "linear";
  67509. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67510. this._soundPanner.refDistance = 1;
  67511. this._soundPanner.rolloffFactor = 1;
  67512. this._soundPanner.panningModel = this._panningModel;
  67513. }
  67514. else {
  67515. this._soundPanner.distanceModel = this.distanceModel;
  67516. this._soundPanner.maxDistance = this.maxDistance;
  67517. this._soundPanner.refDistance = this.refDistance;
  67518. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67519. this._soundPanner.panningModel = this._panningModel;
  67520. }
  67521. }
  67522. };
  67523. Sound.prototype.switchPanningModelToHRTF = function () {
  67524. this._panningModel = "HRTF";
  67525. this._switchPanningModel();
  67526. };
  67527. Sound.prototype.switchPanningModelToEqualPower = function () {
  67528. this._panningModel = "equalpower";
  67529. this._switchPanningModel();
  67530. };
  67531. Sound.prototype._switchPanningModel = function () {
  67532. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67533. this._soundPanner.panningModel = this._panningModel;
  67534. }
  67535. };
  67536. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67538. if (this._isOutputConnected) {
  67539. this._outputAudioNode.disconnect();
  67540. }
  67541. this._outputAudioNode.connect(soundTrackAudioNode);
  67542. this._isOutputConnected = true;
  67543. }
  67544. };
  67545. /**
  67546. * Transform this sound into a directional source
  67547. * @param coneInnerAngle Size of the inner cone in degree
  67548. * @param coneOuterAngle Size of the outer cone in degree
  67549. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67550. */
  67551. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67552. if (coneOuterAngle < coneInnerAngle) {
  67553. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67554. return;
  67555. }
  67556. this._coneInnerAngle = coneInnerAngle;
  67557. this._coneOuterAngle = coneOuterAngle;
  67558. this._coneOuterGain = coneOuterGain;
  67559. this._isDirectional = true;
  67560. if (this.isPlaying && this.loop) {
  67561. this.stop();
  67562. this.play();
  67563. }
  67564. };
  67565. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67566. /**
  67567. * Gets or sets the inner angle for the directional cone.
  67568. */
  67569. get: function () {
  67570. return this._coneInnerAngle;
  67571. },
  67572. /**
  67573. * Gets or sets the inner angle for the directional cone.
  67574. */
  67575. set: function (value) {
  67576. if (value != this._coneInnerAngle) {
  67577. if (this._coneOuterAngle < value) {
  67578. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67579. return;
  67580. }
  67581. this._coneInnerAngle = value;
  67582. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67583. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67584. }
  67585. }
  67586. },
  67587. enumerable: true,
  67588. configurable: true
  67589. });
  67590. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67591. /**
  67592. * Gets or sets the outer angle for the directional cone.
  67593. */
  67594. get: function () {
  67595. return this._coneOuterAngle;
  67596. },
  67597. /**
  67598. * Gets or sets the outer angle for the directional cone.
  67599. */
  67600. set: function (value) {
  67601. if (value != this._coneOuterAngle) {
  67602. if (value < this._coneInnerAngle) {
  67603. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67604. return;
  67605. }
  67606. this._coneOuterAngle = value;
  67607. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67608. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67609. }
  67610. }
  67611. },
  67612. enumerable: true,
  67613. configurable: true
  67614. });
  67615. Sound.prototype.setPosition = function (newPosition) {
  67616. this._position = newPosition;
  67617. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67618. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67619. }
  67620. };
  67621. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  67622. this._localDirection = newLocalDirection;
  67623. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  67624. this._updateDirection();
  67625. }
  67626. };
  67627. Sound.prototype._updateDirection = function () {
  67628. if (!this._connectedMesh || !this._soundPanner) {
  67629. return;
  67630. }
  67631. var mat = this._connectedMesh.getWorldMatrix();
  67632. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  67633. direction.normalize();
  67634. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  67635. };
  67636. Sound.prototype.updateDistanceFromListener = function () {
  67637. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  67638. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  67639. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  67640. }
  67641. };
  67642. Sound.prototype.setAttenuationFunction = function (callback) {
  67643. this._customAttenuationFunction = callback;
  67644. };
  67645. /**
  67646. * Play the sound
  67647. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  67648. * @param offset (optional) Start the sound setting it at a specific time
  67649. */
  67650. Sound.prototype.play = function (time, offset) {
  67651. var _this = this;
  67652. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  67653. try {
  67654. if (this._startOffset < 0) {
  67655. time = -this._startOffset;
  67656. this._startOffset = 0;
  67657. }
  67658. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67659. if (!this._soundSource || !this._streamingSource) {
  67660. if (this.spatialSound && this._soundPanner) {
  67661. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67662. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67663. }
  67664. if (this._isDirectional) {
  67665. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67666. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67667. this._soundPanner.coneOuterGain = this._coneOuterGain;
  67668. if (this._connectedMesh) {
  67669. this._updateDirection();
  67670. }
  67671. else {
  67672. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  67673. }
  67674. }
  67675. }
  67676. }
  67677. if (this._streaming) {
  67678. if (!this._streamingSource) {
  67679. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  67680. this._htmlAudioElement.onended = function () { _this._onended(); };
  67681. this._htmlAudioElement.playbackRate = this._playbackRate;
  67682. }
  67683. this._streamingSource.disconnect();
  67684. this._streamingSource.connect(this._inputAudioNode);
  67685. if (this._htmlAudioElement) {
  67686. // required to manage properly the new suspended default state of Chrome
  67687. // When the option 'streaming: true' is used, we need first to wait for
  67688. // the audio engine to be unlocked by a user gesture before trying to play
  67689. // an HTML Audio elememt
  67690. var tryToPlay = function () {
  67691. if (BABYLON.Engine.audioEngine.unlocked) {
  67692. var playPromise = _this._htmlAudioElement.play();
  67693. // In browsers that don’t yet support this functionality,
  67694. // playPromise won’t be defined.
  67695. if (playPromise !== undefined) {
  67696. playPromise.catch(function (error) {
  67697. // Automatic playback failed.
  67698. // Waiting for the audio engine to be unlocked by user click on unmute
  67699. BABYLON.Engine.audioEngine.lock();
  67700. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  67701. });
  67702. }
  67703. }
  67704. else {
  67705. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  67706. }
  67707. };
  67708. tryToPlay();
  67709. }
  67710. }
  67711. else {
  67712. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  67713. this._soundSource.buffer = this._audioBuffer;
  67714. this._soundSource.connect(this._inputAudioNode);
  67715. this._soundSource.loop = this.loop;
  67716. this._soundSource.playbackRate.value = this._playbackRate;
  67717. this._soundSource.onended = function () { _this._onended(); };
  67718. if (this._soundSource.buffer) {
  67719. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  67720. }
  67721. }
  67722. this._startTime = startTime;
  67723. this.isPlaying = true;
  67724. this.isPaused = false;
  67725. }
  67726. catch (ex) {
  67727. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  67728. }
  67729. }
  67730. };
  67731. Sound.prototype._onended = function () {
  67732. this.isPlaying = false;
  67733. if (this.onended) {
  67734. this.onended();
  67735. }
  67736. this.onEndedObservable.notifyObservers(this);
  67737. };
  67738. /**
  67739. * Stop the sound
  67740. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  67741. */
  67742. Sound.prototype.stop = function (time) {
  67743. if (this.isPlaying) {
  67744. if (this._streaming) {
  67745. if (this._htmlAudioElement) {
  67746. this._htmlAudioElement.pause();
  67747. // Test needed for Firefox or it will generate an Invalid State Error
  67748. if (this._htmlAudioElement.currentTime > 0) {
  67749. this._htmlAudioElement.currentTime = 0;
  67750. }
  67751. }
  67752. else {
  67753. this._streamingSource.disconnect();
  67754. }
  67755. }
  67756. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  67757. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67758. this._soundSource.stop(stopTime);
  67759. this._soundSource.onended = function () { };
  67760. if (!this.isPaused) {
  67761. this._startOffset = 0;
  67762. }
  67763. }
  67764. this.isPlaying = false;
  67765. }
  67766. };
  67767. Sound.prototype.pause = function () {
  67768. if (this.isPlaying) {
  67769. this.isPaused = true;
  67770. if (this._streaming) {
  67771. if (this._htmlAudioElement) {
  67772. this._htmlAudioElement.pause();
  67773. }
  67774. else {
  67775. this._streamingSource.disconnect();
  67776. }
  67777. }
  67778. else if (BABYLON.Engine.audioEngine.audioContext) {
  67779. this.stop(0);
  67780. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  67781. }
  67782. }
  67783. };
  67784. Sound.prototype.setVolume = function (newVolume, time) {
  67785. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  67786. if (time && BABYLON.Engine.audioEngine.audioContext) {
  67787. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  67788. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  67789. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  67790. }
  67791. else {
  67792. this._soundGain.gain.value = newVolume;
  67793. }
  67794. }
  67795. this._volume = newVolume;
  67796. };
  67797. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  67798. this._playbackRate = newPlaybackRate;
  67799. if (this.isPlaying) {
  67800. if (this._streaming && this._htmlAudioElement) {
  67801. this._htmlAudioElement.playbackRate = this._playbackRate;
  67802. }
  67803. else if (this._soundSource) {
  67804. this._soundSource.playbackRate.value = this._playbackRate;
  67805. }
  67806. }
  67807. };
  67808. Sound.prototype.getVolume = function () {
  67809. return this._volume;
  67810. };
  67811. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  67812. var _this = this;
  67813. if (this._connectedMesh && this._registerFunc) {
  67814. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67815. this._registerFunc = null;
  67816. }
  67817. this._connectedMesh = meshToConnectTo;
  67818. if (!this.spatialSound) {
  67819. this.spatialSound = true;
  67820. this._createSpatialParameters();
  67821. if (this.isPlaying && this.loop) {
  67822. this.stop();
  67823. this.play();
  67824. }
  67825. }
  67826. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  67827. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  67828. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  67829. };
  67830. Sound.prototype.detachFromMesh = function () {
  67831. if (this._connectedMesh && this._registerFunc) {
  67832. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67833. this._registerFunc = null;
  67834. this._connectedMesh = null;
  67835. }
  67836. };
  67837. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  67838. if (!node.getBoundingInfo) {
  67839. return;
  67840. }
  67841. var mesh = node;
  67842. if (this._positionInEmitterSpace) {
  67843. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  67844. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  67845. }
  67846. else {
  67847. var boundingInfo = mesh.getBoundingInfo();
  67848. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  67849. }
  67850. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  67851. this._updateDirection();
  67852. }
  67853. };
  67854. Sound.prototype.clone = function () {
  67855. var _this = this;
  67856. if (!this._streaming) {
  67857. var setBufferAndRun = function () {
  67858. if (_this._isReadyToPlay) {
  67859. clonedSound._audioBuffer = _this.getAudioBuffer();
  67860. clonedSound._isReadyToPlay = true;
  67861. if (clonedSound.autoplay) {
  67862. clonedSound.play();
  67863. }
  67864. }
  67865. else {
  67866. window.setTimeout(setBufferAndRun, 300);
  67867. }
  67868. };
  67869. var currentOptions = {
  67870. autoplay: this.autoplay, loop: this.loop,
  67871. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  67872. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  67873. refDistance: this.refDistance, distanceModel: this.distanceModel
  67874. };
  67875. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  67876. if (this.useCustomAttenuation) {
  67877. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  67878. }
  67879. clonedSound.setPosition(this._position);
  67880. clonedSound.setPlaybackRate(this._playbackRate);
  67881. setBufferAndRun();
  67882. return clonedSound;
  67883. }
  67884. // Can't clone a streaming sound
  67885. else {
  67886. return null;
  67887. }
  67888. };
  67889. Sound.prototype.getAudioBuffer = function () {
  67890. return this._audioBuffer;
  67891. };
  67892. Sound.prototype.serialize = function () {
  67893. var serializationObject = {
  67894. name: this.name,
  67895. url: this.name,
  67896. autoplay: this.autoplay,
  67897. loop: this.loop,
  67898. volume: this._volume,
  67899. spatialSound: this.spatialSound,
  67900. maxDistance: this.maxDistance,
  67901. rolloffFactor: this.rolloffFactor,
  67902. refDistance: this.refDistance,
  67903. distanceModel: this.distanceModel,
  67904. playbackRate: this._playbackRate,
  67905. panningModel: this._panningModel,
  67906. soundTrackId: this.soundTrackId
  67907. };
  67908. if (this.spatialSound) {
  67909. if (this._connectedMesh)
  67910. serializationObject.connectedMeshId = this._connectedMesh.id;
  67911. serializationObject.position = this._position.asArray();
  67912. serializationObject.refDistance = this.refDistance;
  67913. serializationObject.distanceModel = this.distanceModel;
  67914. serializationObject.isDirectional = this._isDirectional;
  67915. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  67916. serializationObject.coneInnerAngle = this._coneInnerAngle;
  67917. serializationObject.coneOuterAngle = this._coneOuterAngle;
  67918. serializationObject.coneOuterGain = this._coneOuterGain;
  67919. }
  67920. return serializationObject;
  67921. };
  67922. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  67923. var soundName = parsedSound.name;
  67924. var soundUrl;
  67925. if (parsedSound.url) {
  67926. soundUrl = rootUrl + parsedSound.url;
  67927. }
  67928. else {
  67929. soundUrl = rootUrl + soundName;
  67930. }
  67931. var options = {
  67932. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  67933. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  67934. rolloffFactor: parsedSound.rolloffFactor,
  67935. refDistance: parsedSound.refDistance,
  67936. distanceModel: parsedSound.distanceModel,
  67937. playbackRate: parsedSound.playbackRate
  67938. };
  67939. var newSound;
  67940. if (!sourceSound) {
  67941. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  67942. scene._addPendingData(newSound);
  67943. }
  67944. else {
  67945. var setBufferAndRun = function () {
  67946. if (sourceSound._isReadyToPlay) {
  67947. newSound._audioBuffer = sourceSound.getAudioBuffer();
  67948. newSound._isReadyToPlay = true;
  67949. if (newSound.autoplay) {
  67950. newSound.play();
  67951. }
  67952. }
  67953. else {
  67954. window.setTimeout(setBufferAndRun, 300);
  67955. }
  67956. };
  67957. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  67958. setBufferAndRun();
  67959. }
  67960. if (parsedSound.position) {
  67961. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  67962. newSound.setPosition(soundPosition);
  67963. }
  67964. if (parsedSound.isDirectional) {
  67965. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  67966. if (parsedSound.localDirectionToMesh) {
  67967. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  67968. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  67969. }
  67970. }
  67971. if (parsedSound.connectedMeshId) {
  67972. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  67973. if (connectedMesh) {
  67974. newSound.attachToMesh(connectedMesh);
  67975. }
  67976. }
  67977. return newSound;
  67978. };
  67979. return Sound;
  67980. }());
  67981. BABYLON.Sound = Sound;
  67982. })(BABYLON || (BABYLON = {}));
  67983. //# sourceMappingURL=babylon.sound.js.map
  67984. var BABYLON;
  67985. (function (BABYLON) {
  67986. var SoundTrack = /** @class */ (function () {
  67987. function SoundTrack(scene, options) {
  67988. this.id = -1;
  67989. this._isMainTrack = false;
  67990. this._isInitialized = false;
  67991. this._scene = scene;
  67992. this.soundCollection = new Array();
  67993. this._options = options;
  67994. if (!this._isMainTrack && this._scene.soundTracks) {
  67995. this._scene.soundTracks.push(this);
  67996. this.id = this._scene.soundTracks.length - 1;
  67997. }
  67998. }
  67999. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68000. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68001. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68002. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68003. if (this._options) {
  68004. if (this._options.volume) {
  68005. this._outputAudioNode.gain.value = this._options.volume;
  68006. }
  68007. if (this._options.mainTrack) {
  68008. this._isMainTrack = this._options.mainTrack;
  68009. }
  68010. }
  68011. this._isInitialized = true;
  68012. }
  68013. };
  68014. SoundTrack.prototype.dispose = function () {
  68015. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68016. if (this._connectedAnalyser) {
  68017. this._connectedAnalyser.stopDebugCanvas();
  68018. }
  68019. while (this.soundCollection.length) {
  68020. this.soundCollection[0].dispose();
  68021. }
  68022. if (this._outputAudioNode) {
  68023. this._outputAudioNode.disconnect();
  68024. }
  68025. this._outputAudioNode = null;
  68026. }
  68027. };
  68028. SoundTrack.prototype.AddSound = function (sound) {
  68029. if (!this._isInitialized) {
  68030. this._initializeSoundTrackAudioGraph();
  68031. }
  68032. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68033. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68034. }
  68035. if (sound.soundTrackId) {
  68036. if (sound.soundTrackId === -1) {
  68037. this._scene.mainSoundTrack.RemoveSound(sound);
  68038. }
  68039. else if (this._scene.soundTracks) {
  68040. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68041. }
  68042. }
  68043. this.soundCollection.push(sound);
  68044. sound.soundTrackId = this.id;
  68045. };
  68046. SoundTrack.prototype.RemoveSound = function (sound) {
  68047. var index = this.soundCollection.indexOf(sound);
  68048. if (index !== -1) {
  68049. this.soundCollection.splice(index, 1);
  68050. }
  68051. };
  68052. SoundTrack.prototype.setVolume = function (newVolume) {
  68053. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68054. this._outputAudioNode.gain.value = newVolume;
  68055. }
  68056. };
  68057. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68058. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68059. for (var i = 0; i < this.soundCollection.length; i++) {
  68060. this.soundCollection[i].switchPanningModelToHRTF();
  68061. }
  68062. }
  68063. };
  68064. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68065. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68066. for (var i = 0; i < this.soundCollection.length; i++) {
  68067. this.soundCollection[i].switchPanningModelToEqualPower();
  68068. }
  68069. }
  68070. };
  68071. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68072. if (this._connectedAnalyser) {
  68073. this._connectedAnalyser.stopDebugCanvas();
  68074. }
  68075. this._connectedAnalyser = analyser;
  68076. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68077. this._outputAudioNode.disconnect();
  68078. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68079. }
  68080. };
  68081. return SoundTrack;
  68082. }());
  68083. BABYLON.SoundTrack = SoundTrack;
  68084. })(BABYLON || (BABYLON = {}));
  68085. //# sourceMappingURL=babylon.soundtrack.js.map
  68086. var BABYLON;
  68087. (function (BABYLON) {
  68088. /**
  68089. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68090. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68091. */
  68092. var Analyser = /** @class */ (function () {
  68093. /**
  68094. * Creates a new analyser
  68095. * @param scene defines hosting scene
  68096. */
  68097. function Analyser(scene) {
  68098. /**
  68099. * Gets or sets the smoothing
  68100. * @ignorenaming
  68101. */
  68102. this.SMOOTHING = 0.75;
  68103. /**
  68104. * Gets or sets the FFT table size
  68105. * @ignorenaming
  68106. */
  68107. this.FFT_SIZE = 512;
  68108. /**
  68109. * Gets or sets the bar graph amplitude
  68110. * @ignorenaming
  68111. */
  68112. this.BARGRAPHAMPLITUDE = 256;
  68113. /**
  68114. * Gets or sets the position of the debug canvas
  68115. * @ignorenaming
  68116. */
  68117. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68118. /**
  68119. * Gets or sets the debug canvas size
  68120. * @ignorenaming
  68121. */
  68122. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68123. this._scene = scene;
  68124. this._audioEngine = BABYLON.Engine.audioEngine;
  68125. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68126. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68127. this._webAudioAnalyser.minDecibels = -140;
  68128. this._webAudioAnalyser.maxDecibels = 0;
  68129. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68130. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68131. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68132. }
  68133. }
  68134. /**
  68135. * Get the number of data values you will have to play with for the visualization
  68136. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68137. * @returns a number
  68138. */
  68139. Analyser.prototype.getFrequencyBinCount = function () {
  68140. if (this._audioEngine.canUseWebAudio) {
  68141. return this._webAudioAnalyser.frequencyBinCount;
  68142. }
  68143. else {
  68144. return 0;
  68145. }
  68146. };
  68147. /**
  68148. * Gets the current frequency data as a byte array
  68149. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68150. * @returns a Uint8Array
  68151. */
  68152. Analyser.prototype.getByteFrequencyData = function () {
  68153. if (this._audioEngine.canUseWebAudio) {
  68154. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68155. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68156. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68157. }
  68158. return this._byteFreqs;
  68159. };
  68160. /**
  68161. * Gets the current waveform as a byte array
  68162. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68163. * @returns a Uint8Array
  68164. */
  68165. Analyser.prototype.getByteTimeDomainData = function () {
  68166. if (this._audioEngine.canUseWebAudio) {
  68167. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68168. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68169. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68170. }
  68171. return this._byteTime;
  68172. };
  68173. /**
  68174. * Gets the current frequency data as a float array
  68175. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68176. * @returns a Float32Array
  68177. */
  68178. Analyser.prototype.getFloatFrequencyData = function () {
  68179. if (this._audioEngine.canUseWebAudio) {
  68180. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68181. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68182. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68183. }
  68184. return this._floatFreqs;
  68185. };
  68186. /**
  68187. * Renders the debug canvas
  68188. */
  68189. Analyser.prototype.drawDebugCanvas = function () {
  68190. var _this = this;
  68191. if (this._audioEngine.canUseWebAudio) {
  68192. if (!this._debugCanvas) {
  68193. this._debugCanvas = document.createElement("canvas");
  68194. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68195. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68196. this._debugCanvas.style.position = "absolute";
  68197. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68198. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68199. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68200. document.body.appendChild(this._debugCanvas);
  68201. this._registerFunc = function () {
  68202. _this.drawDebugCanvas();
  68203. };
  68204. this._scene.registerBeforeRender(this._registerFunc);
  68205. }
  68206. if (this._registerFunc && this._debugCanvasContext) {
  68207. var workingArray = this.getByteFrequencyData();
  68208. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68209. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68210. // Draw the frequency domain chart.
  68211. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68212. var value = workingArray[i];
  68213. var percent = value / this.BARGRAPHAMPLITUDE;
  68214. var height = this.DEBUGCANVASSIZE.height * percent;
  68215. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68216. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68217. var hue = i / this.getFrequencyBinCount() * 360;
  68218. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68219. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68220. }
  68221. }
  68222. }
  68223. };
  68224. /**
  68225. * Stops rendering the debug canvas and removes it
  68226. */
  68227. Analyser.prototype.stopDebugCanvas = function () {
  68228. if (this._debugCanvas) {
  68229. if (this._registerFunc) {
  68230. this._scene.unregisterBeforeRender(this._registerFunc);
  68231. this._registerFunc = null;
  68232. }
  68233. document.body.removeChild(this._debugCanvas);
  68234. this._debugCanvas = null;
  68235. this._debugCanvasContext = null;
  68236. }
  68237. };
  68238. /**
  68239. * Connects two audio nodes
  68240. * @param inputAudioNode defines first node to connect
  68241. * @param outputAudioNode defines second node to connect
  68242. */
  68243. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68244. if (this._audioEngine.canUseWebAudio) {
  68245. inputAudioNode.connect(this._webAudioAnalyser);
  68246. this._webAudioAnalyser.connect(outputAudioNode);
  68247. }
  68248. };
  68249. /**
  68250. * Releases all associated resources
  68251. */
  68252. Analyser.prototype.dispose = function () {
  68253. if (this._audioEngine.canUseWebAudio) {
  68254. this._webAudioAnalyser.disconnect();
  68255. }
  68256. };
  68257. return Analyser;
  68258. }());
  68259. BABYLON.Analyser = Analyser;
  68260. })(BABYLON || (BABYLON = {}));
  68261. //# sourceMappingURL=babylon.analyser.js.map
  68262. var BABYLON;
  68263. (function (BABYLON) {
  68264. /**
  68265. * Wraps one or more Sound objects and selects one with random weight for playback.
  68266. */
  68267. var WeightedSound = /** @class */ (function () {
  68268. /**
  68269. * Creates a new WeightedSound from the list of sounds given.
  68270. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68271. * @param sounds Array of Sounds that will be selected from.
  68272. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68273. */
  68274. function WeightedSound(loop, sounds, weights) {
  68275. var _this = this;
  68276. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68277. this.loop = false;
  68278. this._coneInnerAngle = 360;
  68279. this._coneOuterAngle = 360;
  68280. this._volume = 1;
  68281. /** A Sound is currently playing. */
  68282. this.isPlaying = false;
  68283. /** A Sound is currently paused. */
  68284. this.isPaused = false;
  68285. this._sounds = [];
  68286. this._weights = [];
  68287. if (sounds.length !== weights.length) {
  68288. throw new Error('Sounds length does not equal weights length');
  68289. }
  68290. this.loop = loop;
  68291. this._weights = weights;
  68292. // Normalize the weights
  68293. var weightSum = 0;
  68294. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68295. var weight = weights_1[_i];
  68296. weightSum += weight;
  68297. }
  68298. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68299. for (var i = 0; i < this._weights.length; i++) {
  68300. this._weights[i] *= invWeightSum;
  68301. }
  68302. this._sounds = sounds;
  68303. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68304. var sound = _b[_a];
  68305. sound.onEndedObservable.add(function () { _this._onended(); });
  68306. }
  68307. }
  68308. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68309. /**
  68310. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68311. */
  68312. get: function () {
  68313. return this._coneInnerAngle;
  68314. },
  68315. /**
  68316. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68317. */
  68318. set: function (value) {
  68319. if (value !== this._coneInnerAngle) {
  68320. if (this._coneOuterAngle < value) {
  68321. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68322. return;
  68323. }
  68324. this._coneInnerAngle = value;
  68325. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68326. var sound = _a[_i];
  68327. sound.directionalConeInnerAngle = value;
  68328. }
  68329. }
  68330. },
  68331. enumerable: true,
  68332. configurable: true
  68333. });
  68334. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68335. /**
  68336. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68337. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68338. */
  68339. get: function () {
  68340. return this._coneOuterAngle;
  68341. },
  68342. /**
  68343. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68344. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68345. */
  68346. set: function (value) {
  68347. if (value !== this._coneOuterAngle) {
  68348. if (value < this._coneInnerAngle) {
  68349. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68350. return;
  68351. }
  68352. this._coneOuterAngle = value;
  68353. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68354. var sound = _a[_i];
  68355. sound.directionalConeOuterAngle = value;
  68356. }
  68357. }
  68358. },
  68359. enumerable: true,
  68360. configurable: true
  68361. });
  68362. Object.defineProperty(WeightedSound.prototype, "volume", {
  68363. /**
  68364. * Playback volume.
  68365. */
  68366. get: function () {
  68367. return this._volume;
  68368. },
  68369. /**
  68370. * Playback volume.
  68371. */
  68372. set: function (value) {
  68373. if (value !== this._volume) {
  68374. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68375. var sound = _a[_i];
  68376. sound.setVolume(value);
  68377. }
  68378. }
  68379. },
  68380. enumerable: true,
  68381. configurable: true
  68382. });
  68383. WeightedSound.prototype._onended = function () {
  68384. if (this._currentIndex !== undefined) {
  68385. this._sounds[this._currentIndex].autoplay = false;
  68386. }
  68387. if (this.loop && this.isPlaying) {
  68388. this.play();
  68389. }
  68390. else {
  68391. this.isPlaying = false;
  68392. }
  68393. };
  68394. /**
  68395. * Suspend playback
  68396. */
  68397. WeightedSound.prototype.pause = function () {
  68398. this.isPaused = true;
  68399. if (this._currentIndex !== undefined) {
  68400. this._sounds[this._currentIndex].pause();
  68401. }
  68402. };
  68403. /**
  68404. * Stop playback
  68405. */
  68406. WeightedSound.prototype.stop = function () {
  68407. this.isPlaying = false;
  68408. if (this._currentIndex !== undefined) {
  68409. this._sounds[this._currentIndex].stop();
  68410. }
  68411. };
  68412. /**
  68413. * Start playback.
  68414. * @param startOffset Position the clip head at a specific time in seconds.
  68415. */
  68416. WeightedSound.prototype.play = function (startOffset) {
  68417. if (!this.isPaused) {
  68418. this.stop();
  68419. var randomValue = Math.random();
  68420. var total = 0;
  68421. for (var i = 0; i < this._weights.length; i++) {
  68422. total += this._weights[i];
  68423. if (randomValue <= total) {
  68424. this._currentIndex = i;
  68425. break;
  68426. }
  68427. }
  68428. }
  68429. var sound = this._sounds[this._currentIndex];
  68430. if (sound.isReady()) {
  68431. sound.play(0, this.isPaused ? undefined : startOffset);
  68432. }
  68433. else {
  68434. sound.autoplay = true;
  68435. }
  68436. this.isPlaying = true;
  68437. this.isPaused = false;
  68438. };
  68439. return WeightedSound;
  68440. }());
  68441. BABYLON.WeightedSound = WeightedSound;
  68442. })(BABYLON || (BABYLON = {}));
  68443. //# sourceMappingURL=babylon.weightedsound.js.map
  68444. var BABYLON;
  68445. (function (BABYLON) {
  68446. // Adds the parser to the scene parsers.
  68447. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68448. // TODO: add sound
  68449. var loadedSounds = [];
  68450. var loadedSound;
  68451. container.sounds = container.sounds || [];
  68452. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68453. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68454. var parsedSound = parsedData.sounds[index];
  68455. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68456. if (!parsedSound.url)
  68457. parsedSound.url = parsedSound.name;
  68458. if (!loadedSounds[parsedSound.url]) {
  68459. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68460. loadedSounds[parsedSound.url] = loadedSound;
  68461. container.sounds.push(loadedSound);
  68462. }
  68463. else {
  68464. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68465. }
  68466. }
  68467. else {
  68468. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68469. }
  68470. }
  68471. }
  68472. loadedSounds = [];
  68473. });
  68474. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68475. get: function () {
  68476. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68477. if (!compo) {
  68478. compo = new AudioSceneComponent(this);
  68479. this._addComponent(compo);
  68480. }
  68481. if (!this._mainSoundTrack) {
  68482. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68483. }
  68484. return this._mainSoundTrack;
  68485. },
  68486. enumerable: true,
  68487. configurable: true
  68488. });
  68489. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68490. var index;
  68491. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68492. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68493. return this.mainSoundTrack.soundCollection[index];
  68494. }
  68495. }
  68496. if (this.soundTracks) {
  68497. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68498. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68499. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68500. return this.soundTracks[sdIndex].soundCollection[index];
  68501. }
  68502. }
  68503. }
  68504. }
  68505. return null;
  68506. };
  68507. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68508. get: function () {
  68509. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68510. if (!compo) {
  68511. compo = new AudioSceneComponent(this);
  68512. this._addComponent(compo);
  68513. }
  68514. return compo.audioEnabled;
  68515. },
  68516. set: function (value) {
  68517. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68518. if (!compo) {
  68519. compo = new AudioSceneComponent(this);
  68520. this._addComponent(compo);
  68521. }
  68522. if (value) {
  68523. compo.enableAudio();
  68524. }
  68525. else {
  68526. compo.disableAudio();
  68527. }
  68528. },
  68529. enumerable: true,
  68530. configurable: true
  68531. });
  68532. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  68533. get: function () {
  68534. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68535. if (!compo) {
  68536. compo = new AudioSceneComponent(this);
  68537. this._addComponent(compo);
  68538. }
  68539. return compo.headphone;
  68540. },
  68541. set: function (value) {
  68542. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68543. if (!compo) {
  68544. compo = new AudioSceneComponent(this);
  68545. this._addComponent(compo);
  68546. }
  68547. if (value) {
  68548. compo.switchAudioModeForHeadphones();
  68549. }
  68550. else {
  68551. compo.switchAudioModeForNormalSpeakers();
  68552. }
  68553. },
  68554. enumerable: true,
  68555. configurable: true
  68556. });
  68557. /**
  68558. * Defines the sound scene component responsible to manage any sounds
  68559. * in a given scene.
  68560. */
  68561. var AudioSceneComponent = /** @class */ (function () {
  68562. /**
  68563. * Creates a new instance of the component for the given scene
  68564. * @param scene Defines the scene to register the component in
  68565. */
  68566. function AudioSceneComponent(scene) {
  68567. /**
  68568. * The component name helpfull to identify the component in the list of scene components.
  68569. */
  68570. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  68571. this._audioEnabled = true;
  68572. this._headphone = false;
  68573. this.scene = scene;
  68574. scene.soundTracks = new Array();
  68575. scene.sounds = new Array();
  68576. }
  68577. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  68578. /**
  68579. * Gets whether audio is enabled or not.
  68580. * Please use related enable/disable method to switch state.
  68581. */
  68582. get: function () {
  68583. return this._audioEnabled;
  68584. },
  68585. enumerable: true,
  68586. configurable: true
  68587. });
  68588. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  68589. /**
  68590. * Gets whether audio is outputing to headphone or not.
  68591. * Please use the according Switch methods to change output.
  68592. */
  68593. get: function () {
  68594. return this._headphone;
  68595. },
  68596. enumerable: true,
  68597. configurable: true
  68598. });
  68599. /**
  68600. * Registers the component in a given scene
  68601. */
  68602. AudioSceneComponent.prototype.register = function () {
  68603. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  68604. };
  68605. /**
  68606. * Rebuilds the elements related to this component in case of
  68607. * context lost for instance.
  68608. */
  68609. AudioSceneComponent.prototype.rebuild = function () {
  68610. // Nothing to do here. (Not rendering related)
  68611. };
  68612. /**
  68613. * Serializes the component data to the specified json object
  68614. * @param serializationObject The object to serialize to
  68615. */
  68616. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  68617. serializationObject.sounds = [];
  68618. if (this.scene.soundTracks) {
  68619. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  68620. var soundtrack = this.scene.soundTracks[index];
  68621. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68622. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68623. }
  68624. }
  68625. }
  68626. };
  68627. /**
  68628. * Adds all the element from the container to the scene
  68629. * @param container the container holding the elements
  68630. */
  68631. AudioSceneComponent.prototype.addFromContainer = function (container) {
  68632. var _this = this;
  68633. if (!container.sounds) {
  68634. return;
  68635. }
  68636. container.sounds.forEach(function (sound) {
  68637. sound.play();
  68638. sound.autoplay = true;
  68639. _this.scene.mainSoundTrack.AddSound(sound);
  68640. });
  68641. };
  68642. /**
  68643. * Removes all the elements in the container from the scene
  68644. * @param container contains the elements to remove
  68645. */
  68646. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  68647. var _this = this;
  68648. if (!container.sounds) {
  68649. return;
  68650. }
  68651. container.sounds.forEach(function (sound) {
  68652. sound.stop();
  68653. sound.autoplay = false;
  68654. _this.scene.mainSoundTrack.RemoveSound(sound);
  68655. });
  68656. };
  68657. /**
  68658. * Disposes the component and the associated ressources.
  68659. */
  68660. AudioSceneComponent.prototype.dispose = function () {
  68661. var scene = this.scene;
  68662. if (scene._mainSoundTrack) {
  68663. scene.mainSoundTrack.dispose();
  68664. }
  68665. if (scene.soundTracks) {
  68666. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  68667. scene.soundTracks[scIndex].dispose();
  68668. }
  68669. }
  68670. };
  68671. /**
  68672. * Disables audio in the associated scene.
  68673. */
  68674. AudioSceneComponent.prototype.disableAudio = function () {
  68675. var scene = this.scene;
  68676. this._audioEnabled = false;
  68677. var i;
  68678. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68679. scene.mainSoundTrack.soundCollection[i].pause();
  68680. }
  68681. if (scene.soundTracks) {
  68682. for (i = 0; i < scene.soundTracks.length; i++) {
  68683. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68684. scene.soundTracks[i].soundCollection[j].pause();
  68685. }
  68686. }
  68687. }
  68688. };
  68689. /**
  68690. * Enables audio in the associated scene.
  68691. */
  68692. AudioSceneComponent.prototype.enableAudio = function () {
  68693. var scene = this.scene;
  68694. this._audioEnabled = true;
  68695. var i;
  68696. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68697. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  68698. scene.mainSoundTrack.soundCollection[i].play();
  68699. }
  68700. }
  68701. if (scene.soundTracks) {
  68702. for (i = 0; i < scene.soundTracks.length; i++) {
  68703. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68704. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  68705. scene.soundTracks[i].soundCollection[j].play();
  68706. }
  68707. }
  68708. }
  68709. }
  68710. };
  68711. /**
  68712. * Switch audio to headphone output.
  68713. */
  68714. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  68715. var scene = this.scene;
  68716. this._headphone = true;
  68717. scene.mainSoundTrack.switchPanningModelToHRTF();
  68718. if (scene.soundTracks) {
  68719. for (var i = 0; i < scene.soundTracks.length; i++) {
  68720. scene.soundTracks[i].switchPanningModelToHRTF();
  68721. }
  68722. }
  68723. };
  68724. /**
  68725. * Switch audio to normal speakers.
  68726. */
  68727. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  68728. var scene = this.scene;
  68729. this._headphone = false;
  68730. scene.mainSoundTrack.switchPanningModelToEqualPower();
  68731. if (scene.soundTracks) {
  68732. for (var i = 0; i < scene.soundTracks.length; i++) {
  68733. scene.soundTracks[i].switchPanningModelToEqualPower();
  68734. }
  68735. }
  68736. };
  68737. AudioSceneComponent.prototype._afterRender = function () {
  68738. var scene = this.scene;
  68739. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  68740. return;
  68741. }
  68742. var listeningCamera;
  68743. var audioEngine = BABYLON.Engine.audioEngine;
  68744. if (scene.activeCameras.length > 0) {
  68745. listeningCamera = scene.activeCameras[0];
  68746. }
  68747. else {
  68748. listeningCamera = scene.activeCamera;
  68749. }
  68750. if (listeningCamera && audioEngine.audioContext) {
  68751. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  68752. // for VR cameras
  68753. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  68754. listeningCamera = listeningCamera.rigCameras[0];
  68755. }
  68756. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  68757. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  68758. cameraDirection.normalize();
  68759. // To avoid some errors on GearVR
  68760. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  68761. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  68762. }
  68763. var i;
  68764. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68765. var sound = scene.mainSoundTrack.soundCollection[i];
  68766. if (sound.useCustomAttenuation) {
  68767. sound.updateDistanceFromListener();
  68768. }
  68769. }
  68770. if (scene.soundTracks) {
  68771. for (i = 0; i < scene.soundTracks.length; i++) {
  68772. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68773. sound = scene.soundTracks[i].soundCollection[j];
  68774. if (sound.useCustomAttenuation) {
  68775. sound.updateDistanceFromListener();
  68776. }
  68777. }
  68778. }
  68779. }
  68780. }
  68781. };
  68782. return AudioSceneComponent;
  68783. }());
  68784. BABYLON.AudioSceneComponent = AudioSceneComponent;
  68785. })(BABYLON || (BABYLON = {}));
  68786. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  68787. var BABYLON;
  68788. (function (BABYLON) {
  68789. /**
  68790. * This defines an action helpful to play a defined sound on a triggered action.
  68791. */
  68792. var PlaySoundAction = /** @class */ (function (_super) {
  68793. __extends(PlaySoundAction, _super);
  68794. /**
  68795. * Instantiate the action
  68796. * @param triggerOptions defines the trigger options
  68797. * @param sound defines the sound to play
  68798. * @param condition defines the trigger related conditions
  68799. */
  68800. function PlaySoundAction(triggerOptions, sound, condition) {
  68801. var _this = _super.call(this, triggerOptions, condition) || this;
  68802. _this._sound = sound;
  68803. return _this;
  68804. }
  68805. /** @hidden */
  68806. PlaySoundAction.prototype._prepare = function () {
  68807. };
  68808. /**
  68809. * Execute the action and play the sound.
  68810. */
  68811. PlaySoundAction.prototype.execute = function () {
  68812. if (this._sound !== undefined)
  68813. this._sound.play();
  68814. };
  68815. /**
  68816. * Serializes the actions and its related information.
  68817. * @param parent defines the object to serialize in
  68818. * @returns the serialized object
  68819. */
  68820. PlaySoundAction.prototype.serialize = function (parent) {
  68821. return _super.prototype._serialize.call(this, {
  68822. name: "PlaySoundAction",
  68823. properties: [{ name: "sound", value: this._sound.name }]
  68824. }, parent);
  68825. };
  68826. return PlaySoundAction;
  68827. }(BABYLON.Action));
  68828. BABYLON.PlaySoundAction = PlaySoundAction;
  68829. /**
  68830. * This defines an action helpful to stop a defined sound on a triggered action.
  68831. */
  68832. var StopSoundAction = /** @class */ (function (_super) {
  68833. __extends(StopSoundAction, _super);
  68834. /**
  68835. * Instantiate the action
  68836. * @param triggerOptions defines the trigger options
  68837. * @param sound defines the sound to stop
  68838. * @param condition defines the trigger related conditions
  68839. */
  68840. function StopSoundAction(triggerOptions, sound, condition) {
  68841. var _this = _super.call(this, triggerOptions, condition) || this;
  68842. _this._sound = sound;
  68843. return _this;
  68844. }
  68845. /** @hidden */
  68846. StopSoundAction.prototype._prepare = function () {
  68847. };
  68848. /**
  68849. * Execute the action and stop the sound.
  68850. */
  68851. StopSoundAction.prototype.execute = function () {
  68852. if (this._sound !== undefined)
  68853. this._sound.stop();
  68854. };
  68855. /**
  68856. * Serializes the actions and its related information.
  68857. * @param parent defines the object to serialize in
  68858. * @returns the serialized object
  68859. */
  68860. StopSoundAction.prototype.serialize = function (parent) {
  68861. return _super.prototype._serialize.call(this, {
  68862. name: "StopSoundAction",
  68863. properties: [{ name: "sound", value: this._sound.name }]
  68864. }, parent);
  68865. };
  68866. return StopSoundAction;
  68867. }(BABYLON.Action));
  68868. BABYLON.StopSoundAction = StopSoundAction;
  68869. })(BABYLON || (BABYLON = {}));
  68870. //# sourceMappingURL=babylon.directAudioActions.js.map
  68871. var BABYLON;
  68872. (function (BABYLON) {
  68873. var CubeTexture = /** @class */ (function (_super) {
  68874. __extends(CubeTexture, _super);
  68875. /**
  68876. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  68877. * as prefiltered data.
  68878. * @param rootUrl defines the url of the texture or the root name of the six images
  68879. * @param scene defines the scene the texture is attached to
  68880. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  68881. * @param noMipmap defines if mipmaps should be created or not
  68882. * @param files defines the six files to load for the different faces
  68883. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  68884. * @param onError defines a callback triggered in case of error during load
  68885. * @param format defines the internal format to use for the texture once loaded
  68886. * @param prefiltered defines whether or not the texture is created from prefiltered data
  68887. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  68888. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  68889. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  68890. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  68891. * @return the cube texture
  68892. */
  68893. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  68894. if (extensions === void 0) { extensions = null; }
  68895. if (noMipmap === void 0) { noMipmap = false; }
  68896. if (files === void 0) { files = null; }
  68897. if (onLoad === void 0) { onLoad = null; }
  68898. if (onError === void 0) { onError = null; }
  68899. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68900. if (prefiltered === void 0) { prefiltered = false; }
  68901. if (forcedExtension === void 0) { forcedExtension = null; }
  68902. if (createPolynomials === void 0) { createPolynomials = false; }
  68903. if (lodScale === void 0) { lodScale = 0.8; }
  68904. if (lodOffset === void 0) { lodOffset = 0; }
  68905. var _this = _super.call(this, scene) || this;
  68906. /**
  68907. * Gets or sets the center of the bounding box associated with the cube texture
  68908. * It must define where the camera used to render the texture was set
  68909. */
  68910. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  68911. _this._rotationY = 0;
  68912. /** @hidden */
  68913. _this._prefiltered = false;
  68914. _this.name = rootUrl;
  68915. _this.url = rootUrl;
  68916. _this._noMipmap = noMipmap;
  68917. _this.hasAlpha = false;
  68918. _this._format = format;
  68919. _this.isCube = true;
  68920. _this._textureMatrix = BABYLON.Matrix.Identity();
  68921. _this._createPolynomials = createPolynomials;
  68922. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68923. if (!rootUrl && !files) {
  68924. return _this;
  68925. }
  68926. var lastDot = rootUrl.lastIndexOf(".");
  68927. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  68928. var isDDS = (extension === ".dds");
  68929. var isEnv = (extension === ".env");
  68930. if (isEnv) {
  68931. _this.gammaSpace = false;
  68932. _this._prefiltered = false;
  68933. }
  68934. else {
  68935. _this._prefiltered = prefiltered;
  68936. if (prefiltered) {
  68937. _this.gammaSpace = false;
  68938. }
  68939. }
  68940. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  68941. if (!files) {
  68942. if (!isEnv && !isDDS && !extensions) {
  68943. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  68944. }
  68945. files = [];
  68946. if (extensions) {
  68947. for (var index = 0; index < extensions.length; index++) {
  68948. files.push(rootUrl + extensions[index]);
  68949. }
  68950. }
  68951. }
  68952. _this._files = files;
  68953. if (!_this._texture) {
  68954. if (!scene.useDelayedTextureLoading) {
  68955. if (prefiltered) {
  68956. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  68957. }
  68958. else {
  68959. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  68960. }
  68961. }
  68962. else {
  68963. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68964. }
  68965. }
  68966. else if (onLoad) {
  68967. if (_this._texture.isReady) {
  68968. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  68969. }
  68970. else {
  68971. _this._texture.onLoadedObservable.add(onLoad);
  68972. }
  68973. }
  68974. return _this;
  68975. }
  68976. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  68977. get: function () {
  68978. return this._boundingBoxSize;
  68979. },
  68980. /**
  68981. * Gets or sets the size of the bounding box associated with the cube texture
  68982. * When defined, the cubemap will switch to local mode
  68983. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  68984. * @example https://www.babylonjs-playground.com/#RNASML
  68985. */
  68986. set: function (value) {
  68987. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  68988. return;
  68989. }
  68990. this._boundingBoxSize = value;
  68991. var scene = this.getScene();
  68992. if (scene) {
  68993. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  68994. }
  68995. },
  68996. enumerable: true,
  68997. configurable: true
  68998. });
  68999. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69000. /**
  69001. * Gets texture matrix rotation angle around Y axis radians.
  69002. */
  69003. get: function () {
  69004. return this._rotationY;
  69005. },
  69006. /**
  69007. * Sets texture matrix rotation angle around Y axis in radians.
  69008. */
  69009. set: function (value) {
  69010. this._rotationY = value;
  69011. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69012. },
  69013. enumerable: true,
  69014. configurable: true
  69015. });
  69016. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69017. var rootUrlKey = "";
  69018. files.forEach(function (url) { return rootUrlKey += url; });
  69019. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69020. };
  69021. /**
  69022. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69023. * @param url defines the url of the prefiltered texture
  69024. * @param scene defines the scene the texture is attached to
  69025. * @param forcedExtension defines the extension of the file if different from the url
  69026. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69027. * @return the prefiltered texture
  69028. */
  69029. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69030. if (forcedExtension === void 0) { forcedExtension = null; }
  69031. if (createPolynomials === void 0) { createPolynomials = true; }
  69032. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69033. };
  69034. // Methods
  69035. CubeTexture.prototype.delayLoad = function () {
  69036. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69037. return;
  69038. }
  69039. var scene = this.getScene();
  69040. if (!scene) {
  69041. return;
  69042. }
  69043. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69044. this._texture = this._getFromCache(this.url, this._noMipmap);
  69045. if (!this._texture) {
  69046. if (this._prefiltered) {
  69047. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69048. }
  69049. else {
  69050. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69051. }
  69052. }
  69053. };
  69054. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69055. return this._textureMatrix;
  69056. };
  69057. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69058. this._textureMatrix = value;
  69059. };
  69060. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69061. var texture = BABYLON.SerializationHelper.Parse(function () {
  69062. var prefiltered = false;
  69063. if (parsedTexture.prefiltered) {
  69064. prefiltered = parsedTexture.prefiltered;
  69065. }
  69066. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69067. }, parsedTexture, scene);
  69068. // Local Cubemaps
  69069. if (parsedTexture.boundingBoxPosition) {
  69070. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69071. }
  69072. if (parsedTexture.boundingBoxSize) {
  69073. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69074. }
  69075. // Animations
  69076. if (parsedTexture.animations) {
  69077. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69078. var parsedAnimation = parsedTexture.animations[animationIndex];
  69079. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69080. }
  69081. }
  69082. return texture;
  69083. };
  69084. CubeTexture.prototype.clone = function () {
  69085. var _this = this;
  69086. return BABYLON.SerializationHelper.Clone(function () {
  69087. var scene = _this.getScene();
  69088. if (!scene) {
  69089. return _this;
  69090. }
  69091. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69092. }, this);
  69093. };
  69094. __decorate([
  69095. BABYLON.serialize("rotationY")
  69096. ], CubeTexture.prototype, "rotationY", null);
  69097. return CubeTexture;
  69098. }(BABYLON.BaseTexture));
  69099. BABYLON.CubeTexture = CubeTexture;
  69100. })(BABYLON || (BABYLON = {}));
  69101. //# sourceMappingURL=babylon.cubeTexture.js.map
  69102. var BABYLON;
  69103. (function (BABYLON) {
  69104. /**
  69105. * Raw cube texture where the raw buffers are passed in
  69106. */
  69107. var RawCubeTexture = /** @class */ (function (_super) {
  69108. __extends(RawCubeTexture, _super);
  69109. /**
  69110. * Creates a cube texture where the raw buffers are passed in.
  69111. * @param scene defines the scene the texture is attached to
  69112. * @param data defines the array of data to use to create each face
  69113. * @param size defines the size of the textures
  69114. * @param format defines the format of the data
  69115. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69116. * @param generateMipMaps defines if the engine should generate the mip levels
  69117. * @param invertY defines if data must be stored with Y axis inverted
  69118. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69119. * @param compression defines the compression used (null by default)
  69120. */
  69121. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69122. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69123. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69124. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69125. if (invertY === void 0) { invertY = false; }
  69126. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69127. if (compression === void 0) { compression = null; }
  69128. var _this = _super.call(this, "", scene) || this;
  69129. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69130. return _this;
  69131. }
  69132. /**
  69133. * Updates the raw cube texture.
  69134. * @param data defines the data to store
  69135. * @param format defines the data format
  69136. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69137. * @param invertY defines if data must be stored with Y axis inverted
  69138. * @param compression defines the compression used (null by default)
  69139. * @param level defines which level of the texture to update
  69140. */
  69141. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69142. if (compression === void 0) { compression = null; }
  69143. if (level === void 0) { level = 0; }
  69144. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69145. };
  69146. /**
  69147. * Updates a raw cube texture with RGBD encoded data.
  69148. * @param data defines the array of data [mipmap][face] to use to create each face
  69149. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69150. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69151. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69152. * @returns a promsie that resolves when the operation is complete
  69153. */
  69154. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69155. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69156. if (lodScale === void 0) { lodScale = 0.8; }
  69157. if (lodOffset === void 0) { lodOffset = 0; }
  69158. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69159. };
  69160. /**
  69161. * Clones the raw cube texture.
  69162. * @return a new cube texture
  69163. */
  69164. RawCubeTexture.prototype.clone = function () {
  69165. var _this = this;
  69166. return BABYLON.SerializationHelper.Clone(function () {
  69167. var scene = _this.getScene();
  69168. var internalTexture = _this._texture;
  69169. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69170. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69171. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69172. }
  69173. return texture;
  69174. }, this);
  69175. };
  69176. /** @hidden */
  69177. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69178. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69179. internalTexture._bufferViewArrayArray = data;
  69180. internalTexture._lodGenerationScale = lodScale;
  69181. internalTexture._lodGenerationOffset = lodOffset;
  69182. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69183. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69184. internalTexture.isReady = true;
  69185. });
  69186. };
  69187. return RawCubeTexture;
  69188. }(BABYLON.CubeTexture));
  69189. BABYLON.RawCubeTexture = RawCubeTexture;
  69190. })(BABYLON || (BABYLON = {}));
  69191. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69192. var BABYLON;
  69193. (function (BABYLON) {
  69194. var RenderTargetTexture = /** @class */ (function (_super) {
  69195. __extends(RenderTargetTexture, _super);
  69196. /**
  69197. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69198. * or used a shadow, depth texture...
  69199. * @param name The friendly name of the texture
  69200. * @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)
  69201. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69202. * @param generateMipMaps True if mip maps need to be generated after render.
  69203. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69204. * @param type The type of the buffer in the RTT (int, half float, float...)
  69205. * @param isCube True if a cube texture needs to be created
  69206. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69207. * @param generateDepthBuffer True to generate a depth buffer
  69208. * @param generateStencilBuffer True to generate a stencil buffer
  69209. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69210. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69211. */
  69212. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69213. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69214. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69215. if (isCube === void 0) { isCube = false; }
  69216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69217. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69218. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69219. if (isMulti === void 0) { isMulti = false; }
  69220. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69221. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69222. _this.isCube = isCube;
  69223. _this.renderParticles = true;
  69224. _this.renderSprites = false;
  69225. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69226. _this.ignoreCameraViewport = false;
  69227. // Events
  69228. /**
  69229. * An event triggered when the texture is unbind.
  69230. */
  69231. _this.onBeforeBindObservable = new BABYLON.Observable();
  69232. /**
  69233. * An event triggered when the texture is unbind.
  69234. */
  69235. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69236. /**
  69237. * An event triggered before rendering the texture
  69238. */
  69239. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69240. /**
  69241. * An event triggered after rendering the texture
  69242. */
  69243. _this.onAfterRenderObservable = new BABYLON.Observable();
  69244. /**
  69245. * An event triggered after the texture clear
  69246. */
  69247. _this.onClearObservable = new BABYLON.Observable();
  69248. _this._currentRefreshId = -1;
  69249. _this._refreshRate = 1;
  69250. _this._samples = 1;
  69251. /**
  69252. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69253. * It must define where the camera used to render the texture is set
  69254. */
  69255. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69256. scene = _this.getScene();
  69257. if (!scene) {
  69258. return _this;
  69259. }
  69260. _this.renderList = new Array();
  69261. _this._engine = scene.getEngine();
  69262. _this.name = name;
  69263. _this.isRenderTarget = true;
  69264. _this._initialSizeParameter = size;
  69265. _this._processSizeParameter(size);
  69266. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69267. });
  69268. _this._generateMipMaps = generateMipMaps ? true : false;
  69269. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69270. // Rendering groups
  69271. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69272. _this._renderingManager._useSceneAutoClearSetup = true;
  69273. if (isMulti) {
  69274. return _this;
  69275. }
  69276. _this._renderTargetOptions = {
  69277. generateMipMaps: generateMipMaps,
  69278. type: type,
  69279. format: format,
  69280. samplingMode: samplingMode,
  69281. generateDepthBuffer: generateDepthBuffer,
  69282. generateStencilBuffer: generateStencilBuffer
  69283. };
  69284. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69285. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69286. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69287. }
  69288. if (isCube) {
  69289. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69290. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69291. _this._textureMatrix = BABYLON.Matrix.Identity();
  69292. }
  69293. else {
  69294. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69295. }
  69296. return _this;
  69297. }
  69298. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69299. get: function () {
  69300. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69301. },
  69302. enumerable: true,
  69303. configurable: true
  69304. });
  69305. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69306. get: function () {
  69307. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69308. },
  69309. enumerable: true,
  69310. configurable: true
  69311. });
  69312. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69313. get: function () {
  69314. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69315. },
  69316. enumerable: true,
  69317. configurable: true
  69318. });
  69319. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69320. /**
  69321. * Use this list to define the list of mesh you want to render.
  69322. */
  69323. get: function () {
  69324. return this._renderList;
  69325. },
  69326. set: function (value) {
  69327. this._renderList = value;
  69328. if (this._renderList) {
  69329. this._hookArray(this._renderList);
  69330. }
  69331. },
  69332. enumerable: true,
  69333. configurable: true
  69334. });
  69335. RenderTargetTexture.prototype._hookArray = function (array) {
  69336. var _this = this;
  69337. var oldPush = array.push;
  69338. array.push = function () {
  69339. var items = [];
  69340. for (var _i = 0; _i < arguments.length; _i++) {
  69341. items[_i] = arguments[_i];
  69342. }
  69343. var result = oldPush.apply(array, items);
  69344. _this.getScene().meshes.forEach(function (mesh) {
  69345. mesh._markSubMeshesAsLightDirty();
  69346. });
  69347. return result;
  69348. };
  69349. var oldSplice = array.splice;
  69350. array.splice = function (index, deleteCount) {
  69351. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69352. _this.getScene().meshes.forEach(function (mesh) {
  69353. mesh._markSubMeshesAsLightDirty();
  69354. });
  69355. return deleted;
  69356. };
  69357. };
  69358. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69359. set: function (callback) {
  69360. if (this._onAfterUnbindObserver) {
  69361. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69362. }
  69363. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69364. },
  69365. enumerable: true,
  69366. configurable: true
  69367. });
  69368. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69369. set: function (callback) {
  69370. if (this._onBeforeRenderObserver) {
  69371. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69372. }
  69373. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69374. },
  69375. enumerable: true,
  69376. configurable: true
  69377. });
  69378. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69379. set: function (callback) {
  69380. if (this._onAfterRenderObserver) {
  69381. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69382. }
  69383. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69384. },
  69385. enumerable: true,
  69386. configurable: true
  69387. });
  69388. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69389. set: function (callback) {
  69390. if (this._onClearObserver) {
  69391. this.onClearObservable.remove(this._onClearObserver);
  69392. }
  69393. this._onClearObserver = this.onClearObservable.add(callback);
  69394. },
  69395. enumerable: true,
  69396. configurable: true
  69397. });
  69398. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69399. get: function () {
  69400. return this._renderTargetOptions;
  69401. },
  69402. enumerable: true,
  69403. configurable: true
  69404. });
  69405. RenderTargetTexture.prototype._onRatioRescale = function () {
  69406. if (this._sizeRatio) {
  69407. this.resize(this._initialSizeParameter);
  69408. }
  69409. };
  69410. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69411. get: function () {
  69412. return this._boundingBoxSize;
  69413. },
  69414. /**
  69415. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69416. * When defined, the cubemap will switch to local mode
  69417. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69418. * @example https://www.babylonjs-playground.com/#RNASML
  69419. */
  69420. set: function (value) {
  69421. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69422. return;
  69423. }
  69424. this._boundingBoxSize = value;
  69425. var scene = this.getScene();
  69426. if (scene) {
  69427. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69428. }
  69429. },
  69430. enumerable: true,
  69431. configurable: true
  69432. });
  69433. /**
  69434. * Creates a depth stencil texture.
  69435. * This is only available in WebGL 2 or with the depth texture extension available.
  69436. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69437. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69438. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69439. */
  69440. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69441. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69442. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69443. if (generateStencil === void 0) { generateStencil = false; }
  69444. if (!this.getScene()) {
  69445. return;
  69446. }
  69447. var engine = this.getScene().getEngine();
  69448. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69449. bilinearFiltering: bilinearFiltering,
  69450. comparisonFunction: comparisonFunction,
  69451. generateStencil: generateStencil,
  69452. isCube: this.isCube
  69453. });
  69454. engine.setFrameBufferDepthStencilTexture(this);
  69455. };
  69456. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69457. if (size.ratio) {
  69458. this._sizeRatio = size.ratio;
  69459. this._size = {
  69460. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69461. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69462. };
  69463. }
  69464. else {
  69465. this._size = size;
  69466. }
  69467. };
  69468. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69469. get: function () {
  69470. return this._samples;
  69471. },
  69472. set: function (value) {
  69473. if (this._samples === value) {
  69474. return;
  69475. }
  69476. var scene = this.getScene();
  69477. if (!scene) {
  69478. return;
  69479. }
  69480. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69481. },
  69482. enumerable: true,
  69483. configurable: true
  69484. });
  69485. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69486. this._currentRefreshId = -1;
  69487. };
  69488. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69489. get: function () {
  69490. return this._refreshRate;
  69491. },
  69492. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69493. set: function (value) {
  69494. this._refreshRate = value;
  69495. this.resetRefreshCounter();
  69496. },
  69497. enumerable: true,
  69498. configurable: true
  69499. });
  69500. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69501. if (!this._postProcessManager) {
  69502. var scene = this.getScene();
  69503. if (!scene) {
  69504. return;
  69505. }
  69506. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69507. this._postProcesses = new Array();
  69508. }
  69509. this._postProcesses.push(postProcess);
  69510. this._postProcesses[0].autoClear = false;
  69511. };
  69512. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  69513. if (!this._postProcesses) {
  69514. return;
  69515. }
  69516. if (dispose) {
  69517. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  69518. var postProcess = _a[_i];
  69519. postProcess.dispose();
  69520. }
  69521. }
  69522. this._postProcesses = [];
  69523. };
  69524. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  69525. if (!this._postProcesses) {
  69526. return;
  69527. }
  69528. var index = this._postProcesses.indexOf(postProcess);
  69529. if (index === -1) {
  69530. return;
  69531. }
  69532. this._postProcesses.splice(index, 1);
  69533. if (this._postProcesses.length > 0) {
  69534. this._postProcesses[0].autoClear = false;
  69535. }
  69536. };
  69537. /** @hidden */
  69538. RenderTargetTexture.prototype._shouldRender = function () {
  69539. if (this._currentRefreshId === -1) { // At least render once
  69540. this._currentRefreshId = 1;
  69541. return true;
  69542. }
  69543. if (this.refreshRate === this._currentRefreshId) {
  69544. this._currentRefreshId = 1;
  69545. return true;
  69546. }
  69547. this._currentRefreshId++;
  69548. return false;
  69549. };
  69550. RenderTargetTexture.prototype.getRenderSize = function () {
  69551. if (this._size.width) {
  69552. return this._size.width;
  69553. }
  69554. return this._size;
  69555. };
  69556. RenderTargetTexture.prototype.getRenderWidth = function () {
  69557. if (this._size.width) {
  69558. return this._size.width;
  69559. }
  69560. return this._size;
  69561. };
  69562. RenderTargetTexture.prototype.getRenderHeight = function () {
  69563. if (this._size.width) {
  69564. return this._size.height;
  69565. }
  69566. return this._size;
  69567. };
  69568. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  69569. get: function () {
  69570. return true;
  69571. },
  69572. enumerable: true,
  69573. configurable: true
  69574. });
  69575. RenderTargetTexture.prototype.scale = function (ratio) {
  69576. var newSize = this.getRenderSize() * ratio;
  69577. this.resize(newSize);
  69578. };
  69579. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  69580. if (this.isCube) {
  69581. return this._textureMatrix;
  69582. }
  69583. return _super.prototype.getReflectionTextureMatrix.call(this);
  69584. };
  69585. RenderTargetTexture.prototype.resize = function (size) {
  69586. this.releaseInternalTexture();
  69587. var scene = this.getScene();
  69588. if (!scene) {
  69589. return;
  69590. }
  69591. this._processSizeParameter(size);
  69592. if (this.isCube) {
  69593. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  69594. }
  69595. else {
  69596. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  69597. }
  69598. };
  69599. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  69600. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  69601. if (dumpForDebug === void 0) { dumpForDebug = false; }
  69602. var scene = this.getScene();
  69603. if (!scene) {
  69604. return;
  69605. }
  69606. var engine = scene.getEngine();
  69607. if (this.useCameraPostProcesses !== undefined) {
  69608. useCameraPostProcess = this.useCameraPostProcesses;
  69609. }
  69610. if (this._waitingRenderList) {
  69611. this.renderList = [];
  69612. for (var index = 0; index < this._waitingRenderList.length; index++) {
  69613. var id = this._waitingRenderList[index];
  69614. var mesh_1 = scene.getMeshByID(id);
  69615. if (mesh_1) {
  69616. this.renderList.push(mesh_1);
  69617. }
  69618. }
  69619. delete this._waitingRenderList;
  69620. }
  69621. // Is predicate defined?
  69622. if (this.renderListPredicate) {
  69623. if (this.renderList) {
  69624. this.renderList.splice(0); // Clear previous renderList
  69625. }
  69626. else {
  69627. this.renderList = [];
  69628. }
  69629. var scene = this.getScene();
  69630. if (!scene) {
  69631. return;
  69632. }
  69633. var sceneMeshes = scene.meshes;
  69634. for (var index = 0; index < sceneMeshes.length; index++) {
  69635. var mesh = sceneMeshes[index];
  69636. if (this.renderListPredicate(mesh)) {
  69637. this.renderList.push(mesh);
  69638. }
  69639. }
  69640. }
  69641. this.onBeforeBindObservable.notifyObservers(this);
  69642. // Set custom projection.
  69643. // Needs to be before binding to prevent changing the aspect ratio.
  69644. var camera;
  69645. if (this.activeCamera) {
  69646. camera = this.activeCamera;
  69647. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69648. if (this.activeCamera !== scene.activeCamera) {
  69649. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  69650. }
  69651. }
  69652. else {
  69653. camera = scene.activeCamera;
  69654. if (camera) {
  69655. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69656. }
  69657. }
  69658. // Prepare renderingManager
  69659. this._renderingManager.reset();
  69660. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  69661. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  69662. var sceneRenderId = scene.getRenderId();
  69663. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  69664. var mesh = currentRenderList[meshIndex];
  69665. if (mesh) {
  69666. if (!mesh.isReady(this.refreshRate === 0)) {
  69667. this.resetRefreshCounter();
  69668. continue;
  69669. }
  69670. mesh._preActivateForIntermediateRendering(sceneRenderId);
  69671. var isMasked = void 0;
  69672. if (!this.renderList && camera) {
  69673. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  69674. }
  69675. else {
  69676. isMasked = false;
  69677. }
  69678. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  69679. mesh._activate(sceneRenderId);
  69680. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  69681. var subMesh = mesh.subMeshes[subIndex];
  69682. scene._activeIndices.addCount(subMesh.indexCount, false);
  69683. this._renderingManager.dispatch(subMesh, mesh);
  69684. }
  69685. }
  69686. }
  69687. }
  69688. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  69689. var particleSystem = scene.particleSystems[particleIndex];
  69690. var emitter = particleSystem.emitter;
  69691. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  69692. continue;
  69693. }
  69694. if (currentRenderList.indexOf(emitter) >= 0) {
  69695. this._renderingManager.dispatchParticles(particleSystem);
  69696. }
  69697. }
  69698. if (this.isCube) {
  69699. for (var face = 0; face < 6; face++) {
  69700. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69701. scene.incrementRenderId();
  69702. scene.resetCachedMaterial();
  69703. }
  69704. }
  69705. else {
  69706. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69707. }
  69708. this.onAfterUnbindObservable.notifyObservers(this);
  69709. if (scene.activeCamera) {
  69710. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  69711. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  69712. }
  69713. engine.setViewport(scene.activeCamera.viewport);
  69714. }
  69715. scene.resetCachedMaterial();
  69716. };
  69717. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  69718. var minimum = 128;
  69719. var x = renderDimension * scale;
  69720. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  69721. // Ensure we don't exceed the render dimension (while staying POT)
  69722. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  69723. };
  69724. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69725. var _this = this;
  69726. if (!this._texture) {
  69727. return;
  69728. }
  69729. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  69730. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69731. });
  69732. };
  69733. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  69734. var scene = this.getScene();
  69735. if (!scene) {
  69736. return;
  69737. }
  69738. var engine = scene.getEngine();
  69739. if (!this._texture) {
  69740. return;
  69741. }
  69742. // Bind
  69743. if (this._postProcessManager) {
  69744. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  69745. }
  69746. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  69747. if (this._texture) {
  69748. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  69749. }
  69750. }
  69751. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  69752. // Clear
  69753. if (this.onClearObservable.hasObservers()) {
  69754. this.onClearObservable.notifyObservers(engine);
  69755. }
  69756. else {
  69757. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  69758. }
  69759. if (!this._doNotChangeAspectRatio) {
  69760. scene.updateTransformMatrix(true);
  69761. }
  69762. // Render
  69763. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  69764. if (this._postProcessManager) {
  69765. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  69766. }
  69767. else if (useCameraPostProcess) {
  69768. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  69769. }
  69770. if (!this._doNotChangeAspectRatio) {
  69771. scene.updateTransformMatrix(true);
  69772. }
  69773. // Dump ?
  69774. if (dumpForDebug) {
  69775. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  69776. }
  69777. // Unbind
  69778. if (!this.isCube || faceIndex === 5) {
  69779. if (this.isCube) {
  69780. if (faceIndex === 5) {
  69781. engine.generateMipMapsForCubemap(this._texture);
  69782. }
  69783. }
  69784. this.unbindFrameBuffer(engine, faceIndex);
  69785. }
  69786. else {
  69787. this.onAfterRenderObservable.notifyObservers(faceIndex);
  69788. }
  69789. };
  69790. /**
  69791. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  69792. * This allowed control for front to back rendering or reversly depending of the special needs.
  69793. *
  69794. * @param renderingGroupId The rendering group id corresponding to its index
  69795. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  69796. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  69797. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  69798. */
  69799. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  69800. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  69801. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  69802. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  69803. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  69804. };
  69805. /**
  69806. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69807. *
  69808. * @param renderingGroupId The rendering group id corresponding to its index
  69809. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69810. */
  69811. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69812. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69813. this._renderingManager._useSceneAutoClearSetup = false;
  69814. };
  69815. RenderTargetTexture.prototype.clone = function () {
  69816. var textureSize = this.getSize();
  69817. 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);
  69818. // Base texture
  69819. newTexture.hasAlpha = this.hasAlpha;
  69820. newTexture.level = this.level;
  69821. // RenderTarget Texture
  69822. newTexture.coordinatesMode = this.coordinatesMode;
  69823. if (this.renderList) {
  69824. newTexture.renderList = this.renderList.slice(0);
  69825. }
  69826. return newTexture;
  69827. };
  69828. RenderTargetTexture.prototype.serialize = function () {
  69829. if (!this.name) {
  69830. return null;
  69831. }
  69832. var serializationObject = _super.prototype.serialize.call(this);
  69833. serializationObject.renderTargetSize = this.getRenderSize();
  69834. serializationObject.renderList = [];
  69835. if (this.renderList) {
  69836. for (var index = 0; index < this.renderList.length; index++) {
  69837. serializationObject.renderList.push(this.renderList[index].id);
  69838. }
  69839. }
  69840. return serializationObject;
  69841. };
  69842. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  69843. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  69844. var objBuffer = this.getInternalTexture();
  69845. var scene = this.getScene();
  69846. if (objBuffer && scene) {
  69847. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  69848. }
  69849. };
  69850. RenderTargetTexture.prototype.dispose = function () {
  69851. if (this._postProcessManager) {
  69852. this._postProcessManager.dispose();
  69853. this._postProcessManager = null;
  69854. }
  69855. this.clearPostProcesses(true);
  69856. if (this._resizeObserver) {
  69857. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  69858. this._resizeObserver = null;
  69859. }
  69860. this.renderList = null;
  69861. // Remove from custom render targets
  69862. var scene = this.getScene();
  69863. if (!scene) {
  69864. return;
  69865. }
  69866. var index = scene.customRenderTargets.indexOf(this);
  69867. if (index >= 0) {
  69868. scene.customRenderTargets.splice(index, 1);
  69869. }
  69870. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  69871. var camera = _a[_i];
  69872. index = camera.customRenderTargets.indexOf(this);
  69873. if (index >= 0) {
  69874. camera.customRenderTargets.splice(index, 1);
  69875. }
  69876. }
  69877. _super.prototype.dispose.call(this);
  69878. };
  69879. /** @hidden */
  69880. RenderTargetTexture.prototype._rebuild = function () {
  69881. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69882. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69883. }
  69884. if (this._postProcessManager) {
  69885. this._postProcessManager._rebuild();
  69886. }
  69887. };
  69888. /**
  69889. * Clear the info related to rendering groups preventing retention point in material dispose.
  69890. */
  69891. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  69892. if (this._renderingManager) {
  69893. this._renderingManager.freeRenderingGroups();
  69894. }
  69895. };
  69896. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  69897. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  69898. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  69899. return RenderTargetTexture;
  69900. }(BABYLON.Texture));
  69901. BABYLON.RenderTargetTexture = RenderTargetTexture;
  69902. })(BABYLON || (BABYLON = {}));
  69903. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  69904. var BABYLON;
  69905. (function (BABYLON) {
  69906. ;
  69907. var MultiRenderTarget = /** @class */ (function (_super) {
  69908. __extends(MultiRenderTarget, _super);
  69909. function MultiRenderTarget(name, size, count, scene, options) {
  69910. var _this = this;
  69911. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  69912. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  69913. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  69914. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  69915. _this._engine = scene.getEngine();
  69916. if (!_this.isSupported) {
  69917. _this.dispose();
  69918. return;
  69919. }
  69920. var types = [];
  69921. var samplingModes = [];
  69922. for (var i = 0; i < count; i++) {
  69923. if (options && options.types && options.types[i] !== undefined) {
  69924. types.push(options.types[i]);
  69925. }
  69926. else {
  69927. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69928. }
  69929. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  69930. samplingModes.push(options.samplingModes[i]);
  69931. }
  69932. else {
  69933. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69934. }
  69935. }
  69936. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  69937. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  69938. _this._size = size;
  69939. _this._multiRenderTargetOptions = {
  69940. samplingModes: samplingModes,
  69941. generateMipMaps: generateMipMaps,
  69942. generateDepthBuffer: generateDepthBuffer,
  69943. generateStencilBuffer: generateStencilBuffer,
  69944. generateDepthTexture: generateDepthTexture,
  69945. types: types,
  69946. textureCount: count
  69947. };
  69948. _this._createInternalTextures();
  69949. _this._createTextures();
  69950. return _this;
  69951. }
  69952. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  69953. get: function () {
  69954. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  69955. },
  69956. enumerable: true,
  69957. configurable: true
  69958. });
  69959. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  69960. get: function () {
  69961. return this._textures;
  69962. },
  69963. enumerable: true,
  69964. configurable: true
  69965. });
  69966. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  69967. get: function () {
  69968. return this._textures[this._textures.length - 1];
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  69974. set: function (wrap) {
  69975. if (this._textures) {
  69976. for (var i = 0; i < this._textures.length; i++) {
  69977. this._textures[i].wrapU = wrap;
  69978. }
  69979. }
  69980. },
  69981. enumerable: true,
  69982. configurable: true
  69983. });
  69984. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  69985. set: function (wrap) {
  69986. if (this._textures) {
  69987. for (var i = 0; i < this._textures.length; i++) {
  69988. this._textures[i].wrapV = wrap;
  69989. }
  69990. }
  69991. },
  69992. enumerable: true,
  69993. configurable: true
  69994. });
  69995. /** @hidden */
  69996. MultiRenderTarget.prototype._rebuild = function () {
  69997. this.releaseInternalTextures();
  69998. this._createInternalTextures();
  69999. for (var i = 0; i < this._internalTextures.length; i++) {
  70000. var texture = this._textures[i];
  70001. texture._texture = this._internalTextures[i];
  70002. }
  70003. // Keeps references to frame buffer and stencil/depth buffer
  70004. this._texture = this._internalTextures[0];
  70005. };
  70006. MultiRenderTarget.prototype._createInternalTextures = function () {
  70007. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70008. };
  70009. MultiRenderTarget.prototype._createTextures = function () {
  70010. this._textures = [];
  70011. for (var i = 0; i < this._internalTextures.length; i++) {
  70012. var texture = new BABYLON.Texture(null, this.getScene());
  70013. texture._texture = this._internalTextures[i];
  70014. this._textures.push(texture);
  70015. }
  70016. // Keeps references to frame buffer and stencil/depth buffer
  70017. this._texture = this._internalTextures[0];
  70018. };
  70019. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70020. get: function () {
  70021. return this._samples;
  70022. },
  70023. set: function (value) {
  70024. if (this._samples === value) {
  70025. return;
  70026. }
  70027. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70028. },
  70029. enumerable: true,
  70030. configurable: true
  70031. });
  70032. MultiRenderTarget.prototype.resize = function (size) {
  70033. this.releaseInternalTextures();
  70034. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70035. this._createInternalTextures();
  70036. };
  70037. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70038. var _this = this;
  70039. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70040. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70041. });
  70042. };
  70043. MultiRenderTarget.prototype.dispose = function () {
  70044. this.releaseInternalTextures();
  70045. _super.prototype.dispose.call(this);
  70046. };
  70047. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70048. if (!this._internalTextures) {
  70049. return;
  70050. }
  70051. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70052. if (this._internalTextures[i] !== undefined) {
  70053. this._internalTextures[i].dispose();
  70054. this._internalTextures.splice(i, 1);
  70055. }
  70056. }
  70057. };
  70058. return MultiRenderTarget;
  70059. }(BABYLON.RenderTargetTexture));
  70060. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70061. })(BABYLON || (BABYLON = {}));
  70062. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70063. var BABYLON;
  70064. (function (BABYLON) {
  70065. var MirrorTexture = /** @class */ (function (_super) {
  70066. __extends(MirrorTexture, _super);
  70067. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70068. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70070. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70071. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70072. _this.scene = scene;
  70073. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70074. _this._transformMatrix = BABYLON.Matrix.Zero();
  70075. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70076. _this._adaptiveBlurKernel = 0;
  70077. _this._blurKernelX = 0;
  70078. _this._blurKernelY = 0;
  70079. _this._blurRatio = 1.0;
  70080. _this.ignoreCameraViewport = true;
  70081. _this._updateGammaSpace();
  70082. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70083. _this._updateGammaSpace;
  70084. });
  70085. _this.onBeforeRenderObservable.add(function () {
  70086. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70087. _this._savedViewMatrix = scene.getViewMatrix();
  70088. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70089. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70090. scene.clipPlane = _this.mirrorPlane;
  70091. scene.getEngine().cullBackFaces = false;
  70092. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70093. });
  70094. _this.onAfterRenderObservable.add(function () {
  70095. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70096. scene.getEngine().cullBackFaces = true;
  70097. scene._mirroredCameraPosition = null;
  70098. delete scene.clipPlane;
  70099. });
  70100. return _this;
  70101. }
  70102. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70103. get: function () {
  70104. return this._blurRatio;
  70105. },
  70106. set: function (value) {
  70107. if (this._blurRatio === value) {
  70108. return;
  70109. }
  70110. this._blurRatio = value;
  70111. this._preparePostProcesses();
  70112. },
  70113. enumerable: true,
  70114. configurable: true
  70115. });
  70116. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70117. set: function (value) {
  70118. this._adaptiveBlurKernel = value;
  70119. this._autoComputeBlurKernel();
  70120. },
  70121. enumerable: true,
  70122. configurable: true
  70123. });
  70124. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70125. set: function (value) {
  70126. this.blurKernelX = value;
  70127. this.blurKernelY = value;
  70128. },
  70129. enumerable: true,
  70130. configurable: true
  70131. });
  70132. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70133. get: function () {
  70134. return this._blurKernelX;
  70135. },
  70136. set: function (value) {
  70137. if (this._blurKernelX === value) {
  70138. return;
  70139. }
  70140. this._blurKernelX = value;
  70141. this._preparePostProcesses();
  70142. },
  70143. enumerable: true,
  70144. configurable: true
  70145. });
  70146. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70147. get: function () {
  70148. return this._blurKernelY;
  70149. },
  70150. set: function (value) {
  70151. if (this._blurKernelY === value) {
  70152. return;
  70153. }
  70154. this._blurKernelY = value;
  70155. this._preparePostProcesses();
  70156. },
  70157. enumerable: true,
  70158. configurable: true
  70159. });
  70160. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70161. var engine = this.getScene().getEngine();
  70162. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70163. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70164. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70165. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70166. };
  70167. MirrorTexture.prototype._onRatioRescale = function () {
  70168. if (this._sizeRatio) {
  70169. this.resize(this._initialSizeParameter);
  70170. if (!this._adaptiveBlurKernel) {
  70171. this._preparePostProcesses();
  70172. }
  70173. }
  70174. if (this._adaptiveBlurKernel) {
  70175. this._autoComputeBlurKernel();
  70176. }
  70177. };
  70178. MirrorTexture.prototype._updateGammaSpace = function () {
  70179. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70180. };
  70181. MirrorTexture.prototype._preparePostProcesses = function () {
  70182. this.clearPostProcesses(true);
  70183. if (this._blurKernelX && this._blurKernelY) {
  70184. var engine = this.getScene().getEngine();
  70185. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70186. 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);
  70187. this._blurX.autoClear = false;
  70188. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70189. this._blurX.inputTexture = this._texture;
  70190. }
  70191. else {
  70192. this._blurX.alwaysForcePOT = true;
  70193. }
  70194. 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);
  70195. this._blurY.autoClear = false;
  70196. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70197. this.addPostProcess(this._blurX);
  70198. this.addPostProcess(this._blurY);
  70199. }
  70200. else {
  70201. if (this._blurY) {
  70202. this.removePostProcess(this._blurY);
  70203. this._blurY.dispose();
  70204. this._blurY = null;
  70205. }
  70206. if (this._blurX) {
  70207. this.removePostProcess(this._blurX);
  70208. this._blurX.dispose();
  70209. this._blurX = null;
  70210. }
  70211. }
  70212. };
  70213. MirrorTexture.prototype.clone = function () {
  70214. var scene = this.getScene();
  70215. if (!scene) {
  70216. return this;
  70217. }
  70218. var textureSize = this.getSize();
  70219. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70220. // Base texture
  70221. newTexture.hasAlpha = this.hasAlpha;
  70222. newTexture.level = this.level;
  70223. // Mirror Texture
  70224. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70225. if (this.renderList) {
  70226. newTexture.renderList = this.renderList.slice(0);
  70227. }
  70228. return newTexture;
  70229. };
  70230. MirrorTexture.prototype.serialize = function () {
  70231. if (!this.name) {
  70232. return null;
  70233. }
  70234. var serializationObject = _super.prototype.serialize.call(this);
  70235. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70236. return serializationObject;
  70237. };
  70238. MirrorTexture.prototype.dispose = function () {
  70239. _super.prototype.dispose.call(this);
  70240. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70241. };
  70242. return MirrorTexture;
  70243. }(BABYLON.RenderTargetTexture));
  70244. BABYLON.MirrorTexture = MirrorTexture;
  70245. })(BABYLON || (BABYLON = {}));
  70246. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70247. var BABYLON;
  70248. (function (BABYLON) {
  70249. /**
  70250. * Creates a refraction texture used by refraction channel of the standard material.
  70251. * @param name the texture name
  70252. * @param size size of the underlying texture
  70253. * @param scene root scene
  70254. */
  70255. var RefractionTexture = /** @class */ (function (_super) {
  70256. __extends(RefractionTexture, _super);
  70257. function RefractionTexture(name, size, scene, generateMipMaps) {
  70258. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70259. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70260. _this.depth = 2.0;
  70261. _this.onBeforeRenderObservable.add(function () {
  70262. scene.clipPlane = _this.refractionPlane;
  70263. });
  70264. _this.onAfterRenderObservable.add(function () {
  70265. delete scene.clipPlane;
  70266. });
  70267. return _this;
  70268. }
  70269. RefractionTexture.prototype.clone = function () {
  70270. var scene = this.getScene();
  70271. if (!scene) {
  70272. return this;
  70273. }
  70274. var textureSize = this.getSize();
  70275. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70276. // Base texture
  70277. newTexture.hasAlpha = this.hasAlpha;
  70278. newTexture.level = this.level;
  70279. // Refraction Texture
  70280. newTexture.refractionPlane = this.refractionPlane.clone();
  70281. if (this.renderList) {
  70282. newTexture.renderList = this.renderList.slice(0);
  70283. }
  70284. newTexture.depth = this.depth;
  70285. return newTexture;
  70286. };
  70287. RefractionTexture.prototype.serialize = function () {
  70288. if (!this.name) {
  70289. return null;
  70290. }
  70291. var serializationObject = _super.prototype.serialize.call(this);
  70292. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70293. serializationObject.depth = this.depth;
  70294. return serializationObject;
  70295. };
  70296. return RefractionTexture;
  70297. }(BABYLON.RenderTargetTexture));
  70298. BABYLON.RefractionTexture = RefractionTexture;
  70299. })(BABYLON || (BABYLON = {}));
  70300. //# sourceMappingURL=babylon.refractionTexture.js.map
  70301. var BABYLON;
  70302. (function (BABYLON) {
  70303. /**
  70304. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70305. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70306. */
  70307. var DynamicTexture = /** @class */ (function (_super) {
  70308. __extends(DynamicTexture, _super);
  70309. /**
  70310. * Creates a {BABYLON.DynamicTexture}
  70311. * @param name defines the name of the texture
  70312. * @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
  70313. * @param scene defines the scene where you want the texture
  70314. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70315. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70316. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70317. */
  70318. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70319. if (scene === void 0) { scene = null; }
  70320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70321. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70322. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70323. _this.name = name;
  70324. _this._engine = _this.getScene().getEngine();
  70325. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70326. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70327. _this._generateMipMaps = generateMipMaps;
  70328. if (options.getContext) {
  70329. _this._canvas = options;
  70330. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70331. }
  70332. else {
  70333. _this._canvas = document.createElement("canvas");
  70334. if (options.width || options.width === 0) {
  70335. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70336. }
  70337. else {
  70338. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70339. }
  70340. }
  70341. var textureSize = _this.getSize();
  70342. _this._canvas.width = textureSize.width;
  70343. _this._canvas.height = textureSize.height;
  70344. _this._context = _this._canvas.getContext("2d");
  70345. return _this;
  70346. }
  70347. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70348. /**
  70349. * Gets the current state of canRescale
  70350. */
  70351. get: function () {
  70352. return true;
  70353. },
  70354. enumerable: true,
  70355. configurable: true
  70356. });
  70357. DynamicTexture.prototype._recreate = function (textureSize) {
  70358. this._canvas.width = textureSize.width;
  70359. this._canvas.height = textureSize.height;
  70360. this.releaseInternalTexture();
  70361. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70362. };
  70363. /**
  70364. * Scales the texture
  70365. * @param ratio the scale factor to apply to both width and height
  70366. */
  70367. DynamicTexture.prototype.scale = function (ratio) {
  70368. var textureSize = this.getSize();
  70369. textureSize.width *= ratio;
  70370. textureSize.height *= ratio;
  70371. this._recreate(textureSize);
  70372. };
  70373. /**
  70374. * Resizes the texture
  70375. * @param width the new width
  70376. * @param height the new height
  70377. */
  70378. DynamicTexture.prototype.scaleTo = function (width, height) {
  70379. var textureSize = this.getSize();
  70380. textureSize.width = width;
  70381. textureSize.height = height;
  70382. this._recreate(textureSize);
  70383. };
  70384. /**
  70385. * Gets the context of the canvas used by the texture
  70386. * @returns the canvas context of the dynamic texture
  70387. */
  70388. DynamicTexture.prototype.getContext = function () {
  70389. return this._context;
  70390. };
  70391. /**
  70392. * Clears the texture
  70393. */
  70394. DynamicTexture.prototype.clear = function () {
  70395. var size = this.getSize();
  70396. this._context.fillRect(0, 0, size.width, size.height);
  70397. };
  70398. /**
  70399. * Updates the texture
  70400. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70401. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70402. */
  70403. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70404. if (premulAlpha === void 0) { premulAlpha = false; }
  70405. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70406. };
  70407. /**
  70408. * Draws text onto the texture
  70409. * @param text defines the text to be drawn
  70410. * @param x defines the placement of the text from the left
  70411. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70412. * @param font defines the font to be used with font-style, font-size, font-name
  70413. * @param color defines the color used for the text
  70414. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70415. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70416. * @param update defines whether texture is immediately update (default is true)
  70417. */
  70418. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70419. if (update === void 0) { update = true; }
  70420. var size = this.getSize();
  70421. if (clearColor) {
  70422. this._context.fillStyle = clearColor;
  70423. this._context.fillRect(0, 0, size.width, size.height);
  70424. }
  70425. this._context.font = font;
  70426. if (x === null || x === undefined) {
  70427. var textSize = this._context.measureText(text);
  70428. x = (size.width - textSize.width) / 2;
  70429. }
  70430. if (y === null || y === undefined) {
  70431. var fontSize = parseInt((font.replace(/\D/g, '')));
  70432. y = (size.height / 2) + (fontSize / 3.65);
  70433. }
  70434. this._context.fillStyle = color;
  70435. this._context.fillText(text, x, y);
  70436. if (update) {
  70437. this.update(invertY);
  70438. }
  70439. };
  70440. /**
  70441. * Clones the texture
  70442. * @returns the clone of the texture.
  70443. */
  70444. DynamicTexture.prototype.clone = function () {
  70445. var scene = this.getScene();
  70446. if (!scene) {
  70447. return this;
  70448. }
  70449. var textureSize = this.getSize();
  70450. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70451. // Base texture
  70452. newTexture.hasAlpha = this.hasAlpha;
  70453. newTexture.level = this.level;
  70454. // Dynamic Texture
  70455. newTexture.wrapU = this.wrapU;
  70456. newTexture.wrapV = this.wrapV;
  70457. return newTexture;
  70458. };
  70459. /**
  70460. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70461. * @returns a serialized dynamic texture object
  70462. */
  70463. DynamicTexture.prototype.serialize = function () {
  70464. var scene = this.getScene();
  70465. if (scene && !scene.isReady()) {
  70466. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70467. }
  70468. var serializationObject = _super.prototype.serialize.call(this);
  70469. serializationObject.base64String = this._canvas.toDataURL();
  70470. serializationObject.invertY = this._invertY;
  70471. serializationObject.samplingMode = this.samplingMode;
  70472. return serializationObject;
  70473. };
  70474. /** @hidden */
  70475. DynamicTexture.prototype._rebuild = function () {
  70476. this.update();
  70477. };
  70478. return DynamicTexture;
  70479. }(BABYLON.Texture));
  70480. BABYLON.DynamicTexture = DynamicTexture;
  70481. })(BABYLON || (BABYLON = {}));
  70482. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70483. var BABYLON;
  70484. (function (BABYLON) {
  70485. var VideoTexture = /** @class */ (function (_super) {
  70486. __extends(VideoTexture, _super);
  70487. /**
  70488. * Creates a video texture.
  70489. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70490. * @param {string | null} name optional name, will detect from video source, if not defined
  70491. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70492. * @param {BABYLON.Scene} scene is obviously the current scene.
  70493. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70494. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70495. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70496. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70497. */
  70498. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70499. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70500. if (invertY === void 0) { invertY = false; }
  70501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70502. if (settings === void 0) { settings = {
  70503. autoPlay: true,
  70504. loop: true,
  70505. autoUpdateTexture: true,
  70506. }; }
  70507. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70508. _this._onUserActionRequestedObservable = null;
  70509. _this._stillImageCaptured = false;
  70510. _this._poster = false;
  70511. _this._createInternalTexture = function () {
  70512. if (_this._texture != null) {
  70513. if (_this._poster) {
  70514. _this._texture.dispose();
  70515. _this._poster = false;
  70516. }
  70517. else {
  70518. return;
  70519. }
  70520. }
  70521. if (!_this._engine.needPOTTextures ||
  70522. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  70523. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70524. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70525. }
  70526. else {
  70527. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70528. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70529. _this._generateMipMaps = false;
  70530. }
  70531. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  70532. if (!_this.video.autoplay) {
  70533. var oldHandler_1 = _this.video.onplaying;
  70534. var error_1 = false;
  70535. _this.video.onplaying = function () {
  70536. _this.video.onplaying = oldHandler_1;
  70537. _this._texture.isReady = true;
  70538. _this._updateInternalTexture();
  70539. if (!error_1) {
  70540. _this.video.pause();
  70541. }
  70542. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70543. _this.onLoadObservable.notifyObservers(_this);
  70544. }
  70545. };
  70546. var playing = _this.video.play();
  70547. if (playing) {
  70548. playing.then(function () {
  70549. // Everything is good.
  70550. })
  70551. .catch(function () {
  70552. error_1 = true;
  70553. // On Chrome for instance, new policies might prevent playing without user interaction.
  70554. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  70555. _this._onUserActionRequestedObservable.notifyObservers(_this);
  70556. }
  70557. });
  70558. }
  70559. else {
  70560. _this.video.onplaying = oldHandler_1;
  70561. _this._texture.isReady = true;
  70562. _this._updateInternalTexture();
  70563. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70564. _this.onLoadObservable.notifyObservers(_this);
  70565. }
  70566. }
  70567. }
  70568. else {
  70569. _this._texture.isReady = true;
  70570. _this._updateInternalTexture();
  70571. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70572. _this.onLoadObservable.notifyObservers(_this);
  70573. }
  70574. }
  70575. };
  70576. _this.reset = function () {
  70577. if (_this._texture == null) {
  70578. return;
  70579. }
  70580. if (!_this._poster) {
  70581. _this._texture.dispose();
  70582. _this._texture = null;
  70583. }
  70584. };
  70585. _this._updateInternalTexture = function (e) {
  70586. if (_this._texture == null || !_this._texture.isReady) {
  70587. return;
  70588. }
  70589. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  70590. return;
  70591. }
  70592. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  70593. };
  70594. _this._engine = _this.getScene().getEngine();
  70595. _this._generateMipMaps = generateMipMaps;
  70596. _this._samplingMode = samplingMode;
  70597. _this.autoUpdateTexture = settings.autoUpdateTexture;
  70598. _this.name = name || _this._getName(src);
  70599. _this.video = _this._getVideo(src);
  70600. if (settings.poster) {
  70601. _this.video.poster = settings.poster;
  70602. }
  70603. if (settings.autoPlay !== undefined) {
  70604. _this.video.autoplay = settings.autoPlay;
  70605. }
  70606. if (settings.loop !== undefined) {
  70607. _this.video.loop = settings.loop;
  70608. }
  70609. _this.video.setAttribute("playsinline", "");
  70610. _this.video.addEventListener("canplay", _this._createInternalTexture);
  70611. _this.video.addEventListener("paused", _this._updateInternalTexture);
  70612. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  70613. _this.video.addEventListener("emptied", _this.reset);
  70614. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  70615. _this._createInternalTexture();
  70616. }
  70617. if (settings.poster) {
  70618. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  70619. _this._poster = true;
  70620. }
  70621. return _this;
  70622. }
  70623. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  70624. get: function () {
  70625. if (!this._onUserActionRequestedObservable) {
  70626. this._onUserActionRequestedObservable = new BABYLON.Observable();
  70627. }
  70628. return this._onUserActionRequestedObservable;
  70629. },
  70630. enumerable: true,
  70631. configurable: true
  70632. });
  70633. VideoTexture.prototype._getName = function (src) {
  70634. if (src instanceof HTMLVideoElement) {
  70635. return src.currentSrc;
  70636. }
  70637. if (typeof src === "object") {
  70638. return src.toString();
  70639. }
  70640. return src;
  70641. };
  70642. ;
  70643. VideoTexture.prototype._getVideo = function (src) {
  70644. if (src instanceof HTMLVideoElement) {
  70645. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  70646. return src;
  70647. }
  70648. var video = document.createElement("video");
  70649. if (typeof src === "string") {
  70650. BABYLON.Tools.SetCorsBehavior(src, video);
  70651. video.src = src;
  70652. }
  70653. else {
  70654. BABYLON.Tools.SetCorsBehavior(src[0], video);
  70655. src.forEach(function (url) {
  70656. var source = document.createElement("source");
  70657. source.src = url;
  70658. video.appendChild(source);
  70659. });
  70660. }
  70661. return video;
  70662. };
  70663. ;
  70664. /**
  70665. * @hidden Internal method to initiate `update`.
  70666. */
  70667. VideoTexture.prototype._rebuild = function () {
  70668. this.update();
  70669. };
  70670. /**
  70671. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  70672. */
  70673. VideoTexture.prototype.update = function () {
  70674. if (!this.autoUpdateTexture) {
  70675. // Expecting user to call `updateTexture` manually
  70676. return;
  70677. }
  70678. this.updateTexture(true);
  70679. };
  70680. /**
  70681. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  70682. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  70683. */
  70684. VideoTexture.prototype.updateTexture = function (isVisible) {
  70685. if (!isVisible) {
  70686. return;
  70687. }
  70688. if (this.video.paused && this._stillImageCaptured) {
  70689. return;
  70690. }
  70691. this._stillImageCaptured = true;
  70692. this._updateInternalTexture();
  70693. };
  70694. /**
  70695. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  70696. * @param url New url.
  70697. */
  70698. VideoTexture.prototype.updateURL = function (url) {
  70699. this.video.src = url;
  70700. };
  70701. VideoTexture.prototype.dispose = function () {
  70702. _super.prototype.dispose.call(this);
  70703. if (this._onUserActionRequestedObservable) {
  70704. this._onUserActionRequestedObservable.clear();
  70705. this._onUserActionRequestedObservable = null;
  70706. }
  70707. this.video.removeEventListener("canplay", this._createInternalTexture);
  70708. this.video.removeEventListener("paused", this._updateInternalTexture);
  70709. this.video.removeEventListener("seeked", this._updateInternalTexture);
  70710. this.video.removeEventListener("emptied", this.reset);
  70711. this.video.pause();
  70712. };
  70713. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  70714. var video = document.createElement("video");
  70715. video.setAttribute('autoplay', '');
  70716. video.setAttribute('muted', '');
  70717. video.setAttribute('playsinline', '');
  70718. var constraintsDeviceId;
  70719. if (constraints && constraints.deviceId) {
  70720. constraintsDeviceId = {
  70721. exact: constraints.deviceId,
  70722. };
  70723. }
  70724. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  70725. if (navigator.mediaDevices) {
  70726. navigator.mediaDevices.getUserMedia({ video: constraints })
  70727. .then(function (stream) {
  70728. if (video.mozSrcObject !== undefined) {
  70729. // hack for Firefox < 19
  70730. video.mozSrcObject = stream;
  70731. }
  70732. else {
  70733. video.srcObject = stream;
  70734. }
  70735. var onPlaying = function () {
  70736. if (onReady) {
  70737. onReady(new VideoTexture("video", video, scene, true, true));
  70738. }
  70739. video.removeEventListener("playing", onPlaying);
  70740. };
  70741. video.addEventListener("playing", onPlaying);
  70742. video.play();
  70743. })
  70744. .catch(function (err) {
  70745. BABYLON.Tools.Error(err.name);
  70746. });
  70747. }
  70748. else {
  70749. navigator.getUserMedia =
  70750. navigator.getUserMedia ||
  70751. navigator.webkitGetUserMedia ||
  70752. navigator.mozGetUserMedia ||
  70753. navigator.msGetUserMedia;
  70754. if (navigator.getUserMedia) {
  70755. navigator.getUserMedia({
  70756. video: {
  70757. deviceId: constraintsDeviceId,
  70758. width: {
  70759. min: (constraints && constraints.minWidth) || 256,
  70760. max: (constraints && constraints.maxWidth) || 640,
  70761. },
  70762. height: {
  70763. min: (constraints && constraints.minHeight) || 256,
  70764. max: (constraints && constraints.maxHeight) || 480,
  70765. },
  70766. },
  70767. }, function (stream) {
  70768. if (video.mozSrcObject !== undefined) {
  70769. // hack for Firefox < 19
  70770. video.mozSrcObject = stream;
  70771. }
  70772. else {
  70773. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  70774. }
  70775. video.play();
  70776. if (onReady) {
  70777. onReady(new VideoTexture("video", video, scene, true, true));
  70778. }
  70779. }, function (e) {
  70780. BABYLON.Tools.Error(e.name);
  70781. });
  70782. }
  70783. }
  70784. };
  70785. return VideoTexture;
  70786. }(BABYLON.Texture));
  70787. BABYLON.VideoTexture = VideoTexture;
  70788. })(BABYLON || (BABYLON = {}));
  70789. //# sourceMappingURL=babylon.videoTexture.js.map
  70790. var BABYLON;
  70791. (function (BABYLON) {
  70792. var RawTexture = /** @class */ (function (_super) {
  70793. __extends(RawTexture, _super);
  70794. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  70795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70796. if (invertY === void 0) { invertY = false; }
  70797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70798. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70799. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70800. _this.format = format;
  70801. _this._engine = scene.getEngine();
  70802. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  70803. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70804. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70805. return _this;
  70806. }
  70807. RawTexture.prototype.update = function (data) {
  70808. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70809. };
  70810. // Statics
  70811. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70812. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70813. if (invertY === void 0) { invertY = false; }
  70814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70815. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  70816. };
  70817. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70818. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70819. if (invertY === void 0) { invertY = false; }
  70820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70821. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70822. };
  70823. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70824. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70825. if (invertY === void 0) { invertY = false; }
  70826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70827. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70828. };
  70829. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70830. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70831. if (invertY === void 0) { invertY = false; }
  70832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70833. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70834. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  70835. };
  70836. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70837. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70838. if (invertY === void 0) { invertY = false; }
  70839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70840. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70841. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  70842. };
  70843. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70844. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70845. if (invertY === void 0) { invertY = false; }
  70846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70847. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70848. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  70849. };
  70850. return RawTexture;
  70851. }(BABYLON.Texture));
  70852. BABYLON.RawTexture = RawTexture;
  70853. })(BABYLON || (BABYLON = {}));
  70854. //# sourceMappingURL=babylon.rawTexture.js.map
  70855. var BABYLON;
  70856. (function (BABYLON) {
  70857. /**
  70858. * Class used to store 3D textures containing user data
  70859. */
  70860. var RawTexture3D = /** @class */ (function (_super) {
  70861. __extends(RawTexture3D, _super);
  70862. /**
  70863. * Create a new RawTexture3D
  70864. * @param data defines the data of the texture
  70865. * @param width defines the width of the texture
  70866. * @param height defines the height of the texture
  70867. * @param depth defines the depth of the texture
  70868. * @param format defines the texture format to use
  70869. * @param scene defines the hosting scene
  70870. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  70871. * @param invertY defines if texture must be stored with Y axis inverted
  70872. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  70873. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  70874. */
  70875. function RawTexture3D(data, width, height, depth,
  70876. /** Gets or sets the texture format to use */
  70877. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  70878. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70879. if (invertY === void 0) { invertY = false; }
  70880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70882. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70883. _this.format = format;
  70884. _this._engine = scene.getEngine();
  70885. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  70886. _this.is3D = true;
  70887. return _this;
  70888. }
  70889. /**
  70890. * Update the texture with new data
  70891. * @param data defines the data to store in the texture
  70892. */
  70893. RawTexture3D.prototype.update = function (data) {
  70894. if (!this._texture) {
  70895. return;
  70896. }
  70897. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70898. };
  70899. return RawTexture3D;
  70900. }(BABYLON.Texture));
  70901. BABYLON.RawTexture3D = RawTexture3D;
  70902. })(BABYLON || (BABYLON = {}));
  70903. //# sourceMappingURL=babylon.rawTexture3D.js.map
  70904. var BABYLON;
  70905. (function (BABYLON) {
  70906. /**
  70907. * PostProcessManager is used to manage one or more post processes or post process pipelines
  70908. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  70909. */
  70910. var PostProcessManager = /** @class */ (function () {
  70911. /**
  70912. * Creates a new instance PostProcess
  70913. * @param scene The scene that the post process is associated with.
  70914. */
  70915. function PostProcessManager(scene) {
  70916. this._vertexBuffers = {};
  70917. this._scene = scene;
  70918. }
  70919. PostProcessManager.prototype._prepareBuffers = function () {
  70920. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  70921. return;
  70922. }
  70923. // VBO
  70924. var vertices = [];
  70925. vertices.push(1, 1);
  70926. vertices.push(-1, 1);
  70927. vertices.push(-1, -1);
  70928. vertices.push(1, -1);
  70929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70930. this._buildIndexBuffer();
  70931. };
  70932. PostProcessManager.prototype._buildIndexBuffer = function () {
  70933. // Indices
  70934. var indices = [];
  70935. indices.push(0);
  70936. indices.push(1);
  70937. indices.push(2);
  70938. indices.push(0);
  70939. indices.push(2);
  70940. indices.push(3);
  70941. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  70942. };
  70943. /**
  70944. * Rebuilds the vertex buffers of the manager.
  70945. * @hidden
  70946. */
  70947. PostProcessManager.prototype._rebuild = function () {
  70948. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70949. if (!vb) {
  70950. return;
  70951. }
  70952. vb._rebuild();
  70953. this._buildIndexBuffer();
  70954. };
  70955. // Methods
  70956. /**
  70957. * Prepares a frame to be run through a post process.
  70958. * @param sourceTexture The input texture to the post procesess. (default: null)
  70959. * @param postProcesses An array of post processes to be run. (default: null)
  70960. * @returns True if the post processes were able to be run.
  70961. * @hidden
  70962. */
  70963. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  70964. if (sourceTexture === void 0) { sourceTexture = null; }
  70965. if (postProcesses === void 0) { postProcesses = null; }
  70966. var camera = this._scene.activeCamera;
  70967. if (!camera) {
  70968. return false;
  70969. }
  70970. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  70971. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  70972. return false;
  70973. }
  70974. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  70975. return true;
  70976. };
  70977. /**
  70978. * Manually render a set of post processes to a texture.
  70979. * @param postProcesses An array of post processes to be run.
  70980. * @param targetTexture The target texture to render to.
  70981. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  70982. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  70983. * @param lodLevel defines which lod of the texture to render to
  70984. */
  70985. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  70986. if (targetTexture === void 0) { targetTexture = null; }
  70987. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  70988. if (faceIndex === void 0) { faceIndex = 0; }
  70989. if (lodLevel === void 0) { lodLevel = 0; }
  70990. var engine = this._scene.getEngine();
  70991. for (var index = 0; index < postProcesses.length; index++) {
  70992. if (index < postProcesses.length - 1) {
  70993. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  70994. }
  70995. else {
  70996. if (targetTexture) {
  70997. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  70998. }
  70999. else {
  71000. engine.restoreDefaultFramebuffer();
  71001. }
  71002. }
  71003. var pp = postProcesses[index];
  71004. var effect = pp.apply();
  71005. if (effect) {
  71006. pp.onBeforeRenderObservable.notifyObservers(effect);
  71007. // VBOs
  71008. this._prepareBuffers();
  71009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71010. // Draw order
  71011. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71012. pp.onAfterRenderObservable.notifyObservers(effect);
  71013. }
  71014. }
  71015. // Restore depth buffer
  71016. engine.setDepthBuffer(true);
  71017. engine.setDepthWrite(true);
  71018. };
  71019. /**
  71020. * Finalize the result of the output of the postprocesses.
  71021. * @param doNotPresent If true the result will not be displayed to the screen.
  71022. * @param targetTexture The target texture to render to.
  71023. * @param faceIndex The index of the face to bind the target texture to.
  71024. * @param postProcesses The array of post processes to render.
  71025. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71026. * @hidden
  71027. */
  71028. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71029. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71030. var camera = this._scene.activeCamera;
  71031. if (!camera) {
  71032. return;
  71033. }
  71034. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71035. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71036. return;
  71037. }
  71038. var engine = this._scene.getEngine();
  71039. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71040. var pp = postProcesses[index];
  71041. if (index < len - 1) {
  71042. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71043. }
  71044. else {
  71045. if (targetTexture) {
  71046. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71047. pp._outputTexture = targetTexture;
  71048. }
  71049. else {
  71050. engine.restoreDefaultFramebuffer();
  71051. pp._outputTexture = null;
  71052. }
  71053. }
  71054. if (doNotPresent) {
  71055. break;
  71056. }
  71057. var effect = pp.apply();
  71058. if (effect) {
  71059. pp.onBeforeRenderObservable.notifyObservers(effect);
  71060. // VBOs
  71061. this._prepareBuffers();
  71062. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71063. // Draw order
  71064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71065. pp.onAfterRenderObservable.notifyObservers(effect);
  71066. }
  71067. }
  71068. // Restore states
  71069. engine.setDepthBuffer(true);
  71070. engine.setDepthWrite(true);
  71071. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71072. };
  71073. /**
  71074. * Disposes of the post process manager.
  71075. */
  71076. PostProcessManager.prototype.dispose = function () {
  71077. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71078. if (buffer) {
  71079. buffer.dispose();
  71080. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71081. }
  71082. if (this._indexBuffer) {
  71083. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71084. this._indexBuffer = null;
  71085. }
  71086. };
  71087. return PostProcessManager;
  71088. }());
  71089. BABYLON.PostProcessManager = PostProcessManager;
  71090. })(BABYLON || (BABYLON = {}));
  71091. //# sourceMappingURL=babylon.postProcessManager.js.map
  71092. var BABYLON;
  71093. (function (BABYLON) {
  71094. /**
  71095. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71096. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71097. */
  71098. var PostProcess = /** @class */ (function () {
  71099. /**
  71100. * Creates a new instance PostProcess
  71101. * @param name The name of the PostProcess.
  71102. * @param fragmentUrl The url of the fragment shader to be used.
  71103. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71104. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71105. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71106. * @param camera The camera to apply the render pass to.
  71107. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71108. * @param engine The engine which the post process will be applied. (default: current engine)
  71109. * @param reusable If the post process can be reused on the same frame. (default: false)
  71110. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71111. * @param textureType Type of textures used when performing the post process. (default: 0)
  71112. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71113. * @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
  71114. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71115. */
  71116. function PostProcess(
  71117. /** Name of the PostProcess. */
  71118. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71120. if (defines === void 0) { defines = null; }
  71121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71122. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71123. if (blockCompilation === void 0) { blockCompilation = false; }
  71124. this.name = name;
  71125. /**
  71126. * Width of the texture to apply the post process on
  71127. */
  71128. this.width = -1;
  71129. /**
  71130. * Height of the texture to apply the post process on
  71131. */
  71132. this.height = -1;
  71133. /**
  71134. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71135. * @hidden
  71136. */
  71137. this._outputTexture = null;
  71138. /**
  71139. * If the buffer needs to be cleared before applying the post process. (default: true)
  71140. * Should be set to false if shader will overwrite all previous pixels.
  71141. */
  71142. this.autoClear = true;
  71143. /**
  71144. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71145. */
  71146. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71147. /**
  71148. * Animations to be used for the post processing
  71149. */
  71150. this.animations = new Array();
  71151. /**
  71152. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71153. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71154. */
  71155. this.enablePixelPerfectMode = false;
  71156. /**
  71157. * Force the postprocess to be applied without taking in account viewport
  71158. */
  71159. this.forceFullscreenViewport = true;
  71160. /**
  71161. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71162. *
  71163. * | Value | Type | Description |
  71164. * | ----- | ----------------------------------- | ----------- |
  71165. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71166. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71167. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71168. *
  71169. */
  71170. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71171. /**
  71172. * Force textures to be a power of two (default: false)
  71173. */
  71174. this.alwaysForcePOT = false;
  71175. this._samples = 1;
  71176. /**
  71177. * Modify the scale of the post process to be the same as the viewport (default: false)
  71178. */
  71179. this.adaptScaleToCurrentViewport = false;
  71180. this._reusable = false;
  71181. /**
  71182. * Smart array of input and output textures for the post process.
  71183. * @hidden
  71184. */
  71185. this._textures = new BABYLON.SmartArray(2);
  71186. /**
  71187. * The index in _textures that corresponds to the output texture.
  71188. * @hidden
  71189. */
  71190. this._currentRenderTextureInd = 0;
  71191. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71192. this._texelSize = BABYLON.Vector2.Zero();
  71193. // Events
  71194. /**
  71195. * An event triggered when the postprocess is activated.
  71196. */
  71197. this.onActivateObservable = new BABYLON.Observable();
  71198. /**
  71199. * An event triggered when the postprocess changes its size.
  71200. */
  71201. this.onSizeChangedObservable = new BABYLON.Observable();
  71202. /**
  71203. * An event triggered when the postprocess applies its effect.
  71204. */
  71205. this.onApplyObservable = new BABYLON.Observable();
  71206. /**
  71207. * An event triggered before rendering the postprocess
  71208. */
  71209. this.onBeforeRenderObservable = new BABYLON.Observable();
  71210. /**
  71211. * An event triggered after rendering the postprocess
  71212. */
  71213. this.onAfterRenderObservable = new BABYLON.Observable();
  71214. if (camera != null) {
  71215. this._camera = camera;
  71216. this._scene = camera.getScene();
  71217. camera.attachPostProcess(this);
  71218. this._engine = this._scene.getEngine();
  71219. this._scene.postProcesses.push(this);
  71220. }
  71221. else if (engine) {
  71222. this._engine = engine;
  71223. this._engine.postProcesses.push(this);
  71224. }
  71225. this._options = options;
  71226. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71227. this._reusable = reusable || false;
  71228. this._textureType = textureType;
  71229. this._samplers = samplers || [];
  71230. this._samplers.push("textureSampler");
  71231. this._fragmentUrl = fragmentUrl;
  71232. this._vertexUrl = vertexUrl;
  71233. this._parameters = parameters || [];
  71234. this._parameters.push("scale");
  71235. this._indexParameters = indexParameters;
  71236. if (!blockCompilation) {
  71237. this.updateEffect(defines);
  71238. }
  71239. }
  71240. Object.defineProperty(PostProcess.prototype, "samples", {
  71241. /**
  71242. * Number of sample textures (default: 1)
  71243. */
  71244. get: function () {
  71245. return this._samples;
  71246. },
  71247. set: function (n) {
  71248. var _this = this;
  71249. this._samples = n;
  71250. this._textures.forEach(function (texture) {
  71251. if (texture.samples !== _this._samples) {
  71252. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71253. }
  71254. });
  71255. },
  71256. enumerable: true,
  71257. configurable: true
  71258. });
  71259. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71260. /**
  71261. * A function that is added to the onActivateObservable
  71262. */
  71263. set: function (callback) {
  71264. if (this._onActivateObserver) {
  71265. this.onActivateObservable.remove(this._onActivateObserver);
  71266. }
  71267. if (callback) {
  71268. this._onActivateObserver = this.onActivateObservable.add(callback);
  71269. }
  71270. },
  71271. enumerable: true,
  71272. configurable: true
  71273. });
  71274. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71275. /**
  71276. * A function that is added to the onSizeChangedObservable
  71277. */
  71278. set: function (callback) {
  71279. if (this._onSizeChangedObserver) {
  71280. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71281. }
  71282. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71283. },
  71284. enumerable: true,
  71285. configurable: true
  71286. });
  71287. Object.defineProperty(PostProcess.prototype, "onApply", {
  71288. /**
  71289. * A function that is added to the onApplyObservable
  71290. */
  71291. set: function (callback) {
  71292. if (this._onApplyObserver) {
  71293. this.onApplyObservable.remove(this._onApplyObserver);
  71294. }
  71295. this._onApplyObserver = this.onApplyObservable.add(callback);
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71301. /**
  71302. * A function that is added to the onBeforeRenderObservable
  71303. */
  71304. set: function (callback) {
  71305. if (this._onBeforeRenderObserver) {
  71306. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71307. }
  71308. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71309. },
  71310. enumerable: true,
  71311. configurable: true
  71312. });
  71313. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71314. /**
  71315. * A function that is added to the onAfterRenderObservable
  71316. */
  71317. set: function (callback) {
  71318. if (this._onAfterRenderObserver) {
  71319. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71320. }
  71321. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71322. },
  71323. enumerable: true,
  71324. configurable: true
  71325. });
  71326. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71327. /**
  71328. * 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
  71329. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71330. */
  71331. get: function () {
  71332. return this._textures.data[this._currentRenderTextureInd];
  71333. },
  71334. set: function (value) {
  71335. this._forcedOutputTexture = value;
  71336. },
  71337. enumerable: true,
  71338. configurable: true
  71339. });
  71340. /**
  71341. * Gets the camera which post process is applied to.
  71342. * @returns The camera the post process is applied to.
  71343. */
  71344. PostProcess.prototype.getCamera = function () {
  71345. return this._camera;
  71346. };
  71347. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71348. /**
  71349. * Gets the texel size of the postprocess.
  71350. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71351. */
  71352. get: function () {
  71353. if (this._shareOutputWithPostProcess) {
  71354. return this._shareOutputWithPostProcess.texelSize;
  71355. }
  71356. if (this._forcedOutputTexture) {
  71357. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71358. }
  71359. return this._texelSize;
  71360. },
  71361. enumerable: true,
  71362. configurable: true
  71363. });
  71364. /**
  71365. * Gets the engine which this post process belongs to.
  71366. * @returns The engine the post process was enabled with.
  71367. */
  71368. PostProcess.prototype.getEngine = function () {
  71369. return this._engine;
  71370. };
  71371. /**
  71372. * The effect that is created when initializing the post process.
  71373. * @returns The created effect corrisponding the the postprocess.
  71374. */
  71375. PostProcess.prototype.getEffect = function () {
  71376. return this._effect;
  71377. };
  71378. /**
  71379. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71380. * @param postProcess The post process to share the output with.
  71381. * @returns This post process.
  71382. */
  71383. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71384. this._disposeTextures();
  71385. this._shareOutputWithPostProcess = postProcess;
  71386. return this;
  71387. };
  71388. /**
  71389. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71390. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71391. */
  71392. PostProcess.prototype.useOwnOutput = function () {
  71393. if (this._textures.length == 0) {
  71394. this._textures = new BABYLON.SmartArray(2);
  71395. }
  71396. this._shareOutputWithPostProcess = null;
  71397. };
  71398. /**
  71399. * Updates the effect with the current post process compile time values and recompiles the shader.
  71400. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71401. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71402. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71403. * @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
  71404. * @param onCompiled Called when the shader has been compiled.
  71405. * @param onError Called if there is an error when compiling a shader.
  71406. */
  71407. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71408. if (defines === void 0) { defines = null; }
  71409. if (uniforms === void 0) { uniforms = null; }
  71410. if (samplers === void 0) { samplers = null; }
  71411. 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);
  71412. };
  71413. /**
  71414. * The post process is reusable if it can be used multiple times within one frame.
  71415. * @returns If the post process is reusable
  71416. */
  71417. PostProcess.prototype.isReusable = function () {
  71418. return this._reusable;
  71419. };
  71420. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71421. PostProcess.prototype.markTextureDirty = function () {
  71422. this.width = -1;
  71423. };
  71424. /**
  71425. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71426. * 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.
  71427. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71428. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71429. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71430. * @returns The target texture that was bound to be written to.
  71431. */
  71432. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71433. var _this = this;
  71434. if (sourceTexture === void 0) { sourceTexture = null; }
  71435. camera = camera || this._camera;
  71436. var scene = camera.getScene();
  71437. var engine = scene.getEngine();
  71438. var maxSize = engine.getCaps().maxTextureSize;
  71439. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71440. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71441. // 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
  71442. var webVRCamera = camera.parent;
  71443. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71444. requiredWidth /= 2;
  71445. }
  71446. var desiredWidth = (this._options.width || requiredWidth);
  71447. var desiredHeight = this._options.height || requiredHeight;
  71448. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71449. if (this.adaptScaleToCurrentViewport) {
  71450. var currentViewport = engine.currentViewport;
  71451. if (currentViewport) {
  71452. desiredWidth *= currentViewport.width;
  71453. desiredHeight *= currentViewport.height;
  71454. }
  71455. }
  71456. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71457. if (!this._options.width) {
  71458. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71459. }
  71460. if (!this._options.height) {
  71461. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71462. }
  71463. }
  71464. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71465. if (this._textures.length > 0) {
  71466. for (var i = 0; i < this._textures.length; i++) {
  71467. this._engine._releaseTexture(this._textures.data[i]);
  71468. }
  71469. this._textures.reset();
  71470. }
  71471. this.width = desiredWidth;
  71472. this.height = desiredHeight;
  71473. var textureSize = { width: this.width, height: this.height };
  71474. var textureOptions = {
  71475. generateMipMaps: false,
  71476. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71477. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71478. samplingMode: this.renderTargetSamplingMode,
  71479. type: this._textureType
  71480. };
  71481. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71482. if (this._reusable) {
  71483. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71484. }
  71485. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71486. this.onSizeChangedObservable.notifyObservers(this);
  71487. }
  71488. this._textures.forEach(function (texture) {
  71489. if (texture.samples !== _this.samples) {
  71490. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71491. }
  71492. });
  71493. }
  71494. var target;
  71495. if (this._shareOutputWithPostProcess) {
  71496. target = this._shareOutputWithPostProcess.inputTexture;
  71497. }
  71498. else if (this._forcedOutputTexture) {
  71499. target = this._forcedOutputTexture;
  71500. this.width = this._forcedOutputTexture.width;
  71501. this.height = this._forcedOutputTexture.height;
  71502. }
  71503. else {
  71504. target = this.inputTexture;
  71505. }
  71506. // Bind the input of this post process to be used as the output of the previous post process.
  71507. if (this.enablePixelPerfectMode) {
  71508. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  71509. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  71510. }
  71511. else {
  71512. this._scaleRatio.copyFromFloats(1, 1);
  71513. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  71514. }
  71515. this.onActivateObservable.notifyObservers(camera);
  71516. // Clear
  71517. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  71518. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  71519. }
  71520. if (this._reusable) {
  71521. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  71522. }
  71523. return target;
  71524. };
  71525. Object.defineProperty(PostProcess.prototype, "isSupported", {
  71526. /**
  71527. * If the post process is supported.
  71528. */
  71529. get: function () {
  71530. return this._effect.isSupported;
  71531. },
  71532. enumerable: true,
  71533. configurable: true
  71534. });
  71535. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  71536. /**
  71537. * The aspect ratio of the output texture.
  71538. */
  71539. get: function () {
  71540. if (this._shareOutputWithPostProcess) {
  71541. return this._shareOutputWithPostProcess.aspectRatio;
  71542. }
  71543. if (this._forcedOutputTexture) {
  71544. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  71545. }
  71546. return this.width / this.height;
  71547. },
  71548. enumerable: true,
  71549. configurable: true
  71550. });
  71551. /**
  71552. * Get a value indicating if the post-process is ready to be used
  71553. * @returns true if the post-process is ready (shader is compiled)
  71554. */
  71555. PostProcess.prototype.isReady = function () {
  71556. return this._effect && this._effect.isReady();
  71557. };
  71558. /**
  71559. * Binds all textures and uniforms to the shader, this will be run on every pass.
  71560. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  71561. */
  71562. PostProcess.prototype.apply = function () {
  71563. // Check
  71564. if (!this._effect || !this._effect.isReady())
  71565. return null;
  71566. // States
  71567. this._engine.enableEffect(this._effect);
  71568. this._engine.setState(false);
  71569. this._engine.setDepthBuffer(false);
  71570. this._engine.setDepthWrite(false);
  71571. // Alpha
  71572. this._engine.setAlphaMode(this.alphaMode);
  71573. if (this.alphaConstants) {
  71574. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  71575. }
  71576. // Bind the output texture of the preivous post process as the input to this post process.
  71577. var source;
  71578. if (this._shareOutputWithPostProcess) {
  71579. source = this._shareOutputWithPostProcess.inputTexture;
  71580. }
  71581. else if (this._forcedOutputTexture) {
  71582. source = this._forcedOutputTexture;
  71583. }
  71584. else {
  71585. source = this.inputTexture;
  71586. }
  71587. this._effect._bindTexture("textureSampler", source);
  71588. // Parameters
  71589. this._effect.setVector2("scale", this._scaleRatio);
  71590. this.onApplyObservable.notifyObservers(this._effect);
  71591. return this._effect;
  71592. };
  71593. PostProcess.prototype._disposeTextures = function () {
  71594. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  71595. return;
  71596. }
  71597. if (this._textures.length > 0) {
  71598. for (var i = 0; i < this._textures.length; i++) {
  71599. this._engine._releaseTexture(this._textures.data[i]);
  71600. }
  71601. }
  71602. this._textures.dispose();
  71603. };
  71604. /**
  71605. * Disposes the post process.
  71606. * @param camera The camera to dispose the post process on.
  71607. */
  71608. PostProcess.prototype.dispose = function (camera) {
  71609. camera = camera || this._camera;
  71610. this._disposeTextures();
  71611. if (this._scene) {
  71612. var index_1 = this._scene.postProcesses.indexOf(this);
  71613. if (index_1 !== -1) {
  71614. this._scene.postProcesses.splice(index_1, 1);
  71615. }
  71616. }
  71617. else {
  71618. var index_2 = this._engine.postProcesses.indexOf(this);
  71619. if (index_2 !== -1) {
  71620. this._engine.postProcesses.splice(index_2, 1);
  71621. }
  71622. }
  71623. if (!camera) {
  71624. return;
  71625. }
  71626. camera.detachPostProcess(this);
  71627. var index = camera._postProcesses.indexOf(this);
  71628. if (index === 0 && camera._postProcesses.length > 0) {
  71629. var firstPostProcess = this._camera._getFirstPostProcess();
  71630. if (firstPostProcess) {
  71631. firstPostProcess.markTextureDirty();
  71632. }
  71633. }
  71634. this.onActivateObservable.clear();
  71635. this.onAfterRenderObservable.clear();
  71636. this.onApplyObservable.clear();
  71637. this.onBeforeRenderObservable.clear();
  71638. this.onSizeChangedObservable.clear();
  71639. };
  71640. return PostProcess;
  71641. }());
  71642. BABYLON.PostProcess = PostProcess;
  71643. })(BABYLON || (BABYLON = {}));
  71644. //# sourceMappingURL=babylon.postProcess.js.map
  71645. var BABYLON;
  71646. (function (BABYLON) {
  71647. var PassPostProcess = /** @class */ (function (_super) {
  71648. __extends(PassPostProcess, _super);
  71649. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71650. if (camera === void 0) { camera = null; }
  71651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71652. if (blockCompilation === void 0) { blockCompilation = false; }
  71653. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  71654. }
  71655. return PassPostProcess;
  71656. }(BABYLON.PostProcess));
  71657. BABYLON.PassPostProcess = PassPostProcess;
  71658. })(BABYLON || (BABYLON = {}));
  71659. //# sourceMappingURL=babylon.passPostProcess.js.map
  71660. var __assign = (this && this.__assign) || function () {
  71661. __assign = Object.assign || function(t) {
  71662. for (var s, i = 1, n = arguments.length; i < n; i++) {
  71663. s = arguments[i];
  71664. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  71665. t[p] = s[p];
  71666. }
  71667. return t;
  71668. };
  71669. return __assign.apply(this, arguments);
  71670. };
  71671. var BABYLON;
  71672. (function (BABYLON) {
  71673. /**
  71674. * Default implementation IShadowGenerator.
  71675. * This is the main object responsible of generating shadows in the framework.
  71676. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  71677. */
  71678. var ShadowGenerator = /** @class */ (function () {
  71679. /**
  71680. * Creates a ShadowGenerator object.
  71681. * A ShadowGenerator is the required tool to use the shadows.
  71682. * Each light casting shadows needs to use its own ShadowGenerator.
  71683. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  71684. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  71685. * @param light The light object generating the shadows.
  71686. * @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.
  71687. */
  71688. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  71689. this._bias = 0.00005;
  71690. this._normalBias = 0;
  71691. this._blurBoxOffset = 1;
  71692. this._blurScale = 2;
  71693. this._blurKernel = 1;
  71694. this._useKernelBlur = false;
  71695. this._filter = ShadowGenerator.FILTER_NONE;
  71696. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  71697. this._contactHardeningLightSizeUVRatio = 0.1;
  71698. this._darkness = 0;
  71699. this._transparencyShadow = false;
  71700. /**
  71701. * Controls the extent to which the shadows fade out at the edge of the frustum
  71702. * Used only by directionals and spots
  71703. */
  71704. this.frustumEdgeFalloff = 0;
  71705. /**
  71706. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  71707. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  71708. * It might on the other hand introduce peter panning.
  71709. */
  71710. this.forceBackFacesOnly = false;
  71711. this._lightDirection = BABYLON.Vector3.Zero();
  71712. this._viewMatrix = BABYLON.Matrix.Zero();
  71713. this._projectionMatrix = BABYLON.Matrix.Zero();
  71714. this._transformMatrix = BABYLON.Matrix.Zero();
  71715. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71716. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71717. this._currentFaceIndex = 0;
  71718. this._currentFaceIndexCache = 0;
  71719. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  71720. this._mapSize = mapSize;
  71721. this._light = light;
  71722. this._scene = light.getScene();
  71723. light._shadowGenerator = this;
  71724. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  71725. if (!component) {
  71726. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  71727. this._scene._addComponent(component);
  71728. }
  71729. // Texture type fallback from float to int if not supported.
  71730. var caps = this._scene.getEngine().getCaps();
  71731. if (!useFullFloatFirst) {
  71732. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71733. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71734. }
  71735. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71736. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71737. }
  71738. else {
  71739. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71740. }
  71741. }
  71742. else {
  71743. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71744. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71745. }
  71746. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71747. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71748. }
  71749. else {
  71750. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71751. }
  71752. }
  71753. this._initializeGenerator();
  71754. this._applyFilterValues();
  71755. }
  71756. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  71757. /**
  71758. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  71759. */
  71760. get: function () {
  71761. return this._bias;
  71762. },
  71763. /**
  71764. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  71765. */
  71766. set: function (bias) {
  71767. this._bias = bias;
  71768. },
  71769. enumerable: true,
  71770. configurable: true
  71771. });
  71772. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  71773. /**
  71774. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71775. */
  71776. get: function () {
  71777. return this._normalBias;
  71778. },
  71779. /**
  71780. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71781. */
  71782. set: function (normalBias) {
  71783. this._normalBias = normalBias;
  71784. },
  71785. enumerable: true,
  71786. configurable: true
  71787. });
  71788. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  71789. /**
  71790. * Gets the blur box offset: offset applied during the blur pass.
  71791. * Only usefull if useKernelBlur = false
  71792. */
  71793. get: function () {
  71794. return this._blurBoxOffset;
  71795. },
  71796. /**
  71797. * Sets the blur box offset: offset applied during the blur pass.
  71798. * Only usefull if useKernelBlur = false
  71799. */
  71800. set: function (value) {
  71801. if (this._blurBoxOffset === value) {
  71802. return;
  71803. }
  71804. this._blurBoxOffset = value;
  71805. this._disposeBlurPostProcesses();
  71806. },
  71807. enumerable: true,
  71808. configurable: true
  71809. });
  71810. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  71811. /**
  71812. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  71813. * 2 means half of the size.
  71814. */
  71815. get: function () {
  71816. return this._blurScale;
  71817. },
  71818. /**
  71819. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  71820. * 2 means half of the size.
  71821. */
  71822. set: function (value) {
  71823. if (this._blurScale === value) {
  71824. return;
  71825. }
  71826. this._blurScale = value;
  71827. this._disposeBlurPostProcesses();
  71828. },
  71829. enumerable: true,
  71830. configurable: true
  71831. });
  71832. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  71833. /**
  71834. * Gets the blur kernel: kernel size of the blur pass.
  71835. * Only usefull if useKernelBlur = true
  71836. */
  71837. get: function () {
  71838. return this._blurKernel;
  71839. },
  71840. /**
  71841. * Sets the blur kernel: kernel size of the blur pass.
  71842. * Only usefull if useKernelBlur = true
  71843. */
  71844. set: function (value) {
  71845. if (this._blurKernel === value) {
  71846. return;
  71847. }
  71848. this._blurKernel = value;
  71849. this._disposeBlurPostProcesses();
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  71855. /**
  71856. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  71857. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71858. */
  71859. get: function () {
  71860. return this._useKernelBlur;
  71861. },
  71862. /**
  71863. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  71864. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71865. */
  71866. set: function (value) {
  71867. if (this._useKernelBlur === value) {
  71868. return;
  71869. }
  71870. this._useKernelBlur = value;
  71871. this._disposeBlurPostProcesses();
  71872. },
  71873. enumerable: true,
  71874. configurable: true
  71875. });
  71876. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  71877. /**
  71878. * Gets the depth scale used in ESM mode.
  71879. */
  71880. get: function () {
  71881. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  71882. },
  71883. /**
  71884. * Sets the depth scale used in ESM mode.
  71885. * This can override the scale stored on the light.
  71886. */
  71887. set: function (value) {
  71888. this._depthScale = value;
  71889. },
  71890. enumerable: true,
  71891. configurable: true
  71892. });
  71893. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  71894. /**
  71895. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  71896. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71897. */
  71898. get: function () {
  71899. return this._filter;
  71900. },
  71901. /**
  71902. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  71903. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71904. */
  71905. set: function (value) {
  71906. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  71907. if (this._light.needCube()) {
  71908. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  71909. this.useExponentialShadowMap = true;
  71910. return;
  71911. }
  71912. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  71913. this.useCloseExponentialShadowMap = true;
  71914. return;
  71915. }
  71916. // PCF on cubemap would also be expensive
  71917. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71918. this.usePoissonSampling = true;
  71919. return;
  71920. }
  71921. }
  71922. // Weblg1 fallback for PCF.
  71923. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71924. if (this._scene.getEngine().webGLVersion === 1) {
  71925. this.usePoissonSampling = true;
  71926. return;
  71927. }
  71928. }
  71929. if (this._filter === value) {
  71930. return;
  71931. }
  71932. this._filter = value;
  71933. this._disposeBlurPostProcesses();
  71934. this._applyFilterValues();
  71935. this._light._markMeshesAsLightDirty();
  71936. },
  71937. enumerable: true,
  71938. configurable: true
  71939. });
  71940. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  71941. /**
  71942. * Gets if the current filter is set to Poisson Sampling.
  71943. */
  71944. get: function () {
  71945. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  71946. },
  71947. /**
  71948. * Sets the current filter to Poisson Sampling.
  71949. */
  71950. set: function (value) {
  71951. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  71952. return;
  71953. }
  71954. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  71955. },
  71956. enumerable: true,
  71957. configurable: true
  71958. });
  71959. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  71960. /**
  71961. * Gets if the current filter is set to VSM.
  71962. * DEPRECATED. Should use useExponentialShadowMap instead.
  71963. */
  71964. get: function () {
  71965. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71966. return this.useExponentialShadowMap;
  71967. },
  71968. /**
  71969. * Sets the current filter is to VSM.
  71970. * DEPRECATED. Should use useExponentialShadowMap instead.
  71971. */
  71972. set: function (value) {
  71973. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71974. this.useExponentialShadowMap = value;
  71975. },
  71976. enumerable: true,
  71977. configurable: true
  71978. });
  71979. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  71980. /**
  71981. * Gets if the current filter is set to blurred VSM.
  71982. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71983. */
  71984. get: function () {
  71985. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71986. return this.useBlurExponentialShadowMap;
  71987. },
  71988. /**
  71989. * Sets the current filter is to blurred VSM.
  71990. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71991. */
  71992. set: function (value) {
  71993. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71994. this.useBlurExponentialShadowMap = value;
  71995. },
  71996. enumerable: true,
  71997. configurable: true
  71998. });
  71999. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72000. /**
  72001. * Gets if the current filter is set to ESM.
  72002. */
  72003. get: function () {
  72004. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72005. },
  72006. /**
  72007. * Sets the current filter is to ESM.
  72008. */
  72009. set: function (value) {
  72010. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72011. return;
  72012. }
  72013. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72014. },
  72015. enumerable: true,
  72016. configurable: true
  72017. });
  72018. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72019. /**
  72020. * Gets if the current filter is set to filtered ESM.
  72021. */
  72022. get: function () {
  72023. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72024. },
  72025. /**
  72026. * Gets if the current filter is set to filtered ESM.
  72027. */
  72028. set: function (value) {
  72029. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72030. return;
  72031. }
  72032. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72033. },
  72034. enumerable: true,
  72035. configurable: true
  72036. });
  72037. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72038. /**
  72039. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72040. * exponential to prevent steep falloff artifacts).
  72041. */
  72042. get: function () {
  72043. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72044. },
  72045. /**
  72046. * Sets the current filter to "close ESM" (using the inverse of the
  72047. * exponential to prevent steep falloff artifacts).
  72048. */
  72049. set: function (value) {
  72050. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72051. return;
  72052. }
  72053. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72054. },
  72055. enumerable: true,
  72056. configurable: true
  72057. });
  72058. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72059. /**
  72060. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72061. * exponential to prevent steep falloff artifacts).
  72062. */
  72063. get: function () {
  72064. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72065. },
  72066. /**
  72067. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72068. * exponential to prevent steep falloff artifacts).
  72069. */
  72070. set: function (value) {
  72071. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72072. return;
  72073. }
  72074. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72075. },
  72076. enumerable: true,
  72077. configurable: true
  72078. });
  72079. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72080. /**
  72081. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72082. */
  72083. get: function () {
  72084. return this.filter === ShadowGenerator.FILTER_PCF;
  72085. },
  72086. /**
  72087. * Sets the current filter to "PCF" (percentage closer filtering).
  72088. */
  72089. set: function (value) {
  72090. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72091. return;
  72092. }
  72093. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72099. /**
  72100. * Gets the PCF or PCSS Quality.
  72101. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72102. */
  72103. get: function () {
  72104. return this._filteringQuality;
  72105. },
  72106. /**
  72107. * Sets the PCF or PCSS Quality.
  72108. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72109. */
  72110. set: function (filteringQuality) {
  72111. this._filteringQuality = filteringQuality;
  72112. },
  72113. enumerable: true,
  72114. configurable: true
  72115. });
  72116. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72117. /**
  72118. * Gets if the current filter is set to "PCSS" (contact hardening).
  72119. */
  72120. get: function () {
  72121. return this.filter === ShadowGenerator.FILTER_PCSS;
  72122. },
  72123. /**
  72124. * Sets the current filter to "PCSS" (contact hardening).
  72125. */
  72126. set: function (value) {
  72127. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72128. return;
  72129. }
  72130. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72131. },
  72132. enumerable: true,
  72133. configurable: true
  72134. });
  72135. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72136. /**
  72137. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72138. * Using a ratio helps keeping shape stability independently of the map size.
  72139. *
  72140. * It does not account for the light projection as it was having too much
  72141. * instability during the light setup or during light position changes.
  72142. *
  72143. * Only valid if useContactHardeningShadow is true.
  72144. */
  72145. get: function () {
  72146. return this._contactHardeningLightSizeUVRatio;
  72147. },
  72148. /**
  72149. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72150. * Using a ratio helps keeping shape stability independently of the map size.
  72151. *
  72152. * It does not account for the light projection as it was having too much
  72153. * instability during the light setup or during light position changes.
  72154. *
  72155. * Only valid if useContactHardeningShadow is true.
  72156. */
  72157. set: function (contactHardeningLightSizeUVRatio) {
  72158. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72159. },
  72160. enumerable: true,
  72161. configurable: true
  72162. });
  72163. /**
  72164. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72165. * 0 means strongest and 1 would means no shadow.
  72166. * @returns the darkness.
  72167. */
  72168. ShadowGenerator.prototype.getDarkness = function () {
  72169. return this._darkness;
  72170. };
  72171. /**
  72172. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72173. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72174. * @returns the shadow generator allowing fluent coding.
  72175. */
  72176. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72177. if (darkness >= 1.0)
  72178. this._darkness = 1.0;
  72179. else if (darkness <= 0.0)
  72180. this._darkness = 0.0;
  72181. else
  72182. this._darkness = darkness;
  72183. return this;
  72184. };
  72185. /**
  72186. * Sets the ability to have transparent shadow (boolean).
  72187. * @param transparent True if transparent else False
  72188. * @returns the shadow generator allowing fluent coding
  72189. */
  72190. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72191. this._transparencyShadow = transparent;
  72192. return this;
  72193. };
  72194. /**
  72195. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72196. * @returns The render target texture if present otherwise, null
  72197. */
  72198. ShadowGenerator.prototype.getShadowMap = function () {
  72199. return this._shadowMap;
  72200. };
  72201. /**
  72202. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72203. * @returns The render target texture if the shadow map is present otherwise, null
  72204. */
  72205. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72206. if (this._shadowMap2) {
  72207. return this._shadowMap2;
  72208. }
  72209. return this._shadowMap;
  72210. };
  72211. /**
  72212. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72213. * @param mesh Mesh to add
  72214. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72215. * @returns the Shadow Generator itself
  72216. */
  72217. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72218. if (includeDescendants === void 0) { includeDescendants = true; }
  72219. var _a;
  72220. if (!this._shadowMap) {
  72221. return this;
  72222. }
  72223. if (!this._shadowMap.renderList) {
  72224. this._shadowMap.renderList = [];
  72225. }
  72226. this._shadowMap.renderList.push(mesh);
  72227. if (includeDescendants) {
  72228. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72229. }
  72230. return this;
  72231. };
  72232. /**
  72233. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72234. * @param mesh Mesh to remove
  72235. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72236. * @returns the Shadow Generator itself
  72237. */
  72238. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72239. if (includeDescendants === void 0) { includeDescendants = true; }
  72240. if (!this._shadowMap || !this._shadowMap.renderList) {
  72241. return this;
  72242. }
  72243. var index = this._shadowMap.renderList.indexOf(mesh);
  72244. if (index !== -1) {
  72245. this._shadowMap.renderList.splice(index, 1);
  72246. }
  72247. if (includeDescendants) {
  72248. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72249. var child = _a[_i];
  72250. this.removeShadowCaster(child);
  72251. }
  72252. }
  72253. return this;
  72254. };
  72255. /**
  72256. * Returns the associated light object.
  72257. * @returns the light generating the shadow
  72258. */
  72259. ShadowGenerator.prototype.getLight = function () {
  72260. return this._light;
  72261. };
  72262. ShadowGenerator.prototype._initializeGenerator = function () {
  72263. this._light._markMeshesAsLightDirty();
  72264. this._initializeShadowMap();
  72265. };
  72266. ShadowGenerator.prototype._initializeShadowMap = function () {
  72267. var _this = this;
  72268. // Render target
  72269. var engine = this._scene.getEngine();
  72270. if (engine.webGLVersion > 1) {
  72271. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72272. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72273. }
  72274. else {
  72275. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72276. }
  72277. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72278. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72279. this._shadowMap.anisotropicFilteringLevel = 1;
  72280. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72281. this._shadowMap.renderParticles = false;
  72282. this._shadowMap.ignoreCameraViewport = true;
  72283. // Record Face Index before render.
  72284. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72285. _this._currentFaceIndex = faceIndex;
  72286. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72287. engine.setColorWrite(false);
  72288. }
  72289. });
  72290. // Custom render function.
  72291. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72292. // Blur if required afer render.
  72293. this._shadowMap.onAfterUnbindObservable.add(function () {
  72294. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72295. engine.setColorWrite(true);
  72296. }
  72297. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72298. return;
  72299. }
  72300. var shadowMap = _this.getShadowMapForRendering();
  72301. if (shadowMap) {
  72302. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72303. }
  72304. });
  72305. // Clear according to the chosen filter.
  72306. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72307. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72308. this._shadowMap.onClearObservable.add(function (engine) {
  72309. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72310. engine.clear(clearOne, false, true, false);
  72311. }
  72312. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72313. engine.clear(clearZero, true, true, false);
  72314. }
  72315. else {
  72316. engine.clear(clearOne, true, true, false);
  72317. }
  72318. });
  72319. };
  72320. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72321. var _this = this;
  72322. var engine = this._scene.getEngine();
  72323. var targetSize = this._mapSize / this.blurScale;
  72324. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72325. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72326. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72327. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72328. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72329. }
  72330. if (this.useKernelBlur) {
  72331. 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);
  72332. this._kernelBlurXPostprocess.width = targetSize;
  72333. this._kernelBlurXPostprocess.height = targetSize;
  72334. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72335. effect.setTexture("textureSampler", _this._shadowMap);
  72336. });
  72337. 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);
  72338. this._kernelBlurXPostprocess.autoClear = false;
  72339. this._kernelBlurYPostprocess.autoClear = false;
  72340. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72341. this._kernelBlurXPostprocess.packedFloat = true;
  72342. this._kernelBlurYPostprocess.packedFloat = true;
  72343. }
  72344. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72345. }
  72346. else {
  72347. 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);
  72348. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72349. effect.setFloat2("screenSize", targetSize, targetSize);
  72350. effect.setTexture("textureSampler", _this._shadowMap);
  72351. });
  72352. this._boxBlurPostprocess.autoClear = false;
  72353. this._blurPostProcesses = [this._boxBlurPostprocess];
  72354. }
  72355. };
  72356. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72357. var index;
  72358. var engine = this._scene.getEngine();
  72359. if (depthOnlySubMeshes.length) {
  72360. engine.setColorWrite(false);
  72361. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72362. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72363. }
  72364. engine.setColorWrite(true);
  72365. }
  72366. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72367. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72368. }
  72369. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72370. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72371. }
  72372. if (this._transparencyShadow) {
  72373. for (index = 0; index < transparentSubMeshes.length; index++) {
  72374. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72375. }
  72376. }
  72377. };
  72378. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72379. var _this = this;
  72380. var mesh = subMesh.getRenderingMesh();
  72381. var scene = this._scene;
  72382. var engine = scene.getEngine();
  72383. var material = subMesh.getMaterial();
  72384. if (!material) {
  72385. return;
  72386. }
  72387. // Culling
  72388. engine.setState(material.backFaceCulling);
  72389. // Managing instances
  72390. var batch = mesh._getInstancesRenderList(subMesh._id);
  72391. if (batch.mustReturn) {
  72392. return;
  72393. }
  72394. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72395. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72396. engine.enableEffect(this._effect);
  72397. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72398. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72399. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72400. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72401. this._effect.setVector3("lightData", this._cachedDirection);
  72402. }
  72403. else {
  72404. this._effect.setVector3("lightData", this._cachedPosition);
  72405. }
  72406. if (scene.activeCamera) {
  72407. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72408. }
  72409. // Alpha test
  72410. if (material && material.needAlphaTesting()) {
  72411. var alphaTexture = material.getAlphaTestTexture();
  72412. if (alphaTexture) {
  72413. this._effect.setTexture("diffuseSampler", alphaTexture);
  72414. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72415. }
  72416. }
  72417. // Bones
  72418. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72419. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72420. }
  72421. // Morph targets
  72422. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72423. if (this.forceBackFacesOnly) {
  72424. engine.setState(true, 0, false, true);
  72425. }
  72426. // Draw
  72427. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72428. if (this.forceBackFacesOnly) {
  72429. engine.setState(true, 0, false, false);
  72430. }
  72431. }
  72432. else {
  72433. // Need to reset refresh rate of the shadowMap
  72434. if (this._shadowMap) {
  72435. this._shadowMap.resetRefreshCounter();
  72436. }
  72437. }
  72438. };
  72439. ShadowGenerator.prototype._applyFilterValues = function () {
  72440. if (!this._shadowMap) {
  72441. return;
  72442. }
  72443. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72444. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72445. }
  72446. else {
  72447. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72448. }
  72449. };
  72450. /**
  72451. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72452. * @param onCompiled Callback triggered at the and of the effects compilation
  72453. * @param options Sets of optional options forcing the compilation with different modes
  72454. */
  72455. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72456. var _this = this;
  72457. var localOptions = __assign({ useInstances: false }, options);
  72458. var shadowMap = this.getShadowMap();
  72459. if (!shadowMap) {
  72460. if (onCompiled) {
  72461. onCompiled(this);
  72462. }
  72463. return;
  72464. }
  72465. var renderList = shadowMap.renderList;
  72466. if (!renderList) {
  72467. if (onCompiled) {
  72468. onCompiled(this);
  72469. }
  72470. return;
  72471. }
  72472. var subMeshes = new Array();
  72473. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72474. var mesh = renderList_1[_i];
  72475. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72476. }
  72477. if (subMeshes.length === 0) {
  72478. if (onCompiled) {
  72479. onCompiled(this);
  72480. }
  72481. return;
  72482. }
  72483. var currentIndex = 0;
  72484. var checkReady = function () {
  72485. if (!_this._scene || !_this._scene.getEngine()) {
  72486. return;
  72487. }
  72488. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72489. currentIndex++;
  72490. if (currentIndex >= subMeshes.length) {
  72491. if (onCompiled) {
  72492. onCompiled(_this);
  72493. }
  72494. return;
  72495. }
  72496. }
  72497. setTimeout(checkReady, 16);
  72498. };
  72499. checkReady();
  72500. };
  72501. /**
  72502. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72503. * @param options Sets of optional options forcing the compilation with different modes
  72504. * @returns A promise that resolves when the compilation completes
  72505. */
  72506. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72507. var _this = this;
  72508. return new Promise(function (resolve) {
  72509. _this.forceCompilation(function () {
  72510. resolve();
  72511. }, options);
  72512. });
  72513. };
  72514. /**
  72515. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  72516. * @param subMesh The submesh we want to render in the shadow map
  72517. * @param useInstances Defines wether will draw in the map using instances
  72518. * @returns true if ready otherwise, false
  72519. */
  72520. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  72521. var defines = [];
  72522. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72523. defines.push("#define FLOAT");
  72524. }
  72525. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72526. defines.push("#define ESM");
  72527. }
  72528. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  72529. defines.push("#define DEPTHTEXTURE");
  72530. }
  72531. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72532. var mesh = subMesh.getMesh();
  72533. var material = subMesh.getMaterial();
  72534. // Normal bias.
  72535. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  72536. attribs.push(BABYLON.VertexBuffer.NormalKind);
  72537. defines.push("#define NORMAL");
  72538. if (mesh.nonUniformScaling) {
  72539. defines.push("#define NONUNIFORMSCALING");
  72540. }
  72541. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72542. defines.push("#define DIRECTIONINLIGHTDATA");
  72543. }
  72544. }
  72545. // Alpha test
  72546. if (material && material.needAlphaTesting()) {
  72547. var alphaTexture = material.getAlphaTestTexture();
  72548. if (alphaTexture) {
  72549. defines.push("#define ALPHATEST");
  72550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72551. attribs.push(BABYLON.VertexBuffer.UVKind);
  72552. defines.push("#define UV1");
  72553. }
  72554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72555. if (alphaTexture.coordinatesIndex === 1) {
  72556. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72557. defines.push("#define UV2");
  72558. }
  72559. }
  72560. }
  72561. }
  72562. // Bones
  72563. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72566. if (mesh.numBoneInfluencers > 4) {
  72567. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72568. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72569. }
  72570. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72571. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  72572. }
  72573. else {
  72574. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72575. }
  72576. // Morph targets
  72577. var manager = mesh.morphTargetManager;
  72578. var morphInfluencers = 0;
  72579. if (manager) {
  72580. if (manager.numInfluencers > 0) {
  72581. defines.push("#define MORPHTARGETS");
  72582. morphInfluencers = manager.numInfluencers;
  72583. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  72584. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  72585. }
  72586. }
  72587. // Instances
  72588. if (useInstances) {
  72589. defines.push("#define INSTANCES");
  72590. attribs.push("world0");
  72591. attribs.push("world1");
  72592. attribs.push("world2");
  72593. attribs.push("world3");
  72594. }
  72595. // Get correct effect
  72596. var join = defines.join("\n");
  72597. if (this._cachedDefines !== join) {
  72598. this._cachedDefines = join;
  72599. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  72600. }
  72601. if (!this._effect.isReady()) {
  72602. return false;
  72603. }
  72604. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72605. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  72606. this._initializeBlurRTTAndPostProcesses();
  72607. }
  72608. }
  72609. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  72610. return false;
  72611. }
  72612. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  72613. return false;
  72614. }
  72615. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  72616. return false;
  72617. }
  72618. return true;
  72619. };
  72620. /**
  72621. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  72622. * @param defines Defines of the material we want to update
  72623. * @param lightIndex Index of the light in the enabled light list of the material
  72624. */
  72625. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  72626. var scene = this._scene;
  72627. var light = this._light;
  72628. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72629. return;
  72630. }
  72631. defines["SHADOW" + lightIndex] = true;
  72632. if (this.useContactHardeningShadow) {
  72633. defines["SHADOWPCSS" + lightIndex] = true;
  72634. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72635. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72636. }
  72637. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72638. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72639. }
  72640. // else default to high.
  72641. }
  72642. if (this.usePercentageCloserFiltering) {
  72643. defines["SHADOWPCF" + lightIndex] = true;
  72644. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72645. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72646. }
  72647. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72648. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72649. }
  72650. // else default to high.
  72651. }
  72652. else if (this.usePoissonSampling) {
  72653. defines["SHADOWPOISSON" + lightIndex] = true;
  72654. }
  72655. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72656. defines["SHADOWESM" + lightIndex] = true;
  72657. }
  72658. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72659. defines["SHADOWCLOSEESM" + lightIndex] = true;
  72660. }
  72661. if (light.needCube()) {
  72662. defines["SHADOWCUBE" + lightIndex] = true;
  72663. }
  72664. };
  72665. /**
  72666. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  72667. * defined in the generator but impacting the effect).
  72668. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  72669. * @param effect The effect we are binfing the information for
  72670. */
  72671. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  72672. var light = this._light;
  72673. var scene = this._scene;
  72674. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72675. return;
  72676. }
  72677. var camera = scene.activeCamera;
  72678. if (!camera) {
  72679. return;
  72680. }
  72681. var shadowMap = this.getShadowMap();
  72682. if (!shadowMap) {
  72683. return;
  72684. }
  72685. if (!light.needCube()) {
  72686. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  72687. }
  72688. // Only PCF uses depth stencil texture.
  72689. if (this._filter === ShadowGenerator.FILTER_PCF) {
  72690. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72691. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72692. }
  72693. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  72694. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72695. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  72696. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72697. }
  72698. else {
  72699. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72700. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  72701. }
  72702. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  72703. };
  72704. /**
  72705. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  72706. * (eq to shadow prjection matrix * light transform matrix)
  72707. * @returns The transform matrix used to create the shadow map
  72708. */
  72709. ShadowGenerator.prototype.getTransformMatrix = function () {
  72710. var scene = this._scene;
  72711. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  72712. return this._transformMatrix;
  72713. }
  72714. this._currentRenderID = scene.getRenderId();
  72715. this._currentFaceIndexCache = this._currentFaceIndex;
  72716. var lightPosition = this._light.position;
  72717. if (this._light.computeTransformedInformation()) {
  72718. lightPosition = this._light.transformedPosition;
  72719. }
  72720. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  72721. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  72722. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  72723. }
  72724. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  72725. this._cachedPosition.copyFrom(lightPosition);
  72726. this._cachedDirection.copyFrom(this._lightDirection);
  72727. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  72728. var shadowMap = this.getShadowMap();
  72729. if (shadowMap) {
  72730. var renderList = shadowMap.renderList;
  72731. if (renderList) {
  72732. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  72733. }
  72734. }
  72735. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  72736. }
  72737. return this._transformMatrix;
  72738. };
  72739. /**
  72740. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  72741. * Cube and 2D textures for instance.
  72742. */
  72743. ShadowGenerator.prototype.recreateShadowMap = function () {
  72744. var shadowMap = this._shadowMap;
  72745. if (!shadowMap) {
  72746. return;
  72747. }
  72748. // Track render list.
  72749. var renderList = shadowMap.renderList;
  72750. // Clean up existing data.
  72751. this._disposeRTTandPostProcesses();
  72752. // Reinitializes.
  72753. this._initializeGenerator();
  72754. // Reaffect the filter to ensure a correct fallback if necessary.
  72755. this.filter = this.filter;
  72756. // Reaffect the filter.
  72757. this._applyFilterValues();
  72758. // Reaffect Render List.
  72759. this._shadowMap.renderList = renderList;
  72760. };
  72761. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  72762. if (this._shadowMap2) {
  72763. this._shadowMap2.dispose();
  72764. this._shadowMap2 = null;
  72765. }
  72766. if (this._boxBlurPostprocess) {
  72767. this._boxBlurPostprocess.dispose();
  72768. this._boxBlurPostprocess = null;
  72769. }
  72770. if (this._kernelBlurXPostprocess) {
  72771. this._kernelBlurXPostprocess.dispose();
  72772. this._kernelBlurXPostprocess = null;
  72773. }
  72774. if (this._kernelBlurYPostprocess) {
  72775. this._kernelBlurYPostprocess.dispose();
  72776. this._kernelBlurYPostprocess = null;
  72777. }
  72778. this._blurPostProcesses = [];
  72779. };
  72780. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  72781. if (this._shadowMap) {
  72782. this._shadowMap.dispose();
  72783. this._shadowMap = null;
  72784. }
  72785. this._disposeBlurPostProcesses();
  72786. };
  72787. /**
  72788. * Disposes the ShadowGenerator.
  72789. * Returns nothing.
  72790. */
  72791. ShadowGenerator.prototype.dispose = function () {
  72792. this._disposeRTTandPostProcesses();
  72793. if (this._light) {
  72794. this._light._shadowGenerator = null;
  72795. this._light._markMeshesAsLightDirty();
  72796. }
  72797. };
  72798. /**
  72799. * Serializes the shadow generator setup to a json object.
  72800. * @returns The serialized JSON object
  72801. */
  72802. ShadowGenerator.prototype.serialize = function () {
  72803. var serializationObject = {};
  72804. var shadowMap = this.getShadowMap();
  72805. if (!shadowMap) {
  72806. return serializationObject;
  72807. }
  72808. serializationObject.lightId = this._light.id;
  72809. serializationObject.mapSize = shadowMap.getRenderSize();
  72810. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  72811. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  72812. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72813. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72814. serializationObject.usePoissonSampling = this.usePoissonSampling;
  72815. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  72816. serializationObject.depthScale = this.depthScale;
  72817. serializationObject.darkness = this.getDarkness();
  72818. serializationObject.blurBoxOffset = this.blurBoxOffset;
  72819. serializationObject.blurKernel = this.blurKernel;
  72820. serializationObject.blurScale = this.blurScale;
  72821. serializationObject.useKernelBlur = this.useKernelBlur;
  72822. serializationObject.transparencyShadow = this._transparencyShadow;
  72823. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  72824. serializationObject.bias = this.bias;
  72825. serializationObject.normalBias = this.normalBias;
  72826. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  72827. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  72828. serializationObject.filteringQuality = this.filteringQuality;
  72829. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  72830. serializationObject.renderList = [];
  72831. if (shadowMap.renderList) {
  72832. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  72833. var mesh = shadowMap.renderList[meshIndex];
  72834. serializationObject.renderList.push(mesh.id);
  72835. }
  72836. }
  72837. return serializationObject;
  72838. };
  72839. /**
  72840. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  72841. * @param parsedShadowGenerator The JSON object to parse
  72842. * @param scene The scene to create the shadow map for
  72843. * @returns The parsed shadow generator
  72844. */
  72845. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  72846. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  72847. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  72848. var shadowMap = shadowGenerator.getShadowMap();
  72849. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  72850. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  72851. meshes.forEach(function (mesh) {
  72852. if (!shadowMap) {
  72853. return;
  72854. }
  72855. if (!shadowMap.renderList) {
  72856. shadowMap.renderList = [];
  72857. }
  72858. shadowMap.renderList.push(mesh);
  72859. });
  72860. }
  72861. if (parsedShadowGenerator.usePoissonSampling) {
  72862. shadowGenerator.usePoissonSampling = true;
  72863. }
  72864. else if (parsedShadowGenerator.useExponentialShadowMap) {
  72865. shadowGenerator.useExponentialShadowMap = true;
  72866. }
  72867. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  72868. shadowGenerator.useBlurExponentialShadowMap = true;
  72869. }
  72870. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  72871. shadowGenerator.useCloseExponentialShadowMap = true;
  72872. }
  72873. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  72874. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  72875. }
  72876. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  72877. shadowGenerator.usePercentageCloserFiltering = true;
  72878. }
  72879. else if (parsedShadowGenerator.useContactHardeningShadow) {
  72880. shadowGenerator.useContactHardeningShadow = true;
  72881. }
  72882. if (parsedShadowGenerator.filteringQuality) {
  72883. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  72884. }
  72885. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  72886. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  72887. }
  72888. // Backward compat
  72889. else if (parsedShadowGenerator.useVarianceShadowMap) {
  72890. shadowGenerator.useExponentialShadowMap = true;
  72891. }
  72892. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  72893. shadowGenerator.useBlurExponentialShadowMap = true;
  72894. }
  72895. if (parsedShadowGenerator.depthScale) {
  72896. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  72897. }
  72898. if (parsedShadowGenerator.blurScale) {
  72899. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  72900. }
  72901. if (parsedShadowGenerator.blurBoxOffset) {
  72902. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  72903. }
  72904. if (parsedShadowGenerator.useKernelBlur) {
  72905. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  72906. }
  72907. if (parsedShadowGenerator.blurKernel) {
  72908. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  72909. }
  72910. if (parsedShadowGenerator.bias !== undefined) {
  72911. shadowGenerator.bias = parsedShadowGenerator.bias;
  72912. }
  72913. if (parsedShadowGenerator.normalBias !== undefined) {
  72914. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  72915. }
  72916. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  72917. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  72918. }
  72919. if (parsedShadowGenerator.darkness) {
  72920. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  72921. }
  72922. if (parsedShadowGenerator.transparencyShadow) {
  72923. shadowGenerator.setTransparencyShadow(true);
  72924. }
  72925. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  72926. return shadowGenerator;
  72927. };
  72928. /**
  72929. * Shadow generator mode None: no filtering applied.
  72930. */
  72931. ShadowGenerator.FILTER_NONE = 0;
  72932. /**
  72933. * Shadow generator mode ESM: Exponential Shadow Mapping.
  72934. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72935. */
  72936. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  72937. /**
  72938. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  72939. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  72940. */
  72941. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  72942. /**
  72943. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  72944. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72945. */
  72946. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  72947. /**
  72948. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  72949. * edge artifacts on steep falloff.
  72950. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72951. */
  72952. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  72953. /**
  72954. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  72955. * edge artifacts on steep falloff.
  72956. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72957. */
  72958. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  72959. /**
  72960. * Shadow generator mode PCF: Percentage Closer Filtering
  72961. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72962. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  72963. */
  72964. ShadowGenerator.FILTER_PCF = 6;
  72965. /**
  72966. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  72967. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72968. * Contact Hardening
  72969. */
  72970. ShadowGenerator.FILTER_PCSS = 7;
  72971. /**
  72972. * Reserved for PCF and PCSS
  72973. * Highest Quality.
  72974. *
  72975. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  72976. *
  72977. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  72978. */
  72979. ShadowGenerator.QUALITY_HIGH = 0;
  72980. /**
  72981. * Reserved for PCF and PCSS
  72982. * Good tradeoff for quality/perf cross devices
  72983. *
  72984. * Execute PCF on a 3*3 kernel.
  72985. *
  72986. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  72987. */
  72988. ShadowGenerator.QUALITY_MEDIUM = 1;
  72989. /**
  72990. * Reserved for PCF and PCSS
  72991. * The lowest quality but the fastest.
  72992. *
  72993. * Execute PCF on a 1*1 kernel.
  72994. *
  72995. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  72996. */
  72997. ShadowGenerator.QUALITY_LOW = 2;
  72998. return ShadowGenerator;
  72999. }());
  73000. BABYLON.ShadowGenerator = ShadowGenerator;
  73001. })(BABYLON || (BABYLON = {}));
  73002. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73003. var BABYLON;
  73004. (function (BABYLON) {
  73005. // Adds the parser to the scene parsers.
  73006. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73007. // Shadows
  73008. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73009. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73010. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73011. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73012. // SG would be available on their associated lights
  73013. }
  73014. }
  73015. });
  73016. /**
  73017. * Defines the shadow generator component responsible to manage any shadow generators
  73018. * in a given scene.
  73019. */
  73020. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73021. /**
  73022. * Creates a new instance of the component for the given scene
  73023. * @param scene Defines the scene to register the component in
  73024. */
  73025. function ShadowGeneratorSceneComponent(scene) {
  73026. /**
  73027. * The component name helpfull to identify the component in the list of scene components.
  73028. */
  73029. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73030. this.scene = scene;
  73031. }
  73032. /**
  73033. * Registers the component in a given scene
  73034. */
  73035. ShadowGeneratorSceneComponent.prototype.register = function () {
  73036. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73037. };
  73038. /**
  73039. * Rebuilds the elements related to this component in case of
  73040. * context lost for instance.
  73041. */
  73042. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73043. // Nothing To Do Here.
  73044. };
  73045. /**
  73046. * Serializes the component data to the specified json object
  73047. * @param serializationObject The object to serialize to
  73048. */
  73049. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73050. // Shadows
  73051. serializationObject.shadowGenerators = [];
  73052. var lights = this.scene.lights;
  73053. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73054. var light = lights_1[_i];
  73055. var shadowGenerator = light.getShadowGenerator();
  73056. if (shadowGenerator) {
  73057. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73058. }
  73059. }
  73060. };
  73061. /**
  73062. * Adds all the element from the container to the scene
  73063. * @param container the container holding the elements
  73064. */
  73065. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73066. // Nothing To Do Here. (directly attached to a light)
  73067. };
  73068. /**
  73069. * Removes all the elements in the container from the scene
  73070. * @param container contains the elements to remove
  73071. */
  73072. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73073. // Nothing To Do Here. (directly attached to a light)
  73074. };
  73075. /**
  73076. * Rebuilds the elements related to this component in case of
  73077. * context lost for instance.
  73078. */
  73079. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73080. // Nothing To Do Here.
  73081. };
  73082. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73083. // Shadows
  73084. var scene = this.scene;
  73085. if (this.scene.shadowsEnabled) {
  73086. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73087. var light = scene.lights[lightIndex];
  73088. var shadowGenerator = light.getShadowGenerator();
  73089. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73090. var shadowMap = (shadowGenerator.getShadowMap());
  73091. if (scene.textures.indexOf(shadowMap) !== -1) {
  73092. renderTargets.push(shadowMap);
  73093. }
  73094. }
  73095. }
  73096. }
  73097. };
  73098. return ShadowGeneratorSceneComponent;
  73099. }());
  73100. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73101. })(BABYLON || (BABYLON = {}));
  73102. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73103. var BABYLON;
  73104. (function (BABYLON) {
  73105. var DefaultLoadingScreen = /** @class */ (function () {
  73106. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73107. if (_loadingText === void 0) { _loadingText = ""; }
  73108. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73109. var _this = this;
  73110. this._renderingCanvas = _renderingCanvas;
  73111. this._loadingText = _loadingText;
  73112. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73113. // Resize
  73114. this._resizeLoadingUI = function () {
  73115. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73116. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73117. if (!_this._loadingDiv) {
  73118. return;
  73119. }
  73120. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73121. _this._loadingDiv.style.left = canvasRect.left + "px";
  73122. _this._loadingDiv.style.top = canvasRect.top + "px";
  73123. _this._loadingDiv.style.width = canvasRect.width + "px";
  73124. _this._loadingDiv.style.height = canvasRect.height + "px";
  73125. };
  73126. }
  73127. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73128. if (this._loadingDiv) {
  73129. // Do not add a loading screen if there is already one
  73130. return;
  73131. }
  73132. this._loadingDiv = document.createElement("div");
  73133. this._loadingDiv.id = "babylonjsLoadingDiv";
  73134. this._loadingDiv.style.opacity = "0";
  73135. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73136. this._loadingDiv.style.pointerEvents = "none";
  73137. // Loading text
  73138. this._loadingTextDiv = document.createElement("div");
  73139. this._loadingTextDiv.style.position = "absolute";
  73140. this._loadingTextDiv.style.left = "0";
  73141. this._loadingTextDiv.style.top = "50%";
  73142. this._loadingTextDiv.style.marginTop = "80px";
  73143. this._loadingTextDiv.style.width = "100%";
  73144. this._loadingTextDiv.style.height = "20px";
  73145. this._loadingTextDiv.style.fontFamily = "Arial";
  73146. this._loadingTextDiv.style.fontSize = "14px";
  73147. this._loadingTextDiv.style.color = "white";
  73148. this._loadingTextDiv.style.textAlign = "center";
  73149. this._loadingTextDiv.innerHTML = "Loading";
  73150. this._loadingDiv.appendChild(this._loadingTextDiv);
  73151. //set the predefined text
  73152. this._loadingTextDiv.innerHTML = this._loadingText;
  73153. // Generating keyframes
  73154. var style = document.createElement('style');
  73155. style.type = 'text/css';
  73156. 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 }";
  73157. style.innerHTML = keyFrames;
  73158. document.getElementsByTagName('head')[0].appendChild(style);
  73159. // Loading img
  73160. var imgBack = new Image();
  73161. 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";
  73162. imgBack.style.position = "absolute";
  73163. imgBack.style.left = "50%";
  73164. imgBack.style.top = "50%";
  73165. imgBack.style.marginLeft = "-60px";
  73166. imgBack.style.marginTop = "-60px";
  73167. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73168. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73169. imgBack.style.transformOrigin = "50% 50%";
  73170. imgBack.style.webkitTransformOrigin = "50% 50%";
  73171. this._loadingDiv.appendChild(imgBack);
  73172. this._resizeLoadingUI();
  73173. window.addEventListener("resize", this._resizeLoadingUI);
  73174. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73175. document.body.appendChild(this._loadingDiv);
  73176. this._loadingDiv.style.opacity = "1";
  73177. };
  73178. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73179. var _this = this;
  73180. if (!this._loadingDiv) {
  73181. return;
  73182. }
  73183. var onTransitionEnd = function () {
  73184. if (!_this._loadingDiv) {
  73185. return;
  73186. }
  73187. document.body.removeChild(_this._loadingDiv);
  73188. window.removeEventListener("resize", _this._resizeLoadingUI);
  73189. _this._loadingDiv = null;
  73190. };
  73191. this._loadingDiv.style.opacity = "0";
  73192. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73193. };
  73194. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73195. set: function (text) {
  73196. this._loadingText = text;
  73197. if (this._loadingTextDiv) {
  73198. this._loadingTextDiv.innerHTML = this._loadingText;
  73199. }
  73200. },
  73201. enumerable: true,
  73202. configurable: true
  73203. });
  73204. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73205. get: function () {
  73206. return this._loadingDivBackgroundColor;
  73207. },
  73208. set: function (color) {
  73209. this._loadingDivBackgroundColor = color;
  73210. if (!this._loadingDiv) {
  73211. return;
  73212. }
  73213. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73214. },
  73215. enumerable: true,
  73216. configurable: true
  73217. });
  73218. return DefaultLoadingScreen;
  73219. }());
  73220. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73221. })(BABYLON || (BABYLON = {}));
  73222. //# sourceMappingURL=babylon.loadingScreen.js.map
  73223. var BABYLON;
  73224. (function (BABYLON) {
  73225. var SceneLoaderProgressEvent = /** @class */ (function () {
  73226. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73227. this.lengthComputable = lengthComputable;
  73228. this.loaded = loaded;
  73229. this.total = total;
  73230. }
  73231. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73232. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73233. };
  73234. return SceneLoaderProgressEvent;
  73235. }());
  73236. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73237. var SceneLoader = /** @class */ (function () {
  73238. function SceneLoader() {
  73239. }
  73240. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73241. get: function () {
  73242. return 0;
  73243. },
  73244. enumerable: true,
  73245. configurable: true
  73246. });
  73247. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73248. get: function () {
  73249. return 1;
  73250. },
  73251. enumerable: true,
  73252. configurable: true
  73253. });
  73254. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73255. get: function () {
  73256. return 2;
  73257. },
  73258. enumerable: true,
  73259. configurable: true
  73260. });
  73261. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73262. get: function () {
  73263. return 3;
  73264. },
  73265. enumerable: true,
  73266. configurable: true
  73267. });
  73268. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73269. get: function () {
  73270. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73271. },
  73272. set: function (value) {
  73273. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73274. },
  73275. enumerable: true,
  73276. configurable: true
  73277. });
  73278. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73279. get: function () {
  73280. return SceneLoader._ShowLoadingScreen;
  73281. },
  73282. set: function (value) {
  73283. SceneLoader._ShowLoadingScreen = value;
  73284. },
  73285. enumerable: true,
  73286. configurable: true
  73287. });
  73288. Object.defineProperty(SceneLoader, "loggingLevel", {
  73289. get: function () {
  73290. return SceneLoader._loggingLevel;
  73291. },
  73292. set: function (value) {
  73293. SceneLoader._loggingLevel = value;
  73294. },
  73295. enumerable: true,
  73296. configurable: true
  73297. });
  73298. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73299. get: function () {
  73300. return SceneLoader._CleanBoneMatrixWeights;
  73301. },
  73302. set: function (value) {
  73303. SceneLoader._CleanBoneMatrixWeights = value;
  73304. },
  73305. enumerable: true,
  73306. configurable: true
  73307. });
  73308. SceneLoader._getDefaultPlugin = function () {
  73309. return SceneLoader._registeredPlugins[".babylon"];
  73310. };
  73311. SceneLoader._getPluginForExtension = function (extension) {
  73312. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73313. if (registeredPlugin) {
  73314. return registeredPlugin;
  73315. }
  73316. 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");
  73317. return SceneLoader._getDefaultPlugin();
  73318. };
  73319. SceneLoader._getPluginForDirectLoad = function (data) {
  73320. for (var extension in SceneLoader._registeredPlugins) {
  73321. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73322. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73323. return SceneLoader._registeredPlugins[extension];
  73324. }
  73325. }
  73326. return SceneLoader._getDefaultPlugin();
  73327. };
  73328. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73329. var queryStringPosition = sceneFilename.indexOf("?");
  73330. if (queryStringPosition !== -1) {
  73331. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73332. }
  73333. var dotPosition = sceneFilename.lastIndexOf(".");
  73334. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73335. return SceneLoader._getPluginForExtension(extension);
  73336. };
  73337. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73338. SceneLoader._getDirectLoad = function (sceneFilename) {
  73339. if (sceneFilename.substr(0, 5) === "data:") {
  73340. return sceneFilename.substr(5);
  73341. }
  73342. return null;
  73343. };
  73344. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73345. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73346. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73347. var plugin;
  73348. if (registeredPlugin.plugin.createPlugin) {
  73349. plugin = registeredPlugin.plugin.createPlugin();
  73350. }
  73351. else {
  73352. plugin = registeredPlugin.plugin;
  73353. }
  73354. var useArrayBuffer = registeredPlugin.isBinary;
  73355. var database;
  73356. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73357. var dataCallback = function (data, responseURL) {
  73358. if (scene.isDisposed) {
  73359. onError("Scene has been disposed");
  73360. return;
  73361. }
  73362. scene.database = database;
  73363. onSuccess(plugin, data, responseURL);
  73364. };
  73365. var request = null;
  73366. var pluginDisposed = false;
  73367. var onDisposeObservable = plugin.onDisposeObservable;
  73368. if (onDisposeObservable) {
  73369. onDisposeObservable.add(function () {
  73370. pluginDisposed = true;
  73371. if (request) {
  73372. request.abort();
  73373. request = null;
  73374. }
  73375. onDispose();
  73376. });
  73377. }
  73378. var manifestChecked = function () {
  73379. if (pluginDisposed) {
  73380. return;
  73381. }
  73382. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73383. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73384. } : undefined, database, useArrayBuffer, function (request, exception) {
  73385. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73386. });
  73387. };
  73388. if (directLoad) {
  73389. dataCallback(directLoad);
  73390. return plugin;
  73391. }
  73392. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73393. var engine = scene.getEngine();
  73394. var canUseOfflineSupport = engine.enableOfflineSupport;
  73395. if (canUseOfflineSupport) {
  73396. // Also check for exceptions
  73397. var exceptionFound = false;
  73398. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73399. var regex = _a[_i];
  73400. if (regex.test(fileInfo.url)) {
  73401. exceptionFound = true;
  73402. break;
  73403. }
  73404. }
  73405. canUseOfflineSupport = !exceptionFound;
  73406. }
  73407. if (canUseOfflineSupport) {
  73408. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73409. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73410. }
  73411. else {
  73412. manifestChecked();
  73413. }
  73414. }
  73415. // Loading file from disk via input file or drag'n'drop
  73416. else {
  73417. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73418. if (file) {
  73419. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73420. }
  73421. else {
  73422. onError("Unable to find file named " + fileInfo.name);
  73423. }
  73424. }
  73425. return plugin;
  73426. };
  73427. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73428. var url;
  73429. var name;
  73430. if (!sceneFilename) {
  73431. url = rootUrl;
  73432. name = BABYLON.Tools.GetFilename(rootUrl);
  73433. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73434. }
  73435. else {
  73436. if (sceneFilename.substr(0, 1) === "/") {
  73437. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73438. return null;
  73439. }
  73440. url = rootUrl + sceneFilename;
  73441. name = sceneFilename;
  73442. }
  73443. ;
  73444. return {
  73445. url: url,
  73446. rootUrl: rootUrl,
  73447. name: name
  73448. };
  73449. };
  73450. // Public functions
  73451. SceneLoader.GetPluginForExtension = function (extension) {
  73452. return SceneLoader._getPluginForExtension(extension).plugin;
  73453. };
  73454. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73455. return !!SceneLoader._registeredPlugins[extension];
  73456. };
  73457. SceneLoader.RegisterPlugin = function (plugin) {
  73458. if (typeof plugin.extensions === "string") {
  73459. var extension = plugin.extensions;
  73460. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73461. plugin: plugin,
  73462. isBinary: false
  73463. };
  73464. }
  73465. else {
  73466. var extensions = plugin.extensions;
  73467. Object.keys(extensions).forEach(function (extension) {
  73468. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73469. plugin: plugin,
  73470. isBinary: extensions[extension].isBinary
  73471. };
  73472. });
  73473. }
  73474. };
  73475. /**
  73476. * Import meshes into a scene
  73477. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73478. * @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)
  73479. * @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)
  73480. * @param scene the instance of BABYLON.Scene to append to
  73481. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73482. * @param onProgress a callback with a progress event for each file being loaded
  73483. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73484. * @param pluginExtension the extension used to determine the plugin
  73485. * @returns The loaded plugin
  73486. */
  73487. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73488. if (sceneFilename === void 0) { sceneFilename = ""; }
  73489. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73490. if (onSuccess === void 0) { onSuccess = null; }
  73491. if (onProgress === void 0) { onProgress = null; }
  73492. if (onError === void 0) { onError = null; }
  73493. if (pluginExtension === void 0) { pluginExtension = null; }
  73494. if (!scene) {
  73495. BABYLON.Tools.Error("No scene available to import mesh to");
  73496. return null;
  73497. }
  73498. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73499. if (!fileInfo) {
  73500. return null;
  73501. }
  73502. var loadingToken = {};
  73503. scene._addPendingData(loadingToken);
  73504. var disposeHandler = function () {
  73505. scene._removePendingData(loadingToken);
  73506. };
  73507. var errorHandler = function (message, exception) {
  73508. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  73509. if (onError) {
  73510. onError(scene, errorMessage, exception);
  73511. }
  73512. else {
  73513. BABYLON.Tools.Error(errorMessage);
  73514. // should the exception be thrown?
  73515. }
  73516. disposeHandler();
  73517. };
  73518. var progressHandler = onProgress ? function (event) {
  73519. try {
  73520. onProgress(event);
  73521. }
  73522. catch (e) {
  73523. errorHandler("Error in onProgress callback", e);
  73524. }
  73525. } : undefined;
  73526. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  73527. scene.importedMeshesFiles.push(fileInfo.url);
  73528. if (onSuccess) {
  73529. try {
  73530. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  73531. }
  73532. catch (e) {
  73533. errorHandler("Error in onSuccess callback", e);
  73534. }
  73535. }
  73536. scene._removePendingData(loadingToken);
  73537. };
  73538. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73539. if (plugin.rewriteRootURL) {
  73540. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  73541. }
  73542. if (plugin.importMesh) {
  73543. var syncedPlugin = plugin;
  73544. var meshes = new Array();
  73545. var particleSystems = new Array();
  73546. var skeletons = new Array();
  73547. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  73548. return;
  73549. }
  73550. scene.loadingPluginName = plugin.name;
  73551. successHandler(meshes, particleSystems, skeletons, []);
  73552. }
  73553. else {
  73554. var asyncedPlugin = plugin;
  73555. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  73556. scene.loadingPluginName = plugin.name;
  73557. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  73558. }).catch(function (error) {
  73559. errorHandler(error.message, error);
  73560. });
  73561. }
  73562. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73563. };
  73564. /**
  73565. * Import meshes into a scene
  73566. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73567. * @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)
  73568. * @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)
  73569. * @param scene the instance of BABYLON.Scene to append to
  73570. * @param onProgress a callback with a progress event for each file being loaded
  73571. * @param pluginExtension the extension used to determine the plugin
  73572. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  73573. */
  73574. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73575. if (sceneFilename === void 0) { sceneFilename = ""; }
  73576. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73577. if (onProgress === void 0) { onProgress = null; }
  73578. if (pluginExtension === void 0) { pluginExtension = null; }
  73579. return new Promise(function (resolve, reject) {
  73580. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  73581. resolve({
  73582. meshes: meshes,
  73583. particleSystems: particleSystems,
  73584. skeletons: skeletons,
  73585. animationGroups: animationGroups
  73586. });
  73587. }, onProgress, function (scene, message, exception) {
  73588. reject(exception || new Error(message));
  73589. }, pluginExtension);
  73590. });
  73591. };
  73592. /**
  73593. * Load a scene
  73594. * @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)
  73595. * @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)
  73596. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73597. * @param onSuccess a callback with the scene when import succeeds
  73598. * @param onProgress a callback with a progress event for each file being loaded
  73599. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73600. * @param pluginExtension the extension used to determine the plugin
  73601. * @returns The loaded plugin
  73602. */
  73603. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  73604. if (onSuccess === void 0) { onSuccess = null; }
  73605. if (onProgress === void 0) { onProgress = null; }
  73606. if (onError === void 0) { onError = null; }
  73607. if (pluginExtension === void 0) { pluginExtension = null; }
  73608. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  73609. };
  73610. /**
  73611. * Load a scene
  73612. * @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)
  73613. * @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)
  73614. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73615. * @param onProgress a callback with a progress event for each file being loaded
  73616. * @param pluginExtension the extension used to determine the plugin
  73617. * @returns The loaded scene
  73618. */
  73619. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  73620. if (onProgress === void 0) { onProgress = null; }
  73621. if (pluginExtension === void 0) { pluginExtension = null; }
  73622. return new Promise(function (resolve, reject) {
  73623. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  73624. resolve(scene);
  73625. }, onProgress, function (scene, message, exception) {
  73626. reject(exception || new Error(message));
  73627. }, pluginExtension);
  73628. });
  73629. };
  73630. /**
  73631. * Append a scene
  73632. * @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)
  73633. * @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)
  73634. * @param scene is the instance of BABYLON.Scene to append to
  73635. * @param onSuccess a callback with the scene when import succeeds
  73636. * @param onProgress a callback with a progress event for each file being loaded
  73637. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73638. * @param pluginExtension the extension used to determine the plugin
  73639. * @returns The loaded plugin
  73640. */
  73641. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73642. if (sceneFilename === void 0) { sceneFilename = ""; }
  73643. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73644. if (onSuccess === void 0) { onSuccess = null; }
  73645. if (onProgress === void 0) { onProgress = null; }
  73646. if (onError === void 0) { onError = null; }
  73647. if (pluginExtension === void 0) { pluginExtension = null; }
  73648. if (!scene) {
  73649. BABYLON.Tools.Error("No scene available to append to");
  73650. return null;
  73651. }
  73652. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73653. if (!fileInfo) {
  73654. return null;
  73655. }
  73656. if (SceneLoader.ShowLoadingScreen) {
  73657. scene.getEngine().displayLoadingUI();
  73658. }
  73659. var loadingToken = {};
  73660. scene._addPendingData(loadingToken);
  73661. var disposeHandler = function () {
  73662. scene._removePendingData(loadingToken);
  73663. scene.getEngine().hideLoadingUI();
  73664. };
  73665. var errorHandler = function (message, exception) {
  73666. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  73667. if (onError) {
  73668. onError(scene, errorMessage, exception);
  73669. }
  73670. else {
  73671. BABYLON.Tools.Error(errorMessage);
  73672. // should the exception be thrown?
  73673. }
  73674. disposeHandler();
  73675. };
  73676. var progressHandler = onProgress ? function (event) {
  73677. try {
  73678. onProgress(event);
  73679. }
  73680. catch (e) {
  73681. errorHandler("Error in onProgress callback", e);
  73682. }
  73683. } : undefined;
  73684. var successHandler = function () {
  73685. if (onSuccess) {
  73686. try {
  73687. onSuccess(scene);
  73688. }
  73689. catch (e) {
  73690. errorHandler("Error in onSuccess callback", e);
  73691. }
  73692. }
  73693. scene._removePendingData(loadingToken);
  73694. };
  73695. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73696. if (plugin.load) {
  73697. var syncedPlugin = plugin;
  73698. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  73699. return;
  73700. }
  73701. scene.loadingPluginName = plugin.name;
  73702. successHandler();
  73703. }
  73704. else {
  73705. var asyncedPlugin = plugin;
  73706. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  73707. scene.loadingPluginName = plugin.name;
  73708. successHandler();
  73709. }).catch(function (error) {
  73710. errorHandler(error.message, error);
  73711. });
  73712. }
  73713. if (SceneLoader.ShowLoadingScreen) {
  73714. scene.executeWhenReady(function () {
  73715. scene.getEngine().hideLoadingUI();
  73716. });
  73717. }
  73718. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73719. };
  73720. /**
  73721. * Append a scene
  73722. * @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)
  73723. * @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)
  73724. * @param scene is the instance of BABYLON.Scene to append to
  73725. * @param onProgress a callback with a progress event for each file being loaded
  73726. * @param pluginExtension the extension used to determine the plugin
  73727. * @returns The given scene
  73728. */
  73729. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73730. if (sceneFilename === void 0) { sceneFilename = ""; }
  73731. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73732. if (onProgress === void 0) { onProgress = null; }
  73733. if (pluginExtension === void 0) { pluginExtension = null; }
  73734. return new Promise(function (resolve, reject) {
  73735. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  73736. resolve(scene);
  73737. }, onProgress, function (scene, message, exception) {
  73738. reject(exception || new Error(message));
  73739. }, pluginExtension);
  73740. });
  73741. };
  73742. /**
  73743. * Load a scene into an asset container
  73744. * @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)
  73745. * @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)
  73746. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  73747. * @param onSuccess a callback with the scene when import succeeds
  73748. * @param onProgress a callback with a progress event for each file being loaded
  73749. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73750. * @param pluginExtension the extension used to determine the plugin
  73751. * @returns The loaded plugin
  73752. */
  73753. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73754. if (sceneFilename === void 0) { sceneFilename = ""; }
  73755. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73756. if (onSuccess === void 0) { onSuccess = null; }
  73757. if (onProgress === void 0) { onProgress = null; }
  73758. if (onError === void 0) { onError = null; }
  73759. if (pluginExtension === void 0) { pluginExtension = null; }
  73760. if (!scene) {
  73761. BABYLON.Tools.Error("No scene available to load asset container to");
  73762. return null;
  73763. }
  73764. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73765. if (!fileInfo) {
  73766. return null;
  73767. }
  73768. var loadingToken = {};
  73769. scene._addPendingData(loadingToken);
  73770. var disposeHandler = function () {
  73771. scene._removePendingData(loadingToken);
  73772. };
  73773. var errorHandler = function (message, exception) {
  73774. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  73775. if (onError) {
  73776. onError(scene, errorMessage, exception);
  73777. }
  73778. else {
  73779. BABYLON.Tools.Error(errorMessage);
  73780. // should the exception be thrown?
  73781. }
  73782. disposeHandler();
  73783. };
  73784. var progressHandler = onProgress ? function (event) {
  73785. try {
  73786. onProgress(event);
  73787. }
  73788. catch (e) {
  73789. errorHandler("Error in onProgress callback", e);
  73790. }
  73791. } : undefined;
  73792. var successHandler = function (assets) {
  73793. if (onSuccess) {
  73794. try {
  73795. onSuccess(assets);
  73796. }
  73797. catch (e) {
  73798. errorHandler("Error in onSuccess callback", e);
  73799. }
  73800. }
  73801. scene._removePendingData(loadingToken);
  73802. };
  73803. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73804. if (plugin.loadAssetContainer) {
  73805. var syncedPlugin = plugin;
  73806. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  73807. if (!assetContainer) {
  73808. return;
  73809. }
  73810. scene.loadingPluginName = plugin.name;
  73811. successHandler(assetContainer);
  73812. }
  73813. else if (plugin.loadAssetContainerAsync) {
  73814. var asyncedPlugin = plugin;
  73815. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  73816. scene.loadingPluginName = plugin.name;
  73817. successHandler(assetContainer);
  73818. }).catch(function (error) {
  73819. errorHandler(error.message, error);
  73820. });
  73821. }
  73822. else {
  73823. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  73824. }
  73825. if (SceneLoader.ShowLoadingScreen) {
  73826. scene.executeWhenReady(function () {
  73827. scene.getEngine().hideLoadingUI();
  73828. });
  73829. }
  73830. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73831. };
  73832. /**
  73833. * Load a scene into an asset container
  73834. * @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)
  73835. * @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)
  73836. * @param scene is the instance of BABYLON.Scene to append to
  73837. * @param onProgress a callback with a progress event for each file being loaded
  73838. * @param pluginExtension the extension used to determine the plugin
  73839. * @returns The loaded asset container
  73840. */
  73841. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73842. if (sceneFilename === void 0) { sceneFilename = ""; }
  73843. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73844. if (onProgress === void 0) { onProgress = null; }
  73845. if (pluginExtension === void 0) { pluginExtension = null; }
  73846. return new Promise(function (resolve, reject) {
  73847. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  73848. resolve(assetContainer);
  73849. }, onProgress, function (scene, message, exception) {
  73850. reject(exception || new Error(message));
  73851. }, pluginExtension);
  73852. });
  73853. };
  73854. // Flags
  73855. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  73856. SceneLoader._ShowLoadingScreen = true;
  73857. SceneLoader._CleanBoneMatrixWeights = false;
  73858. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  73859. // Members
  73860. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  73861. SceneLoader._registeredPlugins = {};
  73862. return SceneLoader;
  73863. }());
  73864. BABYLON.SceneLoader = SceneLoader;
  73865. ;
  73866. })(BABYLON || (BABYLON = {}));
  73867. //# sourceMappingURL=babylon.sceneLoader.js.map
  73868. var BABYLON;
  73869. (function (BABYLON) {
  73870. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  73871. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73872. var parsedMaterial = parsedData.materials[index];
  73873. if (parsedMaterial.id === id) {
  73874. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73875. }
  73876. }
  73877. return null;
  73878. };
  73879. var isDescendantOf = function (mesh, names, hierarchyIds) {
  73880. for (var i in names) {
  73881. if (mesh.name === names[i]) {
  73882. hierarchyIds.push(mesh.id);
  73883. return true;
  73884. }
  73885. }
  73886. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  73887. hierarchyIds.push(mesh.id);
  73888. return true;
  73889. }
  73890. return false;
  73891. };
  73892. var logOperation = function (operation, producer) {
  73893. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  73894. };
  73895. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  73896. if (addToScene === void 0) { addToScene = false; }
  73897. var container = new BABYLON.AssetContainer(scene);
  73898. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  73899. // when SceneLoader.debugLogging = true (default), or exception encountered.
  73900. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  73901. // and avoid problems with multiple concurrent .babylon loads.
  73902. var log = "importScene has failed JSON parse";
  73903. try {
  73904. var parsedData = JSON.parse(data);
  73905. log = "";
  73906. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  73907. var index;
  73908. var cache;
  73909. // Lights
  73910. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  73911. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  73912. var parsedLight = parsedData.lights[index];
  73913. var light = BABYLON.Light.Parse(parsedLight, scene);
  73914. if (light) {
  73915. container.lights.push(light);
  73916. log += (index === 0 ? "\n\tLights:" : "");
  73917. log += "\n\t\t" + light.toString(fullDetails);
  73918. }
  73919. }
  73920. }
  73921. // Animations
  73922. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  73923. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  73924. var parsedAnimation = parsedData.animations[index];
  73925. var animation = BABYLON.Animation.Parse(parsedAnimation);
  73926. scene.animations.push(animation);
  73927. container.animations.push(animation);
  73928. log += (index === 0 ? "\n\tAnimations:" : "");
  73929. log += "\n\t\t" + animation.toString(fullDetails);
  73930. }
  73931. }
  73932. // Materials
  73933. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  73934. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73935. var parsedMaterial = parsedData.materials[index];
  73936. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73937. container.materials.push(mat);
  73938. log += (index === 0 ? "\n\tMaterials:" : "");
  73939. log += "\n\t\t" + mat.toString(fullDetails);
  73940. }
  73941. }
  73942. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  73943. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  73944. var parsedMultiMaterial = parsedData.multiMaterials[index];
  73945. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  73946. container.multiMaterials.push(mmat);
  73947. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  73948. log += "\n\t\t" + mmat.toString(fullDetails);
  73949. }
  73950. }
  73951. // Morph targets
  73952. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  73953. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  73954. var managerData = _a[_i];
  73955. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  73956. }
  73957. }
  73958. // Skeletons
  73959. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  73960. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  73961. var parsedSkeleton = parsedData.skeletons[index];
  73962. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  73963. container.skeletons.push(skeleton);
  73964. log += (index === 0 ? "\n\tSkeletons:" : "");
  73965. log += "\n\t\t" + skeleton.toString(fullDetails);
  73966. }
  73967. }
  73968. // Geometries
  73969. var geometries = parsedData.geometries;
  73970. if (geometries !== undefined && geometries !== null) {
  73971. var addedGeometry = new Array();
  73972. // Boxes
  73973. var boxes = geometries.boxes;
  73974. if (boxes !== undefined && boxes !== null) {
  73975. for (index = 0, cache = boxes.length; index < cache; index++) {
  73976. var parsedBox = boxes[index];
  73977. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  73978. }
  73979. }
  73980. // Spheres
  73981. var spheres = geometries.spheres;
  73982. if (spheres !== undefined && spheres !== null) {
  73983. for (index = 0, cache = spheres.length; index < cache; index++) {
  73984. var parsedSphere = spheres[index];
  73985. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  73986. }
  73987. }
  73988. // Cylinders
  73989. var cylinders = geometries.cylinders;
  73990. if (cylinders !== undefined && cylinders !== null) {
  73991. for (index = 0, cache = cylinders.length; index < cache; index++) {
  73992. var parsedCylinder = cylinders[index];
  73993. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  73994. }
  73995. }
  73996. // Toruses
  73997. var toruses = geometries.toruses;
  73998. if (toruses !== undefined && toruses !== null) {
  73999. for (index = 0, cache = toruses.length; index < cache; index++) {
  74000. var parsedTorus = toruses[index];
  74001. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74002. }
  74003. }
  74004. // Grounds
  74005. var grounds = geometries.grounds;
  74006. if (grounds !== undefined && grounds !== null) {
  74007. for (index = 0, cache = grounds.length; index < cache; index++) {
  74008. var parsedGround = grounds[index];
  74009. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74010. }
  74011. }
  74012. // Planes
  74013. var planes = geometries.planes;
  74014. if (planes !== undefined && planes !== null) {
  74015. for (index = 0, cache = planes.length; index < cache; index++) {
  74016. var parsedPlane = planes[index];
  74017. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74018. }
  74019. }
  74020. // TorusKnots
  74021. var torusKnots = geometries.torusKnots;
  74022. if (torusKnots !== undefined && torusKnots !== null) {
  74023. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74024. var parsedTorusKnot = torusKnots[index];
  74025. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74026. }
  74027. }
  74028. // VertexData
  74029. var vertexData = geometries.vertexData;
  74030. if (vertexData !== undefined && vertexData !== null) {
  74031. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74032. var parsedVertexData = vertexData[index];
  74033. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74034. }
  74035. }
  74036. addedGeometry.forEach(function (g) {
  74037. if (g) {
  74038. container.geometries.push(g);
  74039. }
  74040. });
  74041. }
  74042. // Transform nodes
  74043. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74044. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74045. var parsedTransformNode = parsedData.transformNodes[index];
  74046. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74047. container.transformNodes.push(node);
  74048. }
  74049. }
  74050. // Meshes
  74051. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74052. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74053. var parsedMesh = parsedData.meshes[index];
  74054. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74055. container.meshes.push(mesh);
  74056. log += (index === 0 ? "\n\tMeshes:" : "");
  74057. log += "\n\t\t" + mesh.toString(fullDetails);
  74058. }
  74059. }
  74060. // Cameras
  74061. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74062. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74063. var parsedCamera = parsedData.cameras[index];
  74064. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74065. container.cameras.push(camera);
  74066. log += (index === 0 ? "\n\tCameras:" : "");
  74067. log += "\n\t\t" + camera.toString(fullDetails);
  74068. }
  74069. }
  74070. // Animation Groups
  74071. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74072. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74073. var parsedAnimationGroup = parsedData.animationGroups[index];
  74074. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74075. container.animationGroups.push(animationGroup);
  74076. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74077. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74078. }
  74079. }
  74080. // Browsing all the graph to connect the dots
  74081. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74082. var camera = scene.cameras[index];
  74083. if (camera._waitingParentId) {
  74084. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74085. camera._waitingParentId = null;
  74086. }
  74087. }
  74088. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74089. var light_1 = scene.lights[index];
  74090. if (light_1 && light_1._waitingParentId) {
  74091. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74092. light_1._waitingParentId = null;
  74093. }
  74094. }
  74095. // Connect parents & children and parse actions
  74096. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74097. var transformNode = scene.transformNodes[index];
  74098. if (transformNode._waitingParentId) {
  74099. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74100. transformNode._waitingParentId = null;
  74101. }
  74102. }
  74103. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74104. var mesh = scene.meshes[index];
  74105. if (mesh._waitingParentId) {
  74106. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74107. mesh._waitingParentId = null;
  74108. }
  74109. }
  74110. // freeze world matrix application
  74111. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74112. var currentMesh = scene.meshes[index];
  74113. if (currentMesh._waitingFreezeWorldMatrix) {
  74114. currentMesh.freezeWorldMatrix();
  74115. currentMesh._waitingFreezeWorldMatrix = null;
  74116. }
  74117. else {
  74118. currentMesh.computeWorldMatrix(true);
  74119. }
  74120. }
  74121. // Lights exclusions / inclusions
  74122. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74123. var light_2 = scene.lights[index];
  74124. // Excluded check
  74125. if (light_2._excludedMeshesIds.length > 0) {
  74126. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74127. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74128. if (excludedMesh) {
  74129. light_2.excludedMeshes.push(excludedMesh);
  74130. }
  74131. }
  74132. light_2._excludedMeshesIds = [];
  74133. }
  74134. // Included check
  74135. if (light_2._includedOnlyMeshesIds.length > 0) {
  74136. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74137. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74138. if (includedOnlyMesh) {
  74139. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74140. }
  74141. }
  74142. light_2._includedOnlyMeshesIds = [];
  74143. }
  74144. }
  74145. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74146. // Actions (scene) Done last as it can access other objects.
  74147. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74148. var mesh = scene.meshes[index];
  74149. if (mesh._waitingActions) {
  74150. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74151. mesh._waitingActions = null;
  74152. }
  74153. }
  74154. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74155. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74156. }
  74157. if (!addToScene) {
  74158. container.removeAllFromScene();
  74159. }
  74160. }
  74161. catch (err) {
  74162. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74163. if (onError) {
  74164. onError(msg, err);
  74165. }
  74166. else {
  74167. BABYLON.Tools.Log(msg);
  74168. throw err;
  74169. }
  74170. }
  74171. finally {
  74172. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74173. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74174. }
  74175. }
  74176. return container;
  74177. };
  74178. BABYLON.SceneLoader.RegisterPlugin({
  74179. name: "babylon.js",
  74180. extensions: ".babylon",
  74181. canDirectLoad: function (data) {
  74182. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74183. return true;
  74184. }
  74185. return false;
  74186. },
  74187. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74188. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74189. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74190. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74191. // and avoid problems with multiple concurrent .babylon loads.
  74192. var log = "importMesh has failed JSON parse";
  74193. try {
  74194. var parsedData = JSON.parse(data);
  74195. log = "";
  74196. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74197. if (!meshesNames) {
  74198. meshesNames = null;
  74199. }
  74200. else if (!Array.isArray(meshesNames)) {
  74201. meshesNames = [meshesNames];
  74202. }
  74203. var hierarchyIds = new Array();
  74204. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74205. var loadedSkeletonsIds = [];
  74206. var loadedMaterialsIds = [];
  74207. var index;
  74208. var cache;
  74209. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74210. var parsedMesh = parsedData.meshes[index];
  74211. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74212. if (meshesNames !== null) {
  74213. // Remove found mesh name from list.
  74214. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74215. }
  74216. //Geometry?
  74217. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74218. //does the file contain geometries?
  74219. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74220. //find the correct geometry and add it to the scene
  74221. var found = false;
  74222. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74223. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74224. return;
  74225. }
  74226. else {
  74227. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74228. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74229. switch (geometryType) {
  74230. case "boxes":
  74231. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74232. break;
  74233. case "spheres":
  74234. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74235. break;
  74236. case "cylinders":
  74237. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74238. break;
  74239. case "toruses":
  74240. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74241. break;
  74242. case "grounds":
  74243. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74244. break;
  74245. case "planes":
  74246. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74247. break;
  74248. case "torusKnots":
  74249. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74250. break;
  74251. case "vertexData":
  74252. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74253. break;
  74254. }
  74255. found = true;
  74256. }
  74257. });
  74258. }
  74259. });
  74260. if (found === false) {
  74261. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74262. }
  74263. }
  74264. }
  74265. // Material ?
  74266. if (parsedMesh.materialId) {
  74267. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74268. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74269. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74270. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74271. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74272. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74273. var subMatId = parsedMultiMaterial.materials[matIndex];
  74274. loadedMaterialsIds.push(subMatId);
  74275. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74276. if (mat) {
  74277. log += "\n\tMaterial " + mat.toString(fullDetails);
  74278. }
  74279. }
  74280. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74281. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74282. if (mmat) {
  74283. materialFound = true;
  74284. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74285. }
  74286. break;
  74287. }
  74288. }
  74289. }
  74290. if (materialFound === false) {
  74291. loadedMaterialsIds.push(parsedMesh.materialId);
  74292. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74293. if (!mat) {
  74294. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74295. }
  74296. else {
  74297. log += "\n\tMaterial " + mat.toString(fullDetails);
  74298. }
  74299. }
  74300. }
  74301. // Skeleton ?
  74302. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74303. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74304. if (skeletonAlreadyLoaded === false) {
  74305. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74306. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74307. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74308. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74309. skeletons.push(skeleton);
  74310. loadedSkeletonsIds.push(parsedSkeleton.id);
  74311. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74312. }
  74313. }
  74314. }
  74315. }
  74316. // Morph targets ?
  74317. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74318. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74319. var managerData = _a[_i];
  74320. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74321. }
  74322. }
  74323. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74324. meshes.push(mesh);
  74325. log += "\n\tMesh " + mesh.toString(fullDetails);
  74326. }
  74327. }
  74328. // Connecting parents
  74329. var currentMesh;
  74330. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74331. currentMesh = scene.meshes[index];
  74332. if (currentMesh._waitingParentId) {
  74333. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74334. currentMesh._waitingParentId = null;
  74335. }
  74336. }
  74337. // freeze and compute world matrix application
  74338. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74339. currentMesh = scene.meshes[index];
  74340. if (currentMesh._waitingFreezeWorldMatrix) {
  74341. currentMesh.freezeWorldMatrix();
  74342. currentMesh._waitingFreezeWorldMatrix = null;
  74343. }
  74344. else {
  74345. currentMesh.computeWorldMatrix(true);
  74346. }
  74347. }
  74348. }
  74349. // Particles
  74350. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74351. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74352. if (parser) {
  74353. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74354. var parsedParticleSystem = parsedData.particleSystems[index];
  74355. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74356. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74357. }
  74358. }
  74359. }
  74360. }
  74361. return true;
  74362. }
  74363. catch (err) {
  74364. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74365. if (onError) {
  74366. onError(msg, err);
  74367. }
  74368. else {
  74369. BABYLON.Tools.Log(msg);
  74370. throw err;
  74371. }
  74372. }
  74373. finally {
  74374. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74375. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74376. }
  74377. }
  74378. return false;
  74379. },
  74380. load: function (scene, data, rootUrl, onError) {
  74381. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74382. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74383. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74384. // and avoid problems with multiple concurrent .babylon loads.
  74385. var log = "importScene has failed JSON parse";
  74386. try {
  74387. var parsedData = JSON.parse(data);
  74388. log = "";
  74389. // Scene
  74390. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74391. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74392. }
  74393. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74394. scene.autoClear = parsedData.autoClear;
  74395. }
  74396. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74397. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74398. }
  74399. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74400. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74401. }
  74402. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74403. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74404. }
  74405. // Fog
  74406. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74407. scene.fogMode = parsedData.fogMode;
  74408. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74409. scene.fogStart = parsedData.fogStart;
  74410. scene.fogEnd = parsedData.fogEnd;
  74411. scene.fogDensity = parsedData.fogDensity;
  74412. log += "\tFog mode for scene: ";
  74413. switch (scene.fogMode) {
  74414. // getters not compiling, so using hardcoded
  74415. case 1:
  74416. log += "exp\n";
  74417. break;
  74418. case 2:
  74419. log += "exp2\n";
  74420. break;
  74421. case 3:
  74422. log += "linear\n";
  74423. break;
  74424. }
  74425. }
  74426. //Physics
  74427. if (parsedData.physicsEnabled) {
  74428. var physicsPlugin;
  74429. if (parsedData.physicsEngine === "cannon") {
  74430. physicsPlugin = new BABYLON.CannonJSPlugin();
  74431. }
  74432. else if (parsedData.physicsEngine === "oimo") {
  74433. physicsPlugin = new BABYLON.OimoJSPlugin();
  74434. }
  74435. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74436. //else - default engine, which is currently oimo
  74437. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74438. scene.enablePhysics(physicsGravity, physicsPlugin);
  74439. }
  74440. // Metadata
  74441. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74442. scene.metadata = parsedData.metadata;
  74443. }
  74444. //collisions, if defined. otherwise, default is true
  74445. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74446. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74447. }
  74448. scene.workerCollisions = !!parsedData.workerCollisions;
  74449. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74450. if (!container) {
  74451. return false;
  74452. }
  74453. if (parsedData.autoAnimate) {
  74454. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74455. }
  74456. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74457. scene.setActiveCameraByID(parsedData.activeCameraID);
  74458. }
  74459. // Environment texture
  74460. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74461. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74462. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74463. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74464. if (parsedData.environmentTextureRotationY) {
  74465. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74466. }
  74467. scene.environmentTexture = hdrTexture;
  74468. }
  74469. else {
  74470. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74471. if (parsedData.environmentTextureRotationY) {
  74472. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74473. }
  74474. scene.environmentTexture = cubeTexture;
  74475. }
  74476. if (parsedData.createDefaultSkybox === true) {
  74477. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74478. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74479. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74480. }
  74481. }
  74482. // Finish
  74483. return true;
  74484. }
  74485. catch (err) {
  74486. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74487. if (onError) {
  74488. onError(msg, err);
  74489. }
  74490. else {
  74491. BABYLON.Tools.Log(msg);
  74492. throw err;
  74493. }
  74494. }
  74495. finally {
  74496. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74497. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74498. }
  74499. }
  74500. return false;
  74501. },
  74502. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74503. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74504. return container;
  74505. }
  74506. });
  74507. })(BABYLON || (BABYLON = {}));
  74508. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  74509. var BABYLON;
  74510. (function (BABYLON) {
  74511. var FilesInput = /** @class */ (function () {
  74512. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  74513. this.onProcessFileCallback = function () { return true; };
  74514. this._engine = engine;
  74515. this._currentScene = scene;
  74516. this._sceneLoadedCallback = sceneLoadedCallback;
  74517. this._progressCallback = progressCallback;
  74518. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  74519. this._textureLoadingCallback = textureLoadingCallback;
  74520. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  74521. this._onReloadCallback = onReloadCallback;
  74522. this._errorCallback = errorCallback;
  74523. }
  74524. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  74525. var _this = this;
  74526. if (elementToMonitor) {
  74527. this._elementToMonitor = elementToMonitor;
  74528. this._dragEnterHandler = function (e) { _this.drag(e); };
  74529. this._dragOverHandler = function (e) { _this.drag(e); };
  74530. this._dropHandler = function (e) { _this.drop(e); };
  74531. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  74532. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  74533. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  74534. }
  74535. };
  74536. FilesInput.prototype.dispose = function () {
  74537. if (!this._elementToMonitor) {
  74538. return;
  74539. }
  74540. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  74541. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  74542. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  74543. };
  74544. FilesInput.prototype.renderFunction = function () {
  74545. if (this._additionalRenderLoopLogicCallback) {
  74546. this._additionalRenderLoopLogicCallback();
  74547. }
  74548. if (this._currentScene) {
  74549. if (this._textureLoadingCallback) {
  74550. var remaining = this._currentScene.getWaitingItemsCount();
  74551. if (remaining > 0) {
  74552. this._textureLoadingCallback(remaining);
  74553. }
  74554. }
  74555. this._currentScene.render();
  74556. }
  74557. };
  74558. FilesInput.prototype.drag = function (e) {
  74559. e.stopPropagation();
  74560. e.preventDefault();
  74561. };
  74562. FilesInput.prototype.drop = function (eventDrop) {
  74563. eventDrop.stopPropagation();
  74564. eventDrop.preventDefault();
  74565. this.loadFiles(eventDrop);
  74566. };
  74567. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  74568. var _this = this;
  74569. var reader = folder.createReader();
  74570. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  74571. reader.readEntries(function (entries) {
  74572. remaining.count += entries.length;
  74573. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  74574. var entry = entries_1[_i];
  74575. if (entry.isFile) {
  74576. entry.file(function (file) {
  74577. file.correctName = relativePath + file.name;
  74578. files.push(file);
  74579. if (--remaining.count === 0) {
  74580. callback();
  74581. }
  74582. });
  74583. }
  74584. else if (entry.isDirectory) {
  74585. _this._traverseFolder(entry, files, remaining, callback);
  74586. }
  74587. }
  74588. if (--remaining.count) {
  74589. callback();
  74590. }
  74591. });
  74592. };
  74593. FilesInput.prototype._processFiles = function (files) {
  74594. for (var i = 0; i < files.length; i++) {
  74595. var name = files[i].correctName.toLowerCase();
  74596. var extension = name.split('.').pop();
  74597. if (!this.onProcessFileCallback(files[i], name, extension)) {
  74598. continue;
  74599. }
  74600. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  74601. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  74602. this._sceneFileToLoad = files[i];
  74603. }
  74604. FilesInput.FilesToLoad[name] = files[i];
  74605. }
  74606. };
  74607. FilesInput.prototype.loadFiles = function (event) {
  74608. var _this = this;
  74609. // Handling data transfer via drag'n'drop
  74610. if (event && event.dataTransfer && event.dataTransfer.files) {
  74611. this._filesToLoad = event.dataTransfer.files;
  74612. }
  74613. // Handling files from input files
  74614. if (event && event.target && event.target.files) {
  74615. this._filesToLoad = event.target.files;
  74616. }
  74617. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  74618. return;
  74619. }
  74620. if (this._startingProcessingFilesCallback) {
  74621. this._startingProcessingFilesCallback(this._filesToLoad);
  74622. }
  74623. if (this._filesToLoad && this._filesToLoad.length > 0) {
  74624. var files_1 = new Array();
  74625. var folders = [];
  74626. var items = event.dataTransfer ? event.dataTransfer.items : null;
  74627. for (var i = 0; i < this._filesToLoad.length; i++) {
  74628. var fileToLoad = this._filesToLoad[i];
  74629. var name_1 = fileToLoad.name.toLowerCase();
  74630. var entry = void 0;
  74631. fileToLoad.correctName = name_1;
  74632. if (items) {
  74633. var item = items[i];
  74634. if (item.getAsEntry) {
  74635. entry = item.getAsEntry();
  74636. }
  74637. else if (item.webkitGetAsEntry) {
  74638. entry = item.webkitGetAsEntry();
  74639. }
  74640. }
  74641. if (!entry) {
  74642. files_1.push(fileToLoad);
  74643. }
  74644. else {
  74645. if (entry.isDirectory) {
  74646. folders.push(entry);
  74647. }
  74648. else {
  74649. files_1.push(fileToLoad);
  74650. }
  74651. }
  74652. }
  74653. if (folders.length === 0) {
  74654. this._processFiles(files_1);
  74655. this._processReload();
  74656. }
  74657. else {
  74658. var remaining = { count: folders.length };
  74659. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  74660. var folder = folders_1[_i];
  74661. this._traverseFolder(folder, files_1, remaining, function () {
  74662. _this._processFiles(files_1);
  74663. if (remaining.count === 0) {
  74664. _this._processReload();
  74665. }
  74666. });
  74667. }
  74668. }
  74669. }
  74670. };
  74671. FilesInput.prototype._processReload = function () {
  74672. if (this._onReloadCallback) {
  74673. this._onReloadCallback(this._sceneFileToLoad);
  74674. }
  74675. else {
  74676. this.reload();
  74677. }
  74678. };
  74679. FilesInput.prototype.reload = function () {
  74680. var _this = this;
  74681. // If a scene file has been provided
  74682. if (this._sceneFileToLoad) {
  74683. if (this._currentScene) {
  74684. if (BABYLON.Tools.errorsCount > 0) {
  74685. BABYLON.Tools.ClearLogCache();
  74686. }
  74687. this._engine.stopRenderLoop();
  74688. }
  74689. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  74690. if (_this._progressCallback) {
  74691. _this._progressCallback(progress);
  74692. }
  74693. }).then(function (scene) {
  74694. if (_this._currentScene) {
  74695. _this._currentScene.dispose();
  74696. }
  74697. _this._currentScene = scene;
  74698. if (_this._sceneLoadedCallback) {
  74699. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  74700. }
  74701. // Wait for textures and shaders to be ready
  74702. _this._currentScene.executeWhenReady(function () {
  74703. _this._engine.runRenderLoop(function () {
  74704. _this.renderFunction();
  74705. });
  74706. });
  74707. }).catch(function (error) {
  74708. if (_this._errorCallback) {
  74709. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  74710. }
  74711. });
  74712. }
  74713. else {
  74714. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  74715. }
  74716. };
  74717. FilesInput.FilesToLoad = {};
  74718. return FilesInput;
  74719. }());
  74720. BABYLON.FilesInput = FilesInput;
  74721. })(BABYLON || (BABYLON = {}));
  74722. //# sourceMappingURL=babylon.filesInput.js.map
  74723. var BABYLON;
  74724. (function (BABYLON) {
  74725. var Tags = /** @class */ (function () {
  74726. function Tags() {
  74727. }
  74728. Tags.EnableFor = function (obj) {
  74729. obj._tags = obj._tags || {};
  74730. obj.hasTags = function () {
  74731. return Tags.HasTags(obj);
  74732. };
  74733. obj.addTags = function (tagsString) {
  74734. return Tags.AddTagsTo(obj, tagsString);
  74735. };
  74736. obj.removeTags = function (tagsString) {
  74737. return Tags.RemoveTagsFrom(obj, tagsString);
  74738. };
  74739. obj.matchesTagsQuery = function (tagsQuery) {
  74740. return Tags.MatchesQuery(obj, tagsQuery);
  74741. };
  74742. };
  74743. Tags.DisableFor = function (obj) {
  74744. delete obj._tags;
  74745. delete obj.hasTags;
  74746. delete obj.addTags;
  74747. delete obj.removeTags;
  74748. delete obj.matchesTagsQuery;
  74749. };
  74750. Tags.HasTags = function (obj) {
  74751. if (!obj._tags) {
  74752. return false;
  74753. }
  74754. return !BABYLON.Tools.IsEmpty(obj._tags);
  74755. };
  74756. Tags.GetTags = function (obj, asString) {
  74757. if (asString === void 0) { asString = true; }
  74758. if (!obj._tags) {
  74759. return null;
  74760. }
  74761. if (asString) {
  74762. var tagsArray = [];
  74763. for (var tag in obj._tags) {
  74764. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  74765. tagsArray.push(tag);
  74766. }
  74767. }
  74768. return tagsArray.join(" ");
  74769. }
  74770. else {
  74771. return obj._tags;
  74772. }
  74773. };
  74774. // the tags 'true' and 'false' are reserved and cannot be used as tags
  74775. // a tag cannot start with '||', '&&', and '!'
  74776. // it cannot contain whitespaces
  74777. Tags.AddTagsTo = function (obj, tagsString) {
  74778. if (!tagsString) {
  74779. return;
  74780. }
  74781. if (typeof tagsString !== "string") {
  74782. return;
  74783. }
  74784. var tags = tagsString.split(" ");
  74785. tags.forEach(function (tag, index, array) {
  74786. Tags._AddTagTo(obj, tag);
  74787. });
  74788. };
  74789. Tags._AddTagTo = function (obj, tag) {
  74790. tag = tag.trim();
  74791. if (tag === "" || tag === "true" || tag === "false") {
  74792. return;
  74793. }
  74794. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  74795. return;
  74796. }
  74797. Tags.EnableFor(obj);
  74798. obj._tags[tag] = true;
  74799. };
  74800. Tags.RemoveTagsFrom = function (obj, tagsString) {
  74801. if (!Tags.HasTags(obj)) {
  74802. return;
  74803. }
  74804. var tags = tagsString.split(" ");
  74805. for (var t in tags) {
  74806. Tags._RemoveTagFrom(obj, tags[t]);
  74807. }
  74808. };
  74809. Tags._RemoveTagFrom = function (obj, tag) {
  74810. delete obj._tags[tag];
  74811. };
  74812. Tags.MatchesQuery = function (obj, tagsQuery) {
  74813. if (tagsQuery === undefined) {
  74814. return true;
  74815. }
  74816. if (tagsQuery === "") {
  74817. return Tags.HasTags(obj);
  74818. }
  74819. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  74820. };
  74821. return Tags;
  74822. }());
  74823. BABYLON.Tags = Tags;
  74824. })(BABYLON || (BABYLON = {}));
  74825. //# sourceMappingURL=babylon.tags.js.map
  74826. var BABYLON;
  74827. (function (BABYLON) {
  74828. /**
  74829. * Class used to evalaute queries containing `and` and `or` operators
  74830. */
  74831. var AndOrNotEvaluator = /** @class */ (function () {
  74832. function AndOrNotEvaluator() {
  74833. }
  74834. /**
  74835. * Evaluate a query
  74836. * @param query defines the query to evaluate
  74837. * @param evaluateCallback defines the callback used to filter result
  74838. * @returns true if the query matches
  74839. */
  74840. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  74841. if (!query.match(/\([^\(\)]*\)/g)) {
  74842. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  74843. }
  74844. else {
  74845. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  74846. // remove parenthesis
  74847. r = r.slice(1, r.length - 1);
  74848. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  74849. });
  74850. }
  74851. if (query === "true") {
  74852. return true;
  74853. }
  74854. if (query === "false") {
  74855. return false;
  74856. }
  74857. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  74858. };
  74859. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  74860. evaluateCallback = evaluateCallback || (function (r) {
  74861. return r === "true" ? true : false;
  74862. });
  74863. var result;
  74864. var or = parenthesisContent.split("||");
  74865. for (var i in or) {
  74866. if (or.hasOwnProperty(i)) {
  74867. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  74868. var and = ori.split("&&");
  74869. if (and.length > 1) {
  74870. for (var j = 0; j < and.length; ++j) {
  74871. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  74872. if (andj !== "true" && andj !== "false") {
  74873. if (andj[0] === "!") {
  74874. result = !evaluateCallback(andj.substring(1));
  74875. }
  74876. else {
  74877. result = evaluateCallback(andj);
  74878. }
  74879. }
  74880. else {
  74881. result = andj === "true" ? true : false;
  74882. }
  74883. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  74884. ori = "false";
  74885. break;
  74886. }
  74887. }
  74888. }
  74889. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  74890. result = true;
  74891. break;
  74892. }
  74893. // result equals false (or undefined)
  74894. if (ori !== "true" && ori !== "false") {
  74895. if (ori[0] === "!") {
  74896. result = !evaluateCallback(ori.substring(1));
  74897. }
  74898. else {
  74899. result = evaluateCallback(ori);
  74900. }
  74901. }
  74902. else {
  74903. result = ori === "true" ? true : false;
  74904. }
  74905. }
  74906. }
  74907. // the whole parenthesis scope is replaced by 'true' or 'false'
  74908. return result ? "true" : "false";
  74909. };
  74910. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  74911. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  74912. // remove whitespaces
  74913. r = r.replace(/[\s]/g, function () { return ""; });
  74914. return r.length % 2 ? "!" : "";
  74915. });
  74916. booleanString = booleanString.trim();
  74917. if (booleanString === "!true") {
  74918. booleanString = "false";
  74919. }
  74920. else if (booleanString === "!false") {
  74921. booleanString = "true";
  74922. }
  74923. return booleanString;
  74924. };
  74925. return AndOrNotEvaluator;
  74926. }());
  74927. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  74928. })(BABYLON || (BABYLON = {}));
  74929. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  74930. var BABYLON;
  74931. (function (BABYLON) {
  74932. /**
  74933. * Class used to enable access to IndexedDB
  74934. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  74935. */
  74936. var Database = /** @class */ (function () {
  74937. /**
  74938. * Creates a new Database
  74939. * @param urlToScene defines the url to load the scene
  74940. * @param callbackManifestChecked defines the callback to use when manifest is checked
  74941. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  74942. */
  74943. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  74944. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  74945. var _this = this;
  74946. // Handling various flavors of prefixed version of IndexedDB
  74947. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  74948. this.callbackManifestChecked = callbackManifestChecked;
  74949. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  74950. this.db = null;
  74951. this._enableSceneOffline = false;
  74952. this._enableTexturesOffline = false;
  74953. this.manifestVersionFound = 0;
  74954. this.mustUpdateRessources = false;
  74955. this.hasReachedQuota = false;
  74956. if (!Database.IDBStorageEnabled) {
  74957. this.callbackManifestChecked(true);
  74958. }
  74959. else {
  74960. if (disableManifestCheck) {
  74961. this._enableSceneOffline = true;
  74962. this._enableTexturesOffline = true;
  74963. this.manifestVersionFound = 1;
  74964. BABYLON.Tools.SetImmediate(function () {
  74965. _this.callbackManifestChecked(true);
  74966. });
  74967. }
  74968. else {
  74969. this._checkManifestFile();
  74970. }
  74971. }
  74972. }
  74973. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  74974. /**
  74975. * Gets a boolean indicating if scene must be saved in the database
  74976. */
  74977. get: function () {
  74978. return this._enableSceneOffline;
  74979. },
  74980. enumerable: true,
  74981. configurable: true
  74982. });
  74983. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  74984. /**
  74985. * Gets a boolean indicating if textures must be saved in the database
  74986. */
  74987. get: function () {
  74988. return this._enableTexturesOffline;
  74989. },
  74990. enumerable: true,
  74991. configurable: true
  74992. });
  74993. Database.prototype._checkManifestFile = function () {
  74994. var _this = this;
  74995. var noManifestFile = function () {
  74996. _this._enableSceneOffline = false;
  74997. _this._enableTexturesOffline = false;
  74998. _this.callbackManifestChecked(false);
  74999. };
  75000. var timeStampUsed = false;
  75001. var manifestURL = this.currentSceneUrl + ".manifest";
  75002. var xhr = new XMLHttpRequest();
  75003. if (navigator.onLine) {
  75004. // Adding a timestamp to by-pass browsers' cache
  75005. timeStampUsed = true;
  75006. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75007. }
  75008. xhr.open("GET", manifestURL, true);
  75009. xhr.addEventListener("load", function () {
  75010. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75011. try {
  75012. var manifestFile = JSON.parse(xhr.response);
  75013. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75014. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75015. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75016. _this.manifestVersionFound = manifestFile.version;
  75017. }
  75018. if (_this.callbackManifestChecked) {
  75019. _this.callbackManifestChecked(true);
  75020. }
  75021. }
  75022. catch (ex) {
  75023. noManifestFile();
  75024. }
  75025. }
  75026. else {
  75027. noManifestFile();
  75028. }
  75029. }, false);
  75030. xhr.addEventListener("error", function (event) {
  75031. if (timeStampUsed) {
  75032. timeStampUsed = false;
  75033. // Let's retry without the timeStamp
  75034. // It could fail when coupled with HTML5 Offline API
  75035. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75036. xhr.open("GET", retryManifestURL, true);
  75037. xhr.send();
  75038. }
  75039. else {
  75040. noManifestFile();
  75041. }
  75042. }, false);
  75043. try {
  75044. xhr.send();
  75045. }
  75046. catch (ex) {
  75047. BABYLON.Tools.Error("Error on XHR send request.");
  75048. this.callbackManifestChecked(false);
  75049. }
  75050. };
  75051. /**
  75052. * Open the database and make it available
  75053. * @param successCallback defines the callback to call on success
  75054. * @param errorCallback defines the callback to call on error
  75055. */
  75056. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75057. var _this = this;
  75058. var handleError = function () {
  75059. _this.isSupported = false;
  75060. if (errorCallback)
  75061. errorCallback();
  75062. };
  75063. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75064. // Your browser doesn't support IndexedDB
  75065. this.isSupported = false;
  75066. if (errorCallback)
  75067. errorCallback();
  75068. }
  75069. else {
  75070. // If the DB hasn't been opened or created yet
  75071. if (!this.db) {
  75072. this.hasReachedQuota = false;
  75073. this.isSupported = true;
  75074. var request = this.idbFactory.open("babylonjs", 1);
  75075. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75076. request.onerror = function (event) {
  75077. handleError();
  75078. };
  75079. // executes when a version change transaction cannot complete due to other active transactions
  75080. request.onblocked = function (event) {
  75081. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75082. handleError();
  75083. };
  75084. // DB has been opened successfully
  75085. request.onsuccess = function (event) {
  75086. _this.db = request.result;
  75087. successCallback();
  75088. };
  75089. // Initialization of the DB. Creating Scenes & Textures stores
  75090. request.onupgradeneeded = function (event) {
  75091. _this.db = (event.target).result;
  75092. if (_this.db) {
  75093. try {
  75094. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75095. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75096. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75097. }
  75098. catch (ex) {
  75099. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75100. handleError();
  75101. }
  75102. }
  75103. };
  75104. }
  75105. // DB has already been created and opened
  75106. else {
  75107. if (successCallback)
  75108. successCallback();
  75109. }
  75110. }
  75111. };
  75112. /**
  75113. * Loads an image from the database
  75114. * @param url defines the url to load from
  75115. * @param image defines the target DOM image
  75116. */
  75117. Database.prototype.loadImageFromDB = function (url, image) {
  75118. var _this = this;
  75119. var completeURL = Database._ReturnFullUrlLocation(url);
  75120. var saveAndLoadImage = function () {
  75121. if (!_this.hasReachedQuota && _this.db !== null) {
  75122. // the texture is not yet in the DB, let's try to save it
  75123. _this._saveImageIntoDBAsync(completeURL, image);
  75124. }
  75125. // If the texture is not in the DB and we've reached the DB quota limit
  75126. // let's load it directly from the web
  75127. else {
  75128. image.src = url;
  75129. }
  75130. };
  75131. if (!this.mustUpdateRessources) {
  75132. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75133. }
  75134. // First time we're download the images or update requested in the manifest file by a version change
  75135. else {
  75136. saveAndLoadImage();
  75137. }
  75138. };
  75139. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75140. if (this.isSupported && this.db !== null) {
  75141. var texture;
  75142. var transaction = this.db.transaction(["textures"]);
  75143. transaction.onabort = function (event) {
  75144. image.src = url;
  75145. };
  75146. transaction.oncomplete = function (event) {
  75147. var blobTextureURL;
  75148. if (texture) {
  75149. var URL = window.URL || window.webkitURL;
  75150. blobTextureURL = URL.createObjectURL(texture.data);
  75151. image.onerror = function () {
  75152. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75153. image.src = url;
  75154. };
  75155. image.src = blobTextureURL;
  75156. }
  75157. else {
  75158. notInDBCallback();
  75159. }
  75160. };
  75161. var getRequest = transaction.objectStore("textures").get(url);
  75162. getRequest.onsuccess = function (event) {
  75163. texture = (event.target).result;
  75164. };
  75165. getRequest.onerror = function (event) {
  75166. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75167. image.src = url;
  75168. };
  75169. }
  75170. else {
  75171. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75172. image.src = url;
  75173. }
  75174. };
  75175. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75176. var _this = this;
  75177. if (this.isSupported) {
  75178. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75179. var generateBlobUrl = function () {
  75180. var blobTextureURL;
  75181. if (blob) {
  75182. var URL = window.URL || window.webkitURL;
  75183. try {
  75184. blobTextureURL = URL.createObjectURL(blob);
  75185. }
  75186. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75187. catch (ex) {
  75188. blobTextureURL = URL.createObjectURL(blob);
  75189. }
  75190. }
  75191. if (blobTextureURL) {
  75192. image.src = blobTextureURL;
  75193. }
  75194. };
  75195. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75196. var xhr = new XMLHttpRequest(), blob;
  75197. xhr.open("GET", url, true);
  75198. xhr.responseType = "blob";
  75199. xhr.addEventListener("load", function () {
  75200. if (xhr.status === 200 && _this.db) {
  75201. // Blob as response (XHR2)
  75202. blob = xhr.response;
  75203. var transaction = _this.db.transaction(["textures"], "readwrite");
  75204. // the transaction could abort because of a QuotaExceededError error
  75205. transaction.onabort = function (event) {
  75206. try {
  75207. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75208. var srcElement = (event.srcElement || event.target);
  75209. var error = srcElement.error;
  75210. if (error && error.name === "QuotaExceededError") {
  75211. _this.hasReachedQuota = true;
  75212. }
  75213. }
  75214. catch (ex) { }
  75215. generateBlobUrl();
  75216. };
  75217. transaction.oncomplete = function (event) {
  75218. generateBlobUrl();
  75219. };
  75220. var newTexture = { textureUrl: url, data: blob };
  75221. try {
  75222. // Put the blob into the dabase
  75223. var addRequest = transaction.objectStore("textures").put(newTexture);
  75224. addRequest.onsuccess = function (event) {
  75225. };
  75226. addRequest.onerror = function (event) {
  75227. generateBlobUrl();
  75228. };
  75229. }
  75230. catch (ex) {
  75231. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75232. if (ex.code === 25) {
  75233. Database.IsUASupportingBlobStorage = false;
  75234. }
  75235. image.src = url;
  75236. }
  75237. }
  75238. else {
  75239. image.src = url;
  75240. }
  75241. }, false);
  75242. xhr.addEventListener("error", function (event) {
  75243. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75244. image.src = url;
  75245. }, false);
  75246. xhr.send();
  75247. }
  75248. else {
  75249. image.src = url;
  75250. }
  75251. }
  75252. else {
  75253. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75254. image.src = url;
  75255. }
  75256. };
  75257. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75258. var _this = this;
  75259. var updateVersion = function () {
  75260. // the version is not yet in the DB or we need to update it
  75261. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75262. };
  75263. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75264. };
  75265. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75266. var _this = this;
  75267. if (this.isSupported && this.db) {
  75268. var version;
  75269. try {
  75270. var transaction = this.db.transaction(["versions"]);
  75271. transaction.oncomplete = function (event) {
  75272. if (version) {
  75273. // If the version in the JSON file is different from the version in DB
  75274. if (_this.manifestVersionFound !== version.data) {
  75275. _this.mustUpdateRessources = true;
  75276. updateInDBCallback();
  75277. }
  75278. else {
  75279. callback(version.data);
  75280. }
  75281. }
  75282. // version was not found in DB
  75283. else {
  75284. _this.mustUpdateRessources = true;
  75285. updateInDBCallback();
  75286. }
  75287. };
  75288. transaction.onabort = function (event) {
  75289. callback(-1);
  75290. };
  75291. var getRequest = transaction.objectStore("versions").get(url);
  75292. getRequest.onsuccess = function (event) {
  75293. version = (event.target).result;
  75294. };
  75295. getRequest.onerror = function (event) {
  75296. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75297. callback(-1);
  75298. };
  75299. }
  75300. catch (ex) {
  75301. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75302. callback(-1);
  75303. }
  75304. }
  75305. else {
  75306. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75307. callback(-1);
  75308. }
  75309. };
  75310. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75311. var _this = this;
  75312. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75313. try {
  75314. // Open a transaction to the database
  75315. var transaction = this.db.transaction(["versions"], "readwrite");
  75316. // the transaction could abort because of a QuotaExceededError error
  75317. transaction.onabort = function (event) {
  75318. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75319. var error = event.srcElement['error'];
  75320. if (error && error.name === "QuotaExceededError") {
  75321. _this.hasReachedQuota = true;
  75322. }
  75323. }
  75324. catch (ex) { }
  75325. callback(-1);
  75326. };
  75327. transaction.oncomplete = function (event) {
  75328. callback(_this.manifestVersionFound);
  75329. };
  75330. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75331. // Put the scene into the database
  75332. var addRequest = transaction.objectStore("versions").put(newVersion);
  75333. addRequest.onsuccess = function (event) {
  75334. };
  75335. addRequest.onerror = function (event) {
  75336. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75337. };
  75338. }
  75339. catch (ex) {
  75340. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75341. callback(-1);
  75342. }
  75343. }
  75344. else {
  75345. callback(-1);
  75346. }
  75347. };
  75348. /**
  75349. * Loads a file from database
  75350. * @param url defines the URL to load from
  75351. * @param sceneLoaded defines a callback to call on success
  75352. * @param progressCallBack defines a callback to call when progress changed
  75353. * @param errorCallback defines a callback to call on error
  75354. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75355. */
  75356. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75357. var _this = this;
  75358. var completeUrl = Database._ReturnFullUrlLocation(url);
  75359. var saveAndLoadFile = function () {
  75360. // the scene is not yet in the DB, let's try to save it
  75361. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75362. };
  75363. this._checkVersionFromDB(completeUrl, function (version) {
  75364. if (version !== -1) {
  75365. if (!_this.mustUpdateRessources) {
  75366. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75367. }
  75368. else {
  75369. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75370. }
  75371. }
  75372. else {
  75373. if (errorCallback) {
  75374. errorCallback();
  75375. }
  75376. }
  75377. });
  75378. };
  75379. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75380. if (this.isSupported && this.db) {
  75381. var targetStore;
  75382. if (url.indexOf(".babylon") !== -1) {
  75383. targetStore = "scenes";
  75384. }
  75385. else {
  75386. targetStore = "textures";
  75387. }
  75388. var file;
  75389. var transaction = this.db.transaction([targetStore]);
  75390. transaction.oncomplete = function (event) {
  75391. if (file) {
  75392. callback(file.data);
  75393. }
  75394. // file was not found in DB
  75395. else {
  75396. notInDBCallback();
  75397. }
  75398. };
  75399. transaction.onabort = function (event) {
  75400. notInDBCallback();
  75401. };
  75402. var getRequest = transaction.objectStore(targetStore).get(url);
  75403. getRequest.onsuccess = function (event) {
  75404. file = (event.target).result;
  75405. };
  75406. getRequest.onerror = function (event) {
  75407. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75408. notInDBCallback();
  75409. };
  75410. }
  75411. else {
  75412. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75413. callback();
  75414. }
  75415. };
  75416. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75417. var _this = this;
  75418. if (this.isSupported) {
  75419. var targetStore;
  75420. if (url.indexOf(".babylon") !== -1) {
  75421. targetStore = "scenes";
  75422. }
  75423. else {
  75424. targetStore = "textures";
  75425. }
  75426. // Create XHR
  75427. var xhr = new XMLHttpRequest();
  75428. var fileData;
  75429. xhr.open("GET", url + "?" + Date.now(), true);
  75430. if (useArrayBuffer) {
  75431. xhr.responseType = "arraybuffer";
  75432. }
  75433. if (progressCallback) {
  75434. xhr.onprogress = progressCallback;
  75435. }
  75436. xhr.addEventListener("load", function () {
  75437. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75438. // Blob as response (XHR2)
  75439. //fileData = xhr.responseText;
  75440. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75441. if (!_this.hasReachedQuota && _this.db) {
  75442. // Open a transaction to the database
  75443. var transaction = _this.db.transaction([targetStore], "readwrite");
  75444. // the transaction could abort because of a QuotaExceededError error
  75445. transaction.onabort = function (event) {
  75446. try {
  75447. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75448. var error = event.srcElement['error'];
  75449. if (error && error.name === "QuotaExceededError") {
  75450. _this.hasReachedQuota = true;
  75451. }
  75452. }
  75453. catch (ex) { }
  75454. callback(fileData);
  75455. };
  75456. transaction.oncomplete = function (event) {
  75457. callback(fileData);
  75458. };
  75459. var newFile;
  75460. if (targetStore === "scenes") {
  75461. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75462. }
  75463. else {
  75464. newFile = { textureUrl: url, data: fileData };
  75465. }
  75466. try {
  75467. // Put the scene into the database
  75468. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75469. addRequest.onsuccess = function (event) {
  75470. };
  75471. addRequest.onerror = function (event) {
  75472. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75473. };
  75474. }
  75475. catch (ex) {
  75476. callback(fileData);
  75477. }
  75478. }
  75479. else {
  75480. callback(fileData);
  75481. }
  75482. }
  75483. else {
  75484. if (xhr.status >= 400 && errorCallback) {
  75485. errorCallback(xhr);
  75486. }
  75487. else {
  75488. callback();
  75489. }
  75490. }
  75491. }, false);
  75492. xhr.addEventListener("error", function (event) {
  75493. BABYLON.Tools.Error("error on XHR request.");
  75494. callback();
  75495. }, false);
  75496. xhr.send();
  75497. }
  75498. else {
  75499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75500. callback();
  75501. }
  75502. };
  75503. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75504. Database.IsUASupportingBlobStorage = true;
  75505. /** Gets a boolean indicating if Database storate is enabled */
  75506. Database.IDBStorageEnabled = true;
  75507. Database._ParseURL = function (url) {
  75508. var a = document.createElement('a');
  75509. a.href = url;
  75510. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  75511. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  75512. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  75513. return absLocation;
  75514. };
  75515. Database._ReturnFullUrlLocation = function (url) {
  75516. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  75517. return (Database._ParseURL(window.location.href) + url);
  75518. }
  75519. else {
  75520. return url;
  75521. }
  75522. };
  75523. return Database;
  75524. }());
  75525. BABYLON.Database = Database;
  75526. })(BABYLON || (BABYLON = {}));
  75527. //# sourceMappingURL=babylon.database.js.map
  75528. var BABYLON;
  75529. (function (BABYLON) {
  75530. var FresnelParameters = /** @class */ (function () {
  75531. function FresnelParameters() {
  75532. this._isEnabled = true;
  75533. this.leftColor = BABYLON.Color3.White();
  75534. this.rightColor = BABYLON.Color3.Black();
  75535. this.bias = 0;
  75536. this.power = 1;
  75537. }
  75538. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  75539. get: function () {
  75540. return this._isEnabled;
  75541. },
  75542. set: function (value) {
  75543. if (this._isEnabled === value) {
  75544. return;
  75545. }
  75546. this._isEnabled = value;
  75547. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  75548. },
  75549. enumerable: true,
  75550. configurable: true
  75551. });
  75552. FresnelParameters.prototype.clone = function () {
  75553. var newFresnelParameters = new FresnelParameters();
  75554. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  75555. return newFresnelParameters;
  75556. };
  75557. FresnelParameters.prototype.serialize = function () {
  75558. var serializationObject = {};
  75559. serializationObject.isEnabled = this.isEnabled;
  75560. serializationObject.leftColor = this.leftColor.asArray();
  75561. serializationObject.rightColor = this.rightColor.asArray();
  75562. serializationObject.bias = this.bias;
  75563. serializationObject.power = this.power;
  75564. return serializationObject;
  75565. };
  75566. FresnelParameters.Parse = function (parsedFresnelParameters) {
  75567. var fresnelParameters = new FresnelParameters();
  75568. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  75569. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  75570. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  75571. fresnelParameters.bias = parsedFresnelParameters.bias;
  75572. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  75573. return fresnelParameters;
  75574. };
  75575. return FresnelParameters;
  75576. }());
  75577. BABYLON.FresnelParameters = FresnelParameters;
  75578. })(BABYLON || (BABYLON = {}));
  75579. //# sourceMappingURL=babylon.fresnelParameters.js.map
  75580. var BABYLON;
  75581. (function (BABYLON) {
  75582. var MultiMaterial = /** @class */ (function (_super) {
  75583. __extends(MultiMaterial, _super);
  75584. function MultiMaterial(name, scene) {
  75585. var _this = _super.call(this, name, scene, true) || this;
  75586. scene.multiMaterials.push(_this);
  75587. _this.subMaterials = new Array();
  75588. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  75589. return _this;
  75590. }
  75591. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  75592. get: function () {
  75593. return this._subMaterials;
  75594. },
  75595. set: function (value) {
  75596. this._subMaterials = value;
  75597. this._hookArray(value);
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. MultiMaterial.prototype._hookArray = function (array) {
  75603. var _this = this;
  75604. var oldPush = array.push;
  75605. array.push = function () {
  75606. var items = [];
  75607. for (var _i = 0; _i < arguments.length; _i++) {
  75608. items[_i] = arguments[_i];
  75609. }
  75610. var result = oldPush.apply(array, items);
  75611. _this._markAllSubMeshesAsTexturesDirty();
  75612. return result;
  75613. };
  75614. var oldSplice = array.splice;
  75615. array.splice = function (index, deleteCount) {
  75616. var deleted = oldSplice.apply(array, [index, deleteCount]);
  75617. _this._markAllSubMeshesAsTexturesDirty();
  75618. return deleted;
  75619. };
  75620. };
  75621. // Properties
  75622. MultiMaterial.prototype.getSubMaterial = function (index) {
  75623. if (index < 0 || index >= this.subMaterials.length) {
  75624. return this.getScene().defaultMaterial;
  75625. }
  75626. return this.subMaterials[index];
  75627. };
  75628. MultiMaterial.prototype.getActiveTextures = function () {
  75629. var _a;
  75630. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  75631. if (subMaterial) {
  75632. return subMaterial.getActiveTextures();
  75633. }
  75634. else {
  75635. return [];
  75636. }
  75637. }));
  75638. };
  75639. // Methods
  75640. MultiMaterial.prototype.getClassName = function () {
  75641. return "MultiMaterial";
  75642. };
  75643. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75644. for (var index = 0; index < this.subMaterials.length; index++) {
  75645. var subMaterial = this.subMaterials[index];
  75646. if (subMaterial) {
  75647. if (subMaterial.storeEffectOnSubMeshes) {
  75648. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  75649. return false;
  75650. }
  75651. continue;
  75652. }
  75653. if (!subMaterial.isReady(mesh)) {
  75654. return false;
  75655. }
  75656. }
  75657. }
  75658. return true;
  75659. };
  75660. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  75661. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  75662. for (var index = 0; index < this.subMaterials.length; index++) {
  75663. var subMaterial = null;
  75664. var current = this.subMaterials[index];
  75665. if (cloneChildren && current) {
  75666. subMaterial = current.clone(name + "-" + current.name);
  75667. }
  75668. else {
  75669. subMaterial = this.subMaterials[index];
  75670. }
  75671. newMultiMaterial.subMaterials.push(subMaterial);
  75672. }
  75673. return newMultiMaterial;
  75674. };
  75675. MultiMaterial.prototype.serialize = function () {
  75676. var serializationObject = {};
  75677. serializationObject.name = this.name;
  75678. serializationObject.id = this.id;
  75679. if (BABYLON.Tags) {
  75680. serializationObject.tags = BABYLON.Tags.GetTags(this);
  75681. }
  75682. serializationObject.materials = [];
  75683. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  75684. var subMat = this.subMaterials[matIndex];
  75685. if (subMat) {
  75686. serializationObject.materials.push(subMat.id);
  75687. }
  75688. else {
  75689. serializationObject.materials.push(null);
  75690. }
  75691. }
  75692. return serializationObject;
  75693. };
  75694. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75695. var scene = this.getScene();
  75696. if (!scene) {
  75697. return;
  75698. }
  75699. var index = scene.multiMaterials.indexOf(this);
  75700. if (index >= 0) {
  75701. scene.multiMaterials.splice(index, 1);
  75702. }
  75703. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  75704. };
  75705. return MultiMaterial;
  75706. }(BABYLON.Material));
  75707. BABYLON.MultiMaterial = MultiMaterial;
  75708. })(BABYLON || (BABYLON = {}));
  75709. //# sourceMappingURL=babylon.multiMaterial.js.map
  75710. var BABYLON;
  75711. (function (BABYLON) {
  75712. /**
  75713. * Manage the touch inputs to control the movement of a free camera.
  75714. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  75715. */
  75716. var FreeCameraTouchInput = /** @class */ (function () {
  75717. function FreeCameraTouchInput() {
  75718. /**
  75719. * Defines the touch sensibility for rotation.
  75720. * The higher the faster.
  75721. */
  75722. this.touchAngularSensibility = 200000.0;
  75723. /**
  75724. * Defines the touch sensibility for move.
  75725. * The higher the faster.
  75726. */
  75727. this.touchMoveSensibility = 250.0;
  75728. this._offsetX = null;
  75729. this._offsetY = null;
  75730. this._pointerPressed = new Array();
  75731. }
  75732. /**
  75733. * Attach the input controls to a specific dom element to get the input from.
  75734. * @param element Defines the element the controls should be listened from
  75735. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  75736. */
  75737. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  75738. var _this = this;
  75739. var previousPosition = null;
  75740. if (this._pointerInput === undefined) {
  75741. this._onLostFocus = function (evt) {
  75742. _this._offsetX = null;
  75743. _this._offsetY = null;
  75744. };
  75745. this._pointerInput = function (p, s) {
  75746. var evt = p.event;
  75747. if (evt.pointerType === "mouse") {
  75748. return;
  75749. }
  75750. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75751. if (!noPreventDefault) {
  75752. evt.preventDefault();
  75753. }
  75754. _this._pointerPressed.push(evt.pointerId);
  75755. if (_this._pointerPressed.length !== 1) {
  75756. return;
  75757. }
  75758. previousPosition = {
  75759. x: evt.clientX,
  75760. y: evt.clientY
  75761. };
  75762. }
  75763. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  75764. if (!noPreventDefault) {
  75765. evt.preventDefault();
  75766. }
  75767. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75768. if (index === -1) {
  75769. return;
  75770. }
  75771. _this._pointerPressed.splice(index, 1);
  75772. if (index != 0) {
  75773. return;
  75774. }
  75775. previousPosition = null;
  75776. _this._offsetX = null;
  75777. _this._offsetY = null;
  75778. }
  75779. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  75780. if (!noPreventDefault) {
  75781. evt.preventDefault();
  75782. }
  75783. if (!previousPosition) {
  75784. return;
  75785. }
  75786. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75787. if (index != 0) {
  75788. return;
  75789. }
  75790. _this._offsetX = evt.clientX - previousPosition.x;
  75791. _this._offsetY = -(evt.clientY - previousPosition.y);
  75792. }
  75793. };
  75794. }
  75795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  75796. if (this._onLostFocus) {
  75797. element.addEventListener("blur", this._onLostFocus);
  75798. }
  75799. };
  75800. /**
  75801. * Detach the current controls from the specified dom element.
  75802. * @param element Defines the element to stop listening the inputs from
  75803. */
  75804. FreeCameraTouchInput.prototype.detachControl = function (element) {
  75805. if (this._pointerInput && element) {
  75806. if (this._observer) {
  75807. this.camera.getScene().onPointerObservable.remove(this._observer);
  75808. this._observer = null;
  75809. }
  75810. if (this._onLostFocus) {
  75811. element.removeEventListener("blur", this._onLostFocus);
  75812. this._onLostFocus = null;
  75813. }
  75814. this._pointerPressed = [];
  75815. this._offsetX = null;
  75816. this._offsetY = null;
  75817. }
  75818. };
  75819. /**
  75820. * Update the current camera state depending on the inputs that have been used this frame.
  75821. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  75822. */
  75823. FreeCameraTouchInput.prototype.checkInputs = function () {
  75824. if (this._offsetX && this._offsetY) {
  75825. var camera = this.camera;
  75826. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  75827. if (this._pointerPressed.length > 1) {
  75828. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  75829. }
  75830. else {
  75831. var speed = camera._computeLocalCameraSpeed();
  75832. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  75833. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  75834. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  75835. }
  75836. }
  75837. };
  75838. /**
  75839. * Gets the class name of the current intput.
  75840. * @returns the class name
  75841. */
  75842. FreeCameraTouchInput.prototype.getClassName = function () {
  75843. return "FreeCameraTouchInput";
  75844. };
  75845. /**
  75846. * Get the friendly name associated with the input class.
  75847. * @returns the input friendly name
  75848. */
  75849. FreeCameraTouchInput.prototype.getSimpleName = function () {
  75850. return "touch";
  75851. };
  75852. __decorate([
  75853. BABYLON.serialize()
  75854. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  75855. __decorate([
  75856. BABYLON.serialize()
  75857. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  75858. return FreeCameraTouchInput;
  75859. }());
  75860. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  75861. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  75862. })(BABYLON || (BABYLON = {}));
  75863. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  75864. var BABYLON;
  75865. (function (BABYLON) {
  75866. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  75867. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  75868. });
  75869. /**
  75870. * This represents a FPS type of camera controlled by touch.
  75871. * This is like a universal camera minus the Gamepad controls.
  75872. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75873. */
  75874. var TouchCamera = /** @class */ (function (_super) {
  75875. __extends(TouchCamera, _super);
  75876. /**
  75877. * Instantiates a new touch camera.
  75878. * This represents a FPS type of camera controlled by touch.
  75879. * This is like a universal camera minus the Gamepad controls.
  75880. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75881. * @param name Define the name of the camera in the scene
  75882. * @param position Define the start position of the camera in the scene
  75883. * @param scene Define the scene the camera belongs to
  75884. */
  75885. function TouchCamera(name, position, scene) {
  75886. var _this = _super.call(this, name, position, scene) || this;
  75887. _this.inputs.addTouch();
  75888. _this._setupInputs();
  75889. return _this;
  75890. }
  75891. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  75892. /**
  75893. * Defines the touch sensibility for rotation.
  75894. * The higher the faster.
  75895. */
  75896. get: function () {
  75897. var touch = this.inputs.attached["touch"];
  75898. if (touch)
  75899. return touch.touchAngularSensibility;
  75900. return 0;
  75901. },
  75902. set: function (value) {
  75903. var touch = this.inputs.attached["touch"];
  75904. if (touch)
  75905. touch.touchAngularSensibility = value;
  75906. },
  75907. enumerable: true,
  75908. configurable: true
  75909. });
  75910. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  75911. /**
  75912. * Defines the touch sensibility for move.
  75913. * The higher the faster.
  75914. */
  75915. get: function () {
  75916. var touch = this.inputs.attached["touch"];
  75917. if (touch)
  75918. return touch.touchMoveSensibility;
  75919. return 0;
  75920. },
  75921. set: function (value) {
  75922. var touch = this.inputs.attached["touch"];
  75923. if (touch)
  75924. touch.touchMoveSensibility = value;
  75925. },
  75926. enumerable: true,
  75927. configurable: true
  75928. });
  75929. /**
  75930. * Gets the current object class name.
  75931. * @return the class name
  75932. */
  75933. TouchCamera.prototype.getClassName = function () {
  75934. return "TouchCamera";
  75935. };
  75936. /** @hidden */
  75937. TouchCamera.prototype._setupInputs = function () {
  75938. var mouse = this.inputs.attached["mouse"];
  75939. if (mouse) {
  75940. mouse.touchEnabled = false;
  75941. }
  75942. };
  75943. return TouchCamera;
  75944. }(BABYLON.FreeCamera));
  75945. BABYLON.TouchCamera = TouchCamera;
  75946. })(BABYLON || (BABYLON = {}));
  75947. //# sourceMappingURL=babylon.touchCamera.js.map
  75948. var BABYLON;
  75949. (function (BABYLON) {
  75950. var ProceduralTexture = /** @class */ (function (_super) {
  75951. __extends(ProceduralTexture, _super);
  75952. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  75953. if (fallbackTexture === void 0) { fallbackTexture = null; }
  75954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75955. if (isCube === void 0) { isCube = false; }
  75956. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  75957. _this.isCube = isCube;
  75958. _this.isEnabled = true;
  75959. _this._currentRefreshId = -1;
  75960. _this._refreshRate = 1;
  75961. /**
  75962. * Event raised when the texture is generated
  75963. */
  75964. _this.onGeneratedObservable = new BABYLON.Observable();
  75965. _this._vertexBuffers = {};
  75966. _this._uniforms = new Array();
  75967. _this._samplers = new Array();
  75968. /** @hidden */
  75969. _this._textures = {};
  75970. _this._floats = {};
  75971. _this._ints = {};
  75972. _this._floatsArrays = {};
  75973. _this._colors3 = {};
  75974. _this._colors4 = {};
  75975. _this._vectors2 = {};
  75976. _this._vectors3 = {};
  75977. _this._matrices = {};
  75978. _this._fallbackTextureUsed = false;
  75979. _this._cachedDefines = "";
  75980. _this._contentUpdateId = -1;
  75981. scene = _this.getScene();
  75982. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  75983. if (!component) {
  75984. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  75985. scene._addComponent(component);
  75986. }
  75987. scene.proceduralTextures.push(_this);
  75988. _this._engine = scene.getEngine();
  75989. _this.name = name;
  75990. _this.isRenderTarget = true;
  75991. _this._size = size;
  75992. _this._generateMipMaps = generateMipMaps;
  75993. _this.setFragment(fragment);
  75994. _this._fallbackTexture = fallbackTexture;
  75995. if (isCube) {
  75996. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  75997. _this.setFloat("face", 0);
  75998. }
  75999. else {
  76000. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76001. }
  76002. // VBO
  76003. var vertices = [];
  76004. vertices.push(1, 1);
  76005. vertices.push(-1, 1);
  76006. vertices.push(-1, -1);
  76007. vertices.push(1, -1);
  76008. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76009. _this._createIndexBuffer();
  76010. return _this;
  76011. }
  76012. /**
  76013. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76014. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76015. */
  76016. ProceduralTexture.prototype.getContent = function () {
  76017. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76018. return this._contentData;
  76019. }
  76020. this._contentData = this.readPixels(0, 0, this._contentData);
  76021. this._contentUpdateId = this._currentRefreshId;
  76022. return this._contentData;
  76023. };
  76024. ProceduralTexture.prototype._createIndexBuffer = function () {
  76025. var engine = this._engine;
  76026. // Indices
  76027. var indices = [];
  76028. indices.push(0);
  76029. indices.push(1);
  76030. indices.push(2);
  76031. indices.push(0);
  76032. indices.push(2);
  76033. indices.push(3);
  76034. this._indexBuffer = engine.createIndexBuffer(indices);
  76035. };
  76036. /** @hidden */
  76037. ProceduralTexture.prototype._rebuild = function () {
  76038. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76039. if (vb) {
  76040. vb._rebuild();
  76041. }
  76042. this._createIndexBuffer();
  76043. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76044. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76045. }
  76046. };
  76047. ProceduralTexture.prototype.reset = function () {
  76048. if (this._effect === undefined) {
  76049. return;
  76050. }
  76051. var engine = this._engine;
  76052. engine._releaseEffect(this._effect);
  76053. };
  76054. ProceduralTexture.prototype._getDefines = function () {
  76055. return "";
  76056. };
  76057. ProceduralTexture.prototype.isReady = function () {
  76058. var _this = this;
  76059. var engine = this._engine;
  76060. var shaders;
  76061. if (!this._fragment) {
  76062. return false;
  76063. }
  76064. if (this._fallbackTextureUsed) {
  76065. return true;
  76066. }
  76067. var defines = this._getDefines();
  76068. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76069. return true;
  76070. }
  76071. if (this._fragment.fragmentElement !== undefined) {
  76072. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76073. }
  76074. else {
  76075. shaders = { vertex: "procedural", fragment: this._fragment };
  76076. }
  76077. this._cachedDefines = defines;
  76078. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76079. _this.releaseInternalTexture();
  76080. if (_this._fallbackTexture) {
  76081. _this._texture = _this._fallbackTexture._texture;
  76082. if (_this._texture) {
  76083. _this._texture.incrementReferences();
  76084. }
  76085. }
  76086. _this._fallbackTextureUsed = true;
  76087. });
  76088. return this._effect.isReady();
  76089. };
  76090. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76091. this._currentRefreshId = -1;
  76092. };
  76093. ProceduralTexture.prototype.setFragment = function (fragment) {
  76094. this._fragment = fragment;
  76095. };
  76096. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76097. get: function () {
  76098. return this._refreshRate;
  76099. },
  76100. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76101. set: function (value) {
  76102. this._refreshRate = value;
  76103. this.resetRefreshCounter();
  76104. },
  76105. enumerable: true,
  76106. configurable: true
  76107. });
  76108. /** @hidden */
  76109. ProceduralTexture.prototype._shouldRender = function () {
  76110. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76111. if (this._texture) {
  76112. this._texture.isReady = false;
  76113. }
  76114. return false;
  76115. }
  76116. if (this._fallbackTextureUsed) {
  76117. return false;
  76118. }
  76119. if (this._currentRefreshId === -1) { // At least render once
  76120. this._currentRefreshId = 1;
  76121. return true;
  76122. }
  76123. if (this.refreshRate === this._currentRefreshId) {
  76124. this._currentRefreshId = 1;
  76125. return true;
  76126. }
  76127. this._currentRefreshId++;
  76128. return false;
  76129. };
  76130. ProceduralTexture.prototype.getRenderSize = function () {
  76131. return this._size;
  76132. };
  76133. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76134. if (this._fallbackTextureUsed) {
  76135. return;
  76136. }
  76137. this.releaseInternalTexture();
  76138. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76139. // Update properties
  76140. this._size = size;
  76141. this._generateMipMaps = generateMipMaps;
  76142. };
  76143. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76144. if (this._uniforms.indexOf(uniformName) === -1) {
  76145. this._uniforms.push(uniformName);
  76146. }
  76147. };
  76148. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76149. if (this._samplers.indexOf(name) === -1) {
  76150. this._samplers.push(name);
  76151. }
  76152. this._textures[name] = texture;
  76153. return this;
  76154. };
  76155. ProceduralTexture.prototype.setFloat = function (name, value) {
  76156. this._checkUniform(name);
  76157. this._floats[name] = value;
  76158. return this;
  76159. };
  76160. /**
  76161. * Set the value of an uniform to an integer value
  76162. * @param name defines the name of the uniform
  76163. * @param value defines the value to set
  76164. * @returns the current procedural texture
  76165. */
  76166. ProceduralTexture.prototype.setInt = function (name, value) {
  76167. this._checkUniform(name);
  76168. this._ints[name] = value;
  76169. return this;
  76170. };
  76171. ProceduralTexture.prototype.setFloats = function (name, value) {
  76172. this._checkUniform(name);
  76173. this._floatsArrays[name] = value;
  76174. return this;
  76175. };
  76176. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76177. this._checkUniform(name);
  76178. this._colors3[name] = value;
  76179. return this;
  76180. };
  76181. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76182. this._checkUniform(name);
  76183. this._colors4[name] = value;
  76184. return this;
  76185. };
  76186. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76187. this._checkUniform(name);
  76188. this._vectors2[name] = value;
  76189. return this;
  76190. };
  76191. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76192. this._checkUniform(name);
  76193. this._vectors3[name] = value;
  76194. return this;
  76195. };
  76196. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76197. this._checkUniform(name);
  76198. this._matrices[name] = value;
  76199. return this;
  76200. };
  76201. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76202. var scene = this.getScene();
  76203. if (!scene) {
  76204. return;
  76205. }
  76206. var engine = this._engine;
  76207. // Render
  76208. engine.enableEffect(this._effect);
  76209. engine.setState(false);
  76210. // Texture
  76211. for (var name in this._textures) {
  76212. this._effect.setTexture(name, this._textures[name]);
  76213. }
  76214. // Float
  76215. for (name in this._ints) {
  76216. this._effect.setInt(name, this._ints[name]);
  76217. }
  76218. // Float
  76219. for (name in this._floats) {
  76220. this._effect.setFloat(name, this._floats[name]);
  76221. }
  76222. // Floats
  76223. for (name in this._floatsArrays) {
  76224. this._effect.setArray(name, this._floatsArrays[name]);
  76225. }
  76226. // Color3
  76227. for (name in this._colors3) {
  76228. this._effect.setColor3(name, this._colors3[name]);
  76229. }
  76230. // Color4
  76231. for (name in this._colors4) {
  76232. var color = this._colors4[name];
  76233. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76234. }
  76235. // Vector2
  76236. for (name in this._vectors2) {
  76237. this._effect.setVector2(name, this._vectors2[name]);
  76238. }
  76239. // Vector3
  76240. for (name in this._vectors3) {
  76241. this._effect.setVector3(name, this._vectors3[name]);
  76242. }
  76243. // Matrix
  76244. for (name in this._matrices) {
  76245. this._effect.setMatrix(name, this._matrices[name]);
  76246. }
  76247. if (!this._texture) {
  76248. return;
  76249. }
  76250. if (this.isCube) {
  76251. for (var face = 0; face < 6; face++) {
  76252. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76253. // VBOs
  76254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76255. this._effect.setFloat("face", face);
  76256. // Clear
  76257. engine.clear(scene.clearColor, true, true, true);
  76258. // Draw order
  76259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76260. // Mipmaps
  76261. if (face === 5) {
  76262. engine.generateMipMapsForCubemap(this._texture);
  76263. }
  76264. }
  76265. }
  76266. else {
  76267. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76268. // VBOs
  76269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76270. // Clear
  76271. engine.clear(scene.clearColor, true, true, true);
  76272. // Draw order
  76273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76274. }
  76275. // Unbind
  76276. engine.unBindFramebuffer(this._texture, this.isCube);
  76277. if (this.onGenerated) {
  76278. this.onGenerated();
  76279. }
  76280. this.onGeneratedObservable.notifyObservers(this);
  76281. };
  76282. ProceduralTexture.prototype.clone = function () {
  76283. var textureSize = this.getSize();
  76284. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76285. // Base texture
  76286. newTexture.hasAlpha = this.hasAlpha;
  76287. newTexture.level = this.level;
  76288. // RenderTarget Texture
  76289. newTexture.coordinatesMode = this.coordinatesMode;
  76290. return newTexture;
  76291. };
  76292. ProceduralTexture.prototype.dispose = function () {
  76293. var scene = this.getScene();
  76294. if (!scene) {
  76295. return;
  76296. }
  76297. var index = scene.proceduralTextures.indexOf(this);
  76298. if (index >= 0) {
  76299. scene.proceduralTextures.splice(index, 1);
  76300. }
  76301. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76302. if (vertexBuffer) {
  76303. vertexBuffer.dispose();
  76304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76305. }
  76306. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76307. this._indexBuffer = null;
  76308. }
  76309. _super.prototype.dispose.call(this);
  76310. };
  76311. __decorate([
  76312. BABYLON.serialize()
  76313. ], ProceduralTexture.prototype, "_size", void 0);
  76314. __decorate([
  76315. BABYLON.serialize()
  76316. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76317. __decorate([
  76318. BABYLON.serialize()
  76319. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76320. __decorate([
  76321. BABYLON.serialize()
  76322. ], ProceduralTexture.prototype, "refreshRate", null);
  76323. return ProceduralTexture;
  76324. }(BABYLON.Texture));
  76325. BABYLON.ProceduralTexture = ProceduralTexture;
  76326. })(BABYLON || (BABYLON = {}));
  76327. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76328. var BABYLON;
  76329. (function (BABYLON) {
  76330. /**
  76331. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76332. * in a given scene.
  76333. */
  76334. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76335. /**
  76336. * Creates a new instance of the component for the given scene
  76337. * @param scene Defines the scene to register the component in
  76338. */
  76339. function ProceduralTextureSceneComponent(scene) {
  76340. /**
  76341. * The component name helpfull to identify the component in the list of scene components.
  76342. */
  76343. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76344. this.scene = scene;
  76345. this.scene.proceduralTextures = new Array();
  76346. scene.layers = new Array();
  76347. }
  76348. /**
  76349. * Registers the component in a given scene
  76350. */
  76351. ProceduralTextureSceneComponent.prototype.register = function () {
  76352. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76353. };
  76354. /**
  76355. * Rebuilds the elements related to this component in case of
  76356. * context lost for instance.
  76357. */
  76358. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76359. // Nothing to do here.
  76360. };
  76361. /**
  76362. * Disposes the component and the associated ressources.
  76363. */
  76364. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76365. // Nothing to do here.
  76366. };
  76367. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76368. if (this.scene.proceduralTexturesEnabled) {
  76369. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76370. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76371. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76372. if (proceduralTexture._shouldRender()) {
  76373. proceduralTexture.render();
  76374. }
  76375. }
  76376. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76377. }
  76378. };
  76379. return ProceduralTextureSceneComponent;
  76380. }());
  76381. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76382. })(BABYLON || (BABYLON = {}));
  76383. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76384. var BABYLON;
  76385. (function (BABYLON) {
  76386. var CustomProceduralTexture = /** @class */ (function (_super) {
  76387. __extends(CustomProceduralTexture, _super);
  76388. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76389. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76390. _this._animate = true;
  76391. _this._time = 0;
  76392. _this._texturePath = texturePath;
  76393. //Try to load json
  76394. _this.loadJson(texturePath);
  76395. _this.refreshRate = 1;
  76396. return _this;
  76397. }
  76398. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76399. var _this = this;
  76400. var noConfigFile = function () {
  76401. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76402. try {
  76403. _this.setFragment(_this._texturePath);
  76404. }
  76405. catch (ex) {
  76406. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76407. }
  76408. };
  76409. var configFileUrl = jsonUrl + "/config.json";
  76410. var xhr = new XMLHttpRequest();
  76411. xhr.open("GET", configFileUrl, true);
  76412. xhr.addEventListener("load", function () {
  76413. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76414. try {
  76415. _this._config = JSON.parse(xhr.response);
  76416. _this.updateShaderUniforms();
  76417. _this.updateTextures();
  76418. _this.setFragment(_this._texturePath + "/custom");
  76419. _this._animate = _this._config.animate;
  76420. _this.refreshRate = _this._config.refreshrate;
  76421. }
  76422. catch (ex) {
  76423. noConfigFile();
  76424. }
  76425. }
  76426. else {
  76427. noConfigFile();
  76428. }
  76429. }, false);
  76430. xhr.addEventListener("error", function () {
  76431. noConfigFile();
  76432. }, false);
  76433. try {
  76434. xhr.send();
  76435. }
  76436. catch (ex) {
  76437. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76438. }
  76439. };
  76440. CustomProceduralTexture.prototype.isReady = function () {
  76441. if (!_super.prototype.isReady.call(this)) {
  76442. return false;
  76443. }
  76444. for (var name in this._textures) {
  76445. var texture = this._textures[name];
  76446. if (!texture.isReady()) {
  76447. return false;
  76448. }
  76449. }
  76450. return true;
  76451. };
  76452. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76453. var scene = this.getScene();
  76454. if (this._animate && scene) {
  76455. this._time += scene.getAnimationRatio() * 0.03;
  76456. this.updateShaderUniforms();
  76457. }
  76458. _super.prototype.render.call(this, useCameraPostProcess);
  76459. };
  76460. CustomProceduralTexture.prototype.updateTextures = function () {
  76461. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76462. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76463. }
  76464. };
  76465. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76466. if (this._config) {
  76467. for (var j = 0; j < this._config.uniforms.length; j++) {
  76468. var uniform = this._config.uniforms[j];
  76469. switch (uniform.type) {
  76470. case "float":
  76471. this.setFloat(uniform.name, uniform.value);
  76472. break;
  76473. case "color3":
  76474. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76475. break;
  76476. case "color4":
  76477. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76478. break;
  76479. case "vector2":
  76480. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76481. break;
  76482. case "vector3":
  76483. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76484. break;
  76485. }
  76486. }
  76487. }
  76488. this.setFloat("time", this._time);
  76489. };
  76490. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76491. get: function () {
  76492. return this._animate;
  76493. },
  76494. set: function (value) {
  76495. this._animate = value;
  76496. },
  76497. enumerable: true,
  76498. configurable: true
  76499. });
  76500. return CustomProceduralTexture;
  76501. }(BABYLON.ProceduralTexture));
  76502. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76503. })(BABYLON || (BABYLON = {}));
  76504. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76505. var BABYLON;
  76506. (function (BABYLON) {
  76507. /**
  76508. * Manage the gamepad inputs to control a free camera.
  76509. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76510. */
  76511. var FreeCameraGamepadInput = /** @class */ (function () {
  76512. function FreeCameraGamepadInput() {
  76513. /**
  76514. * Defines the gamepad rotation sensiblity.
  76515. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76516. */
  76517. this.gamepadAngularSensibility = 200;
  76518. /**
  76519. * Defines the gamepad move sensiblity.
  76520. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76521. */
  76522. this.gamepadMoveSensibility = 40;
  76523. this._cameraTransform = BABYLON.Matrix.Identity();
  76524. this._deltaTransform = BABYLON.Vector3.Zero();
  76525. this._vector3 = BABYLON.Vector3.Zero();
  76526. this._vector2 = BABYLON.Vector2.Zero();
  76527. }
  76528. /**
  76529. * Attach the input controls to a specific dom element to get the input from.
  76530. * @param element Defines the element the controls should be listened from
  76531. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76532. */
  76533. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76534. var _this = this;
  76535. var manager = this.camera.getScene().gamepadManager;
  76536. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76537. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76538. // prioritize XBOX gamepads.
  76539. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76540. _this.gamepad = gamepad;
  76541. }
  76542. }
  76543. });
  76544. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76545. if (_this.gamepad === gamepad) {
  76546. _this.gamepad = null;
  76547. }
  76548. });
  76549. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76550. };
  76551. /**
  76552. * Detach the current controls from the specified dom element.
  76553. * @param element Defines the element to stop listening the inputs from
  76554. */
  76555. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  76556. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76557. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76558. this.gamepad = null;
  76559. };
  76560. /**
  76561. * Update the current camera state depending on the inputs that have been used this frame.
  76562. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76563. */
  76564. FreeCameraGamepadInput.prototype.checkInputs = function () {
  76565. if (this.gamepad && this.gamepad.leftStick) {
  76566. var camera = this.camera;
  76567. var LSValues = this.gamepad.leftStick;
  76568. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  76569. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76570. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  76571. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  76572. var RSValues = this.gamepad.rightStick;
  76573. if (RSValues) {
  76574. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  76575. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  76576. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  76577. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  76578. }
  76579. else {
  76580. RSValues = { x: 0, y: 0 };
  76581. }
  76582. if (!camera.rotationQuaternion) {
  76583. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  76584. }
  76585. else {
  76586. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  76587. }
  76588. var speed = camera._computeLocalCameraSpeed() * 50.0;
  76589. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  76590. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  76591. camera.cameraDirection.addInPlace(this._deltaTransform);
  76592. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  76593. camera.cameraRotation.addInPlace(this._vector2);
  76594. }
  76595. };
  76596. /**
  76597. * Gets the class name of the current intput.
  76598. * @returns the class name
  76599. */
  76600. FreeCameraGamepadInput.prototype.getClassName = function () {
  76601. return "FreeCameraGamepadInput";
  76602. };
  76603. /**
  76604. * Get the friendly name associated with the input class.
  76605. * @returns the input friendly name
  76606. */
  76607. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  76608. return "gamepad";
  76609. };
  76610. __decorate([
  76611. BABYLON.serialize()
  76612. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  76613. __decorate([
  76614. BABYLON.serialize()
  76615. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76616. return FreeCameraGamepadInput;
  76617. }());
  76618. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  76619. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  76620. })(BABYLON || (BABYLON = {}));
  76621. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  76622. var BABYLON;
  76623. (function (BABYLON) {
  76624. /**
  76625. * Manage the gamepad inputs to control an arc rotate camera.
  76626. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76627. */
  76628. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  76629. function ArcRotateCameraGamepadInput() {
  76630. /**
  76631. * Defines the gamepad rotation sensiblity.
  76632. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76633. */
  76634. this.gamepadRotationSensibility = 80;
  76635. /**
  76636. * Defines the gamepad move sensiblity.
  76637. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76638. */
  76639. this.gamepadMoveSensibility = 40;
  76640. }
  76641. /**
  76642. * Attach the input controls to a specific dom element to get the input from.
  76643. * @param element Defines the element the controls should be listened from
  76644. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76645. */
  76646. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76647. var _this = this;
  76648. var manager = this.camera.getScene().gamepadManager;
  76649. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76650. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76651. // prioritize XBOX gamepads.
  76652. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76653. _this.gamepad = gamepad;
  76654. }
  76655. }
  76656. });
  76657. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76658. if (_this.gamepad === gamepad) {
  76659. _this.gamepad = null;
  76660. }
  76661. });
  76662. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76663. };
  76664. /**
  76665. * Detach the current controls from the specified dom element.
  76666. * @param element Defines the element to stop listening the inputs from
  76667. */
  76668. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  76669. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76670. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76671. this.gamepad = null;
  76672. };
  76673. /**
  76674. * Update the current camera state depending on the inputs that have been used this frame.
  76675. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76676. */
  76677. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  76678. if (this.gamepad) {
  76679. var camera = this.camera;
  76680. var RSValues = this.gamepad.rightStick;
  76681. if (RSValues) {
  76682. if (RSValues.x != 0) {
  76683. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  76684. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  76685. camera.inertialAlphaOffset += normalizedRX;
  76686. }
  76687. }
  76688. if (RSValues.y != 0) {
  76689. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  76690. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  76691. camera.inertialBetaOffset += normalizedRY;
  76692. }
  76693. }
  76694. }
  76695. var LSValues = this.gamepad.leftStick;
  76696. if (LSValues && LSValues.y != 0) {
  76697. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76698. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  76699. this.camera.inertialRadiusOffset -= normalizedLY;
  76700. }
  76701. }
  76702. }
  76703. };
  76704. /**
  76705. * Gets the class name of the current intput.
  76706. * @returns the class name
  76707. */
  76708. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  76709. return "ArcRotateCameraGamepadInput";
  76710. };
  76711. /**
  76712. * Get the friendly name associated with the input class.
  76713. * @returns the input friendly name
  76714. */
  76715. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  76716. return "gamepad";
  76717. };
  76718. __decorate([
  76719. BABYLON.serialize()
  76720. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  76721. __decorate([
  76722. BABYLON.serialize()
  76723. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76724. return ArcRotateCameraGamepadInput;
  76725. }());
  76726. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  76727. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  76728. })(BABYLON || (BABYLON = {}));
  76729. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  76730. var BABYLON;
  76731. (function (BABYLON) {
  76732. var GamepadManager = /** @class */ (function () {
  76733. function GamepadManager(_scene) {
  76734. var _this = this;
  76735. this._scene = _scene;
  76736. this._babylonGamepads = [];
  76737. this._oneGamepadConnected = false;
  76738. /** @hidden */
  76739. this._isMonitoring = false;
  76740. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  76741. if (!BABYLON.Tools.IsWindowObjectExist()) {
  76742. this._gamepadEventSupported = false;
  76743. }
  76744. else {
  76745. this._gamepadEventSupported = 'GamepadEvent' in window;
  76746. this._gamepadSupport = (navigator.getGamepads ||
  76747. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  76748. }
  76749. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  76750. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  76751. for (var i in _this._babylonGamepads) {
  76752. var gamepad = _this._babylonGamepads[i];
  76753. if (gamepad && gamepad._isConnected) {
  76754. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  76755. }
  76756. }
  76757. });
  76758. this._onGamepadConnectedEvent = function (evt) {
  76759. var gamepad = evt.gamepad;
  76760. if (gamepad.index in _this._babylonGamepads) {
  76761. if (_this._babylonGamepads[gamepad.index].isConnected) {
  76762. return;
  76763. }
  76764. }
  76765. var newGamepad;
  76766. if (_this._babylonGamepads[gamepad.index]) {
  76767. newGamepad = _this._babylonGamepads[gamepad.index];
  76768. newGamepad.browserGamepad = gamepad;
  76769. newGamepad._isConnected = true;
  76770. }
  76771. else {
  76772. newGamepad = _this._addNewGamepad(gamepad);
  76773. }
  76774. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76775. _this._startMonitoringGamepads();
  76776. };
  76777. this._onGamepadDisconnectedEvent = function (evt) {
  76778. var gamepad = evt.gamepad;
  76779. // Remove the gamepad from the list of gamepads to monitor.
  76780. for (var i in _this._babylonGamepads) {
  76781. if (_this._babylonGamepads[i].index === gamepad.index) {
  76782. var disconnectedGamepad = _this._babylonGamepads[i];
  76783. disconnectedGamepad._isConnected = false;
  76784. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  76785. break;
  76786. }
  76787. }
  76788. };
  76789. if (this._gamepadSupport) {
  76790. //first add already-connected gamepads
  76791. this._updateGamepadObjects();
  76792. if (this._babylonGamepads.length) {
  76793. this._startMonitoringGamepads();
  76794. }
  76795. // Checking if the gamepad connected event is supported (like in Firefox)
  76796. if (this._gamepadEventSupported) {
  76797. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  76798. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  76799. }
  76800. else {
  76801. this._startMonitoringGamepads();
  76802. }
  76803. }
  76804. }
  76805. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  76806. get: function () {
  76807. return this._babylonGamepads;
  76808. },
  76809. enumerable: true,
  76810. configurable: true
  76811. });
  76812. GamepadManager.prototype.getGamepadByType = function (type) {
  76813. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  76814. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  76815. var gamepad = _a[_i];
  76816. if (gamepad && gamepad.type === type) {
  76817. return gamepad;
  76818. }
  76819. }
  76820. return null;
  76821. };
  76822. GamepadManager.prototype.dispose = function () {
  76823. if (this._gamepadEventSupported) {
  76824. if (this._onGamepadConnectedEvent) {
  76825. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  76826. }
  76827. if (this._onGamepadDisconnectedEvent) {
  76828. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  76829. }
  76830. this._onGamepadConnectedEvent = null;
  76831. this._onGamepadDisconnectedEvent = null;
  76832. }
  76833. this._babylonGamepads.forEach(function (gamepad) {
  76834. gamepad.dispose();
  76835. });
  76836. this.onGamepadConnectedObservable.clear();
  76837. this.onGamepadDisconnectedObservable.clear();
  76838. this._oneGamepadConnected = false;
  76839. this._stopMonitoringGamepads();
  76840. this._babylonGamepads = [];
  76841. };
  76842. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  76843. if (!this._oneGamepadConnected) {
  76844. this._oneGamepadConnected = true;
  76845. }
  76846. var newGamepad;
  76847. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  76848. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  76849. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  76850. }
  76851. // if pose is supported, use the (WebVR) pose enabled controller
  76852. else if (gamepad.pose) {
  76853. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  76854. }
  76855. else {
  76856. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  76857. }
  76858. this._babylonGamepads[newGamepad.index] = newGamepad;
  76859. return newGamepad;
  76860. };
  76861. GamepadManager.prototype._startMonitoringGamepads = function () {
  76862. if (!this._isMonitoring) {
  76863. this._isMonitoring = true;
  76864. //back-comp
  76865. if (!this._scene) {
  76866. this._checkGamepadsStatus();
  76867. }
  76868. }
  76869. };
  76870. GamepadManager.prototype._stopMonitoringGamepads = function () {
  76871. this._isMonitoring = false;
  76872. };
  76873. /** @hidden */
  76874. GamepadManager.prototype._checkGamepadsStatus = function () {
  76875. var _this = this;
  76876. // Hack to be compatible Chrome
  76877. this._updateGamepadObjects();
  76878. for (var i in this._babylonGamepads) {
  76879. var gamepad = this._babylonGamepads[i];
  76880. if (!gamepad || !gamepad.isConnected) {
  76881. continue;
  76882. }
  76883. gamepad.update();
  76884. }
  76885. if (this._isMonitoring && !this._scene) {
  76886. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  76887. }
  76888. };
  76889. // This function is called only on Chrome, which does not properly support
  76890. // connection/disconnection events and forces you to recopy again the gamepad object
  76891. GamepadManager.prototype._updateGamepadObjects = function () {
  76892. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  76893. for (var i = 0; i < gamepads.length; i++) {
  76894. var gamepad = gamepads[i];
  76895. if (gamepad) {
  76896. if (!this._babylonGamepads[gamepad.index]) {
  76897. var newGamepad = this._addNewGamepad(gamepad);
  76898. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76899. }
  76900. else {
  76901. // Forced to copy again this object for Chrome for unknown reason
  76902. this._babylonGamepads[i].browserGamepad = gamepad;
  76903. if (!this._babylonGamepads[i].isConnected) {
  76904. this._babylonGamepads[i]._isConnected = true;
  76905. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  76906. }
  76907. }
  76908. }
  76909. }
  76910. };
  76911. return GamepadManager;
  76912. }());
  76913. BABYLON.GamepadManager = GamepadManager;
  76914. })(BABYLON || (BABYLON = {}));
  76915. //# sourceMappingURL=babylon.gamepadManager.js.map
  76916. var BABYLON;
  76917. (function (BABYLON) {
  76918. var StickValues = /** @class */ (function () {
  76919. function StickValues(x, y) {
  76920. this.x = x;
  76921. this.y = y;
  76922. }
  76923. return StickValues;
  76924. }());
  76925. BABYLON.StickValues = StickValues;
  76926. var Gamepad = /** @class */ (function () {
  76927. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  76928. if (leftStickX === void 0) { leftStickX = 0; }
  76929. if (leftStickY === void 0) { leftStickY = 1; }
  76930. if (rightStickX === void 0) { rightStickX = 2; }
  76931. if (rightStickY === void 0) { rightStickY = 3; }
  76932. this.id = id;
  76933. this.index = index;
  76934. this.browserGamepad = browserGamepad;
  76935. this._leftStick = { x: 0, y: 0 };
  76936. this._rightStick = { x: 0, y: 0 };
  76937. /** @hidden */
  76938. this._isConnected = true;
  76939. this._invertLeftStickY = false;
  76940. this.type = Gamepad.GAMEPAD;
  76941. this._leftStickAxisX = leftStickX;
  76942. this._leftStickAxisY = leftStickY;
  76943. this._rightStickAxisX = rightStickX;
  76944. this._rightStickAxisY = rightStickY;
  76945. if (this.browserGamepad.axes.length >= 2) {
  76946. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76947. }
  76948. if (this.browserGamepad.axes.length >= 4) {
  76949. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  76950. }
  76951. }
  76952. Object.defineProperty(Gamepad.prototype, "isConnected", {
  76953. get: function () {
  76954. return this._isConnected;
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Gamepad.prototype.onleftstickchanged = function (callback) {
  76960. this._onleftstickchanged = callback;
  76961. };
  76962. Gamepad.prototype.onrightstickchanged = function (callback) {
  76963. this._onrightstickchanged = callback;
  76964. };
  76965. Object.defineProperty(Gamepad.prototype, "leftStick", {
  76966. get: function () {
  76967. return this._leftStick;
  76968. },
  76969. set: function (newValues) {
  76970. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  76971. this._onleftstickchanged(newValues);
  76972. }
  76973. this._leftStick = newValues;
  76974. },
  76975. enumerable: true,
  76976. configurable: true
  76977. });
  76978. Object.defineProperty(Gamepad.prototype, "rightStick", {
  76979. get: function () {
  76980. return this._rightStick;
  76981. },
  76982. set: function (newValues) {
  76983. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  76984. this._onrightstickchanged(newValues);
  76985. }
  76986. this._rightStick = newValues;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. Gamepad.prototype.update = function () {
  76992. if (this._leftStick) {
  76993. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76994. if (this._invertLeftStickY) {
  76995. this.leftStick.y *= -1;
  76996. }
  76997. }
  76998. if (this._rightStick) {
  76999. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77000. }
  77001. };
  77002. Gamepad.prototype.dispose = function () {
  77003. };
  77004. Gamepad.GAMEPAD = 0;
  77005. Gamepad.GENERIC = 1;
  77006. Gamepad.XBOX = 2;
  77007. Gamepad.POSE_ENABLED = 3;
  77008. return Gamepad;
  77009. }());
  77010. BABYLON.Gamepad = Gamepad;
  77011. var GenericPad = /** @class */ (function (_super) {
  77012. __extends(GenericPad, _super);
  77013. function GenericPad(id, index, browserGamepad) {
  77014. var _this = _super.call(this, id, index, browserGamepad) || this;
  77015. _this.onButtonDownObservable = new BABYLON.Observable();
  77016. _this.onButtonUpObservable = new BABYLON.Observable();
  77017. _this.type = Gamepad.GENERIC;
  77018. _this._buttons = new Array(browserGamepad.buttons.length);
  77019. return _this;
  77020. }
  77021. GenericPad.prototype.onbuttondown = function (callback) {
  77022. this._onbuttondown = callback;
  77023. };
  77024. GenericPad.prototype.onbuttonup = function (callback) {
  77025. this._onbuttonup = callback;
  77026. };
  77027. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77028. if (newValue !== currentValue) {
  77029. if (newValue === 1) {
  77030. if (this._onbuttondown) {
  77031. this._onbuttondown(buttonIndex);
  77032. }
  77033. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77034. }
  77035. if (newValue === 0) {
  77036. if (this._onbuttonup) {
  77037. this._onbuttonup(buttonIndex);
  77038. }
  77039. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77040. }
  77041. }
  77042. return newValue;
  77043. };
  77044. GenericPad.prototype.update = function () {
  77045. _super.prototype.update.call(this);
  77046. for (var index = 0; index < this._buttons.length; index++) {
  77047. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77048. }
  77049. };
  77050. GenericPad.prototype.dispose = function () {
  77051. _super.prototype.dispose.call(this);
  77052. this.onButtonDownObservable.clear();
  77053. this.onButtonUpObservable.clear();
  77054. };
  77055. return GenericPad;
  77056. }(Gamepad));
  77057. BABYLON.GenericPad = GenericPad;
  77058. })(BABYLON || (BABYLON = {}));
  77059. //# sourceMappingURL=babylon.gamepad.js.map
  77060. var BABYLON;
  77061. (function (BABYLON) {
  77062. /**
  77063. * Defines supported buttons for XBox360 compatible gamepads
  77064. */
  77065. var Xbox360Button;
  77066. (function (Xbox360Button) {
  77067. /** A */
  77068. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77069. /** B */
  77070. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77071. /** X */
  77072. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77073. /** Y */
  77074. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77075. /** Start */
  77076. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77077. /** Back */
  77078. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77079. /** Left button */
  77080. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77081. /** Right button */
  77082. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77083. /** Left stick */
  77084. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77085. /** Right stick */
  77086. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77087. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77088. /** Defines values for XBox360 DPad */
  77089. var Xbox360Dpad;
  77090. (function (Xbox360Dpad) {
  77091. /** Up */
  77092. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77093. /** Down */
  77094. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77095. /** Left */
  77096. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77097. /** Right */
  77098. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77099. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77100. /**
  77101. * Defines a XBox360 gamepad
  77102. */
  77103. var Xbox360Pad = /** @class */ (function (_super) {
  77104. __extends(Xbox360Pad, _super);
  77105. /**
  77106. * Creates a new XBox360 gamepad object
  77107. * @param id defines the id of this gamepad
  77108. * @param index defines its index
  77109. * @param gamepad defines the internal HTML gamepad object
  77110. * @param xboxOne defines if it is a XBox One gamepad
  77111. */
  77112. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77113. if (xboxOne === void 0) { xboxOne = false; }
  77114. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77115. _this._leftTrigger = 0;
  77116. _this._rightTrigger = 0;
  77117. /** Observable raised when a button is pressed */
  77118. _this.onButtonDownObservable = new BABYLON.Observable();
  77119. /** Observable raised when a button is released */
  77120. _this.onButtonUpObservable = new BABYLON.Observable();
  77121. /** Observable raised when a pad is pressed */
  77122. _this.onPadDownObservable = new BABYLON.Observable();
  77123. /** Observable raised when a pad is released */
  77124. _this.onPadUpObservable = new BABYLON.Observable();
  77125. _this._buttonA = 0;
  77126. _this._buttonB = 0;
  77127. _this._buttonX = 0;
  77128. _this._buttonY = 0;
  77129. _this._buttonBack = 0;
  77130. _this._buttonStart = 0;
  77131. _this._buttonLB = 0;
  77132. _this._buttonRB = 0;
  77133. _this._buttonLeftStick = 0;
  77134. _this._buttonRightStick = 0;
  77135. _this._dPadUp = 0;
  77136. _this._dPadDown = 0;
  77137. _this._dPadLeft = 0;
  77138. _this._dPadRight = 0;
  77139. _this._isXboxOnePad = false;
  77140. _this.type = BABYLON.Gamepad.XBOX;
  77141. _this._isXboxOnePad = xboxOne;
  77142. return _this;
  77143. }
  77144. /**
  77145. * Defines the callback to call when left trigger is pressed
  77146. * @param callback defines the callback to use
  77147. */
  77148. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77149. this._onlefttriggerchanged = callback;
  77150. };
  77151. /**
  77152. * Defines the callback to call when right trigger is pressed
  77153. * @param callback defines the callback to use
  77154. */
  77155. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77156. this._onrighttriggerchanged = callback;
  77157. };
  77158. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77159. /**
  77160. * Gets or sets left trigger value
  77161. */
  77162. get: function () {
  77163. return this._leftTrigger;
  77164. },
  77165. set: function (newValue) {
  77166. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77167. this._onlefttriggerchanged(newValue);
  77168. }
  77169. this._leftTrigger = newValue;
  77170. },
  77171. enumerable: true,
  77172. configurable: true
  77173. });
  77174. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77175. /**
  77176. * Gets or sets right trigger value
  77177. */
  77178. get: function () {
  77179. return this._rightTrigger;
  77180. },
  77181. set: function (newValue) {
  77182. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77183. this._onrighttriggerchanged(newValue);
  77184. }
  77185. this._rightTrigger = newValue;
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. /**
  77191. * Defines the callback to call when a button is pressed
  77192. * @param callback defines the callback to use
  77193. */
  77194. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77195. this._onbuttondown = callback;
  77196. };
  77197. /**
  77198. * Defines the callback to call when a button is released
  77199. * @param callback defines the callback to use
  77200. */
  77201. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77202. this._onbuttonup = callback;
  77203. };
  77204. /**
  77205. * Defines the callback to call when a pad is pressed
  77206. * @param callback defines the callback to use
  77207. */
  77208. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77209. this._ondpaddown = callback;
  77210. };
  77211. /**
  77212. * Defines the callback to call when a pad is released
  77213. * @param callback defines the callback to use
  77214. */
  77215. Xbox360Pad.prototype.ondpadup = function (callback) {
  77216. this._ondpadup = callback;
  77217. };
  77218. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77219. if (newValue !== currentValue) {
  77220. if (newValue === 1) {
  77221. if (this._onbuttondown) {
  77222. this._onbuttondown(buttonType);
  77223. }
  77224. this.onButtonDownObservable.notifyObservers(buttonType);
  77225. }
  77226. if (newValue === 0) {
  77227. if (this._onbuttonup) {
  77228. this._onbuttonup(buttonType);
  77229. }
  77230. this.onButtonUpObservable.notifyObservers(buttonType);
  77231. }
  77232. }
  77233. return newValue;
  77234. };
  77235. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77236. if (newValue !== currentValue) {
  77237. if (newValue === 1) {
  77238. if (this._ondpaddown) {
  77239. this._ondpaddown(buttonType);
  77240. }
  77241. this.onPadDownObservable.notifyObservers(buttonType);
  77242. }
  77243. if (newValue === 0) {
  77244. if (this._ondpadup) {
  77245. this._ondpadup(buttonType);
  77246. }
  77247. this.onPadUpObservable.notifyObservers(buttonType);
  77248. }
  77249. }
  77250. return newValue;
  77251. };
  77252. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77253. /** Gets or sets value of A button */
  77254. get: function () {
  77255. return this._buttonA;
  77256. },
  77257. set: function (value) {
  77258. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77259. },
  77260. enumerable: true,
  77261. configurable: true
  77262. });
  77263. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77264. /** Gets or sets value of B button */
  77265. get: function () {
  77266. return this._buttonB;
  77267. },
  77268. set: function (value) {
  77269. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77270. },
  77271. enumerable: true,
  77272. configurable: true
  77273. });
  77274. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77275. /** Gets or sets value of X button */
  77276. get: function () {
  77277. return this._buttonX;
  77278. },
  77279. set: function (value) {
  77280. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77281. },
  77282. enumerable: true,
  77283. configurable: true
  77284. });
  77285. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77286. /** Gets or sets value of Y button */
  77287. get: function () {
  77288. return this._buttonY;
  77289. },
  77290. set: function (value) {
  77291. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77292. },
  77293. enumerable: true,
  77294. configurable: true
  77295. });
  77296. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77297. /** Gets or sets value of Start button */
  77298. get: function () {
  77299. return this._buttonStart;
  77300. },
  77301. set: function (value) {
  77302. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77303. },
  77304. enumerable: true,
  77305. configurable: true
  77306. });
  77307. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77308. /** Gets or sets value of Back button */
  77309. get: function () {
  77310. return this._buttonBack;
  77311. },
  77312. set: function (value) {
  77313. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77314. },
  77315. enumerable: true,
  77316. configurable: true
  77317. });
  77318. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77319. /** Gets or sets value of Left button */
  77320. get: function () {
  77321. return this._buttonLB;
  77322. },
  77323. set: function (value) {
  77324. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77325. },
  77326. enumerable: true,
  77327. configurable: true
  77328. });
  77329. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77330. /** Gets or sets value of Right button */
  77331. get: function () {
  77332. return this._buttonRB;
  77333. },
  77334. set: function (value) {
  77335. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  77336. },
  77337. enumerable: true,
  77338. configurable: true
  77339. });
  77340. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  77341. /** Gets or sets value of left stick */
  77342. get: function () {
  77343. return this._buttonLeftStick;
  77344. },
  77345. set: function (value) {
  77346. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  77352. /** Gets or sets value of right stick */
  77353. get: function () {
  77354. return this._buttonRightStick;
  77355. },
  77356. set: function (value) {
  77357. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  77358. },
  77359. enumerable: true,
  77360. configurable: true
  77361. });
  77362. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  77363. /** Gets or sets value of DPad up */
  77364. get: function () {
  77365. return this._dPadUp;
  77366. },
  77367. set: function (value) {
  77368. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  77369. },
  77370. enumerable: true,
  77371. configurable: true
  77372. });
  77373. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  77374. /** Gets or sets value of DPad down */
  77375. get: function () {
  77376. return this._dPadDown;
  77377. },
  77378. set: function (value) {
  77379. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  77380. },
  77381. enumerable: true,
  77382. configurable: true
  77383. });
  77384. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  77385. /** Gets or sets value of DPad left */
  77386. get: function () {
  77387. return this._dPadLeft;
  77388. },
  77389. set: function (value) {
  77390. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  77391. },
  77392. enumerable: true,
  77393. configurable: true
  77394. });
  77395. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  77396. /** Gets or sets value of DPad right */
  77397. get: function () {
  77398. return this._dPadRight;
  77399. },
  77400. set: function (value) {
  77401. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  77402. },
  77403. enumerable: true,
  77404. configurable: true
  77405. });
  77406. /**
  77407. * Force the gamepad to synchronize with device values
  77408. */
  77409. Xbox360Pad.prototype.update = function () {
  77410. _super.prototype.update.call(this);
  77411. if (this._isXboxOnePad) {
  77412. this.buttonA = this.browserGamepad.buttons[0].value;
  77413. this.buttonB = this.browserGamepad.buttons[1].value;
  77414. this.buttonX = this.browserGamepad.buttons[2].value;
  77415. this.buttonY = this.browserGamepad.buttons[3].value;
  77416. this.buttonLB = this.browserGamepad.buttons[4].value;
  77417. this.buttonRB = this.browserGamepad.buttons[5].value;
  77418. this.leftTrigger = this.browserGamepad.axes[2];
  77419. this.rightTrigger = this.browserGamepad.axes[5];
  77420. this.buttonBack = this.browserGamepad.buttons[9].value;
  77421. this.buttonStart = this.browserGamepad.buttons[8].value;
  77422. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  77423. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  77424. this.dPadUp = this.browserGamepad.buttons[11].value;
  77425. this.dPadDown = this.browserGamepad.buttons[12].value;
  77426. this.dPadLeft = this.browserGamepad.buttons[13].value;
  77427. this.dPadRight = this.browserGamepad.buttons[14].value;
  77428. }
  77429. else {
  77430. this.buttonA = this.browserGamepad.buttons[0].value;
  77431. this.buttonB = this.browserGamepad.buttons[1].value;
  77432. this.buttonX = this.browserGamepad.buttons[2].value;
  77433. this.buttonY = this.browserGamepad.buttons[3].value;
  77434. this.buttonLB = this.browserGamepad.buttons[4].value;
  77435. this.buttonRB = this.browserGamepad.buttons[5].value;
  77436. this.leftTrigger = this.browserGamepad.buttons[6].value;
  77437. this.rightTrigger = this.browserGamepad.buttons[7].value;
  77438. this.buttonBack = this.browserGamepad.buttons[8].value;
  77439. this.buttonStart = this.browserGamepad.buttons[9].value;
  77440. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  77441. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  77442. this.dPadUp = this.browserGamepad.buttons[12].value;
  77443. this.dPadDown = this.browserGamepad.buttons[13].value;
  77444. this.dPadLeft = this.browserGamepad.buttons[14].value;
  77445. this.dPadRight = this.browserGamepad.buttons[15].value;
  77446. }
  77447. };
  77448. Xbox360Pad.prototype.dispose = function () {
  77449. _super.prototype.dispose.call(this);
  77450. this.onButtonDownObservable.clear();
  77451. this.onButtonUpObservable.clear();
  77452. this.onPadDownObservable.clear();
  77453. this.onPadUpObservable.clear();
  77454. };
  77455. return Xbox360Pad;
  77456. }(BABYLON.Gamepad));
  77457. BABYLON.Xbox360Pad = Xbox360Pad;
  77458. })(BABYLON || (BABYLON = {}));
  77459. //# sourceMappingURL=babylon.xboxGamepad.js.map
  77460. var BABYLON;
  77461. (function (BABYLON) {
  77462. /**
  77463. * Defines the types of pose enabled controllers that are supported
  77464. */
  77465. var PoseEnabledControllerType;
  77466. (function (PoseEnabledControllerType) {
  77467. /**
  77468. * HTC Vive
  77469. */
  77470. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  77471. /**
  77472. * Oculus Rift
  77473. */
  77474. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  77475. /**
  77476. * Windows mixed reality
  77477. */
  77478. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  77479. /**
  77480. * Samsung gear VR
  77481. */
  77482. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  77483. /**
  77484. * Google Daydream
  77485. */
  77486. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  77487. /**
  77488. * Generic
  77489. */
  77490. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  77491. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  77492. /**
  77493. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77494. */
  77495. var PoseEnabledControllerHelper = /** @class */ (function () {
  77496. function PoseEnabledControllerHelper() {
  77497. }
  77498. /**
  77499. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77500. * @param vrGamepad the gamepad to initialized
  77501. * @returns a vr controller of the type the gamepad identified as
  77502. */
  77503. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  77504. // Oculus Touch
  77505. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  77506. return new BABYLON.OculusTouchController(vrGamepad);
  77507. }
  77508. // Windows Mixed Reality controllers
  77509. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  77510. return new BABYLON.WindowsMotionController(vrGamepad);
  77511. }
  77512. // HTC Vive
  77513. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  77514. return new BABYLON.ViveController(vrGamepad);
  77515. }
  77516. // Samsung/Oculus Gear VR or Oculus Go
  77517. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  77518. return new BABYLON.GearVRController(vrGamepad);
  77519. }
  77520. // Google Daydream
  77521. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  77522. return new BABYLON.DaydreamController(vrGamepad);
  77523. }
  77524. // Generic
  77525. else {
  77526. return new BABYLON.GenericController(vrGamepad);
  77527. }
  77528. };
  77529. return PoseEnabledControllerHelper;
  77530. }());
  77531. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  77532. /**
  77533. * Defines the PoseEnabledController object that contains state of a vr capable controller
  77534. */
  77535. var PoseEnabledController = /** @class */ (function (_super) {
  77536. __extends(PoseEnabledController, _super);
  77537. /**
  77538. * Creates a new PoseEnabledController from a gamepad
  77539. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  77540. */
  77541. function PoseEnabledController(browserGamepad) {
  77542. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  77543. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77544. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77545. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  77546. /**
  77547. * The device position in babylon space
  77548. */
  77549. _this.devicePosition = BABYLON.Vector3.Zero();
  77550. /**
  77551. * The device rotation in babylon space
  77552. */
  77553. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  77554. /**
  77555. * The scale factor of the device in babylon space
  77556. */
  77557. _this.deviceScaleFactor = 1;
  77558. // Used to convert 6dof controllers to 3dof
  77559. _this._trackPosition = true;
  77560. _this._maxRotationDistFromHeadset = Math.PI / 5;
  77561. _this._draggedRoomRotation = 0;
  77562. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  77563. /**
  77564. * Internal, matrix used to convert room space to babylon space
  77565. * @hidden
  77566. */
  77567. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77568. /**
  77569. * Node to be used when casting a ray from the controller
  77570. * @hidden
  77571. */
  77572. _this._pointingPoseNode = null;
  77573. _this._workingMatrix = BABYLON.Matrix.Identity();
  77574. /**
  77575. * @hidden
  77576. */
  77577. _this._meshAttachedObservable = new BABYLON.Observable();
  77578. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  77579. _this.controllerType = PoseEnabledControllerType.GENERIC;
  77580. _this.position = BABYLON.Vector3.Zero();
  77581. _this.rotationQuaternion = new BABYLON.Quaternion();
  77582. _this._calculatedPosition = BABYLON.Vector3.Zero();
  77583. _this._calculatedRotation = new BABYLON.Quaternion();
  77584. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  77585. return _this;
  77586. }
  77587. /**
  77588. * @hidden
  77589. */
  77590. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  77591. if (this._trackPosition) {
  77592. this._calculatedPosition.copyFrom(fixedPosition);
  77593. this._trackPosition = false;
  77594. }
  77595. };
  77596. /**
  77597. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  77598. */
  77599. PoseEnabledController.prototype.update = function () {
  77600. _super.prototype.update.call(this);
  77601. this._updatePoseAndMesh();
  77602. };
  77603. /**
  77604. * Updates only the pose device and mesh without doing any button event checking
  77605. */
  77606. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  77607. var pose = this.browserGamepad.pose;
  77608. this.updateFromDevice(pose);
  77609. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  77610. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  77611. camera._computeDevicePosition();
  77612. this._deviceToWorld.setTranslation(camera.devicePosition);
  77613. if (camera.deviceRotationQuaternion) {
  77614. var camera = camera;
  77615. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  77616. // Find the radian distance away that the headset is from the controllers rotation
  77617. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  77618. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  77619. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  77620. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  77621. this._draggedRoomRotation += rotationAmount;
  77622. // Rotate controller around headset
  77623. var sin = Math.sin(-rotationAmount);
  77624. var cos = Math.cos(-rotationAmount);
  77625. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77626. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77627. }
  77628. }
  77629. }
  77630. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  77631. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  77632. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77633. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  77634. if (this._mesh) {
  77635. this._mesh.position.copyFrom(this.devicePosition);
  77636. if (this._mesh.rotationQuaternion) {
  77637. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  77638. }
  77639. }
  77640. };
  77641. /**
  77642. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77643. * @param poseData raw pose fromthe device
  77644. */
  77645. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  77646. if (poseData) {
  77647. this.rawPose = poseData;
  77648. if (poseData.position) {
  77649. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  77650. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  77651. this._deviceRoomPosition.z *= -1;
  77652. }
  77653. if (this._trackPosition) {
  77654. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  77655. }
  77656. this._calculatedPosition.addInPlace(this.position);
  77657. }
  77658. var pose = this.rawPose;
  77659. if (poseData.orientation && pose.orientation) {
  77660. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  77661. if (this._mesh) {
  77662. if (this._mesh.getScene().useRightHandedSystem) {
  77663. this._deviceRoomRotationQuaternion.z *= -1;
  77664. this._deviceRoomRotationQuaternion.w *= -1;
  77665. }
  77666. else {
  77667. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  77668. }
  77669. }
  77670. // if the camera is set, rotate to the camera's rotation
  77671. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  77672. }
  77673. }
  77674. };
  77675. /**
  77676. * Attaches a mesh to the controller
  77677. * @param mesh the mesh to be attached
  77678. */
  77679. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  77680. if (this._mesh) {
  77681. this._mesh.parent = null;
  77682. }
  77683. this._mesh = mesh;
  77684. if (this._poseControlledCamera) {
  77685. this._mesh.parent = this._poseControlledCamera;
  77686. }
  77687. if (!this._mesh.rotationQuaternion) {
  77688. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  77689. }
  77690. // 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
  77691. this._updatePoseAndMesh();
  77692. if (this._pointingPoseNode) {
  77693. var parents = [];
  77694. var obj = this._pointingPoseNode;
  77695. while (obj.parent) {
  77696. parents.push(obj.parent);
  77697. obj = obj.parent;
  77698. }
  77699. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  77700. }
  77701. this._meshAttachedObservable.notifyObservers(mesh);
  77702. };
  77703. /**
  77704. * Attaches the controllers mesh to a camera
  77705. * @param camera the camera the mesh should be attached to
  77706. */
  77707. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  77708. this._poseControlledCamera = camera;
  77709. if (this._mesh) {
  77710. this._mesh.parent = this._poseControlledCamera;
  77711. }
  77712. };
  77713. /**
  77714. * Disposes of the controller
  77715. */
  77716. PoseEnabledController.prototype.dispose = function () {
  77717. if (this._mesh) {
  77718. this._mesh.dispose();
  77719. }
  77720. this._mesh = null;
  77721. _super.prototype.dispose.call(this);
  77722. };
  77723. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  77724. /**
  77725. * The mesh that is attached to the controller
  77726. */
  77727. get: function () {
  77728. return this._mesh;
  77729. },
  77730. enumerable: true,
  77731. configurable: true
  77732. });
  77733. /**
  77734. * Gets the ray of the controller in the direction the controller is pointing
  77735. * @param length the length the resulting ray should be
  77736. * @returns a ray in the direction the controller is pointing
  77737. */
  77738. PoseEnabledController.prototype.getForwardRay = function (length) {
  77739. if (length === void 0) { length = 100; }
  77740. if (!this.mesh) {
  77741. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  77742. }
  77743. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  77744. var origin = m.getTranslation();
  77745. var forward = new BABYLON.Vector3(0, 0, -1);
  77746. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77747. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77748. return new BABYLON.Ray(origin, direction, length);
  77749. };
  77750. /**
  77751. * Name of the child mesh that can be used to cast a ray from the controller
  77752. */
  77753. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  77754. return PoseEnabledController;
  77755. }(BABYLON.Gamepad));
  77756. BABYLON.PoseEnabledController = PoseEnabledController;
  77757. })(BABYLON || (BABYLON = {}));
  77758. //# sourceMappingURL=babylon.poseEnabledController.js.map
  77759. var BABYLON;
  77760. (function (BABYLON) {
  77761. /**
  77762. * Defines the WebVRController object that represents controllers tracked in 3D space
  77763. */
  77764. var WebVRController = /** @class */ (function (_super) {
  77765. __extends(WebVRController, _super);
  77766. /**
  77767. * Creates a new WebVRController from a gamepad
  77768. * @param vrGamepad the gamepad that the WebVRController should be created from
  77769. */
  77770. function WebVRController(vrGamepad) {
  77771. var _this = _super.call(this, vrGamepad) || this;
  77772. // Observables
  77773. /**
  77774. * Fired when the trigger state has changed
  77775. */
  77776. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  77777. /**
  77778. * Fired when the main button state has changed
  77779. */
  77780. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  77781. /**
  77782. * Fired when the secondary button state has changed
  77783. */
  77784. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  77785. /**
  77786. * Fired when the pad state has changed
  77787. */
  77788. _this.onPadStateChangedObservable = new BABYLON.Observable();
  77789. /**
  77790. * Fired when controllers stick values have changed
  77791. */
  77792. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  77793. /**
  77794. * X and Y axis corrisponding to the controllers joystick
  77795. */
  77796. _this.pad = { x: 0, y: 0 };
  77797. // avoid GC, store state in a tmp object
  77798. _this._changes = {
  77799. pressChanged: false,
  77800. touchChanged: false,
  77801. valueChanged: false,
  77802. changed: false
  77803. };
  77804. _this._buttons = new Array(vrGamepad.buttons.length);
  77805. _this.hand = vrGamepad.hand;
  77806. return _this;
  77807. }
  77808. /**
  77809. * Fired when a controller button's state has changed
  77810. * @param callback the callback containing the button that was modified
  77811. */
  77812. WebVRController.prototype.onButtonStateChange = function (callback) {
  77813. this._onButtonStateChange = callback;
  77814. };
  77815. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  77816. /**
  77817. * The default controller model for the controller
  77818. */
  77819. get: function () {
  77820. return this._defaultModel;
  77821. },
  77822. enumerable: true,
  77823. configurable: true
  77824. });
  77825. /**
  77826. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  77827. */
  77828. WebVRController.prototype.update = function () {
  77829. _super.prototype.update.call(this);
  77830. for (var index = 0; index < this._buttons.length; index++) {
  77831. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  77832. }
  77833. ;
  77834. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  77835. this.pad.x = this.leftStick.x;
  77836. this.pad.y = this.leftStick.y;
  77837. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  77838. }
  77839. };
  77840. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  77841. if (!newState) {
  77842. newState = {
  77843. pressed: false,
  77844. touched: false,
  77845. value: 0
  77846. };
  77847. }
  77848. if (!currentState) {
  77849. this._buttons[buttonIndex] = {
  77850. pressed: newState.pressed,
  77851. touched: newState.touched,
  77852. value: newState.value
  77853. };
  77854. return;
  77855. }
  77856. this._checkChanges(newState, currentState);
  77857. if (this._changes.changed) {
  77858. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  77859. this._handleButtonChange(buttonIndex, newState, this._changes);
  77860. }
  77861. this._buttons[buttonIndex].pressed = newState.pressed;
  77862. this._buttons[buttonIndex].touched = newState.touched;
  77863. // oculus triggers are never 0, thou not touched.
  77864. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  77865. };
  77866. WebVRController.prototype._checkChanges = function (newState, currentState) {
  77867. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  77868. this._changes.touchChanged = newState.touched !== currentState.touched;
  77869. this._changes.valueChanged = newState.value !== currentState.value;
  77870. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  77871. return this._changes;
  77872. };
  77873. /**
  77874. * Disposes of th webVRCOntroller
  77875. */
  77876. WebVRController.prototype.dispose = function () {
  77877. _super.prototype.dispose.call(this);
  77878. this.onTriggerStateChangedObservable.clear();
  77879. this.onMainButtonStateChangedObservable.clear();
  77880. this.onSecondaryButtonStateChangedObservable.clear();
  77881. this.onPadStateChangedObservable.clear();
  77882. this.onPadValuesChangedObservable.clear();
  77883. };
  77884. return WebVRController;
  77885. }(BABYLON.PoseEnabledController));
  77886. BABYLON.WebVRController = WebVRController;
  77887. })(BABYLON || (BABYLON = {}));
  77888. //# sourceMappingURL=babylon.webVRController.js.map
  77889. var BABYLON;
  77890. (function (BABYLON) {
  77891. /**
  77892. * Oculus Touch Controller
  77893. */
  77894. var OculusTouchController = /** @class */ (function (_super) {
  77895. __extends(OculusTouchController, _super);
  77896. /**
  77897. * Creates a new OculusTouchController from a gamepad
  77898. * @param vrGamepad the gamepad that the controller should be created from
  77899. */
  77900. function OculusTouchController(vrGamepad) {
  77901. var _this = _super.call(this, vrGamepad) || this;
  77902. /**
  77903. * Fired when the secondary trigger on this controller is modified
  77904. */
  77905. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  77906. /**
  77907. * Fired when the thumb rest on this controller is modified
  77908. */
  77909. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  77910. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  77911. return _this;
  77912. }
  77913. /**
  77914. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77915. * @param scene scene in which to add meshes
  77916. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77917. */
  77918. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77919. var _this = this;
  77920. var meshName;
  77921. // Hand
  77922. if (this.hand === 'left') {
  77923. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  77924. }
  77925. else { // Right is the default if no hand is specified
  77926. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  77927. }
  77928. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  77929. /*
  77930. Parent Mesh name: oculus_touch_left
  77931. - body
  77932. - trigger
  77933. - thumbstick
  77934. - grip
  77935. - button_y
  77936. - button_x
  77937. - button_enter
  77938. */
  77939. _this._defaultModel = newMeshes[1];
  77940. _this.attachToMesh(_this._defaultModel);
  77941. if (meshLoaded) {
  77942. meshLoaded(_this._defaultModel);
  77943. }
  77944. });
  77945. };
  77946. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  77947. /**
  77948. * Fired when the A button on this controller is modified
  77949. */
  77950. get: function () {
  77951. if (this.hand === 'right') {
  77952. return this.onMainButtonStateChangedObservable;
  77953. }
  77954. else {
  77955. throw new Error('No A button on left hand');
  77956. }
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  77962. /**
  77963. * Fired when the B button on this controller is modified
  77964. */
  77965. get: function () {
  77966. if (this.hand === 'right') {
  77967. return this.onSecondaryButtonStateChangedObservable;
  77968. }
  77969. else {
  77970. throw new Error('No B button on left hand');
  77971. }
  77972. },
  77973. enumerable: true,
  77974. configurable: true
  77975. });
  77976. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  77977. /**
  77978. * Fired when the X button on this controller is modified
  77979. */
  77980. get: function () {
  77981. if (this.hand === 'left') {
  77982. return this.onMainButtonStateChangedObservable;
  77983. }
  77984. else {
  77985. throw new Error('No X button on right hand');
  77986. }
  77987. },
  77988. enumerable: true,
  77989. configurable: true
  77990. });
  77991. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  77992. /**
  77993. * Fired when the Y button on this controller is modified
  77994. */
  77995. get: function () {
  77996. if (this.hand === 'left') {
  77997. return this.onSecondaryButtonStateChangedObservable;
  77998. }
  77999. else {
  78000. throw new Error('No Y button on right hand');
  78001. }
  78002. },
  78003. enumerable: true,
  78004. configurable: true
  78005. });
  78006. /**
  78007. * Called once for each button that changed state since the last frame
  78008. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78009. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78010. * 2) secondary trigger (same)
  78011. * 3) A (right) X (left), touch, pressed = value
  78012. * 4) B / Y
  78013. * 5) thumb rest
  78014. * @param buttonIdx Which button index changed
  78015. * @param state New state of the button
  78016. * @param changes Which properties on the state changed since last frame
  78017. */
  78018. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78019. var notifyObject = state; //{ state: state, changes: changes };
  78020. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78021. switch (buttonIdx) {
  78022. case 0:
  78023. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78024. return;
  78025. case 1: // index trigger
  78026. if (this._defaultModel) {
  78027. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78028. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78029. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78030. }
  78031. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78032. return;
  78033. case 2: // secondary trigger
  78034. if (this._defaultModel) {
  78035. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78036. }
  78037. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78038. return;
  78039. case 3:
  78040. if (this._defaultModel) {
  78041. if (notifyObject.pressed) {
  78042. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78043. }
  78044. else {
  78045. (this._defaultModel.getChildren()[1]).position.y = 0;
  78046. }
  78047. }
  78048. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78049. return;
  78050. case 4:
  78051. if (this._defaultModel) {
  78052. if (notifyObject.pressed) {
  78053. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78054. }
  78055. else {
  78056. (this._defaultModel.getChildren()[2]).position.y = 0;
  78057. }
  78058. }
  78059. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78060. return;
  78061. case 5:
  78062. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78063. return;
  78064. }
  78065. };
  78066. /**
  78067. * Base Url for the controller model.
  78068. */
  78069. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78070. /**
  78071. * File name for the left controller model.
  78072. */
  78073. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78074. /**
  78075. * File name for the right controller model.
  78076. */
  78077. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78078. return OculusTouchController;
  78079. }(BABYLON.WebVRController));
  78080. BABYLON.OculusTouchController = OculusTouchController;
  78081. })(BABYLON || (BABYLON = {}));
  78082. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78083. var BABYLON;
  78084. (function (BABYLON) {
  78085. /**
  78086. * Vive Controller
  78087. */
  78088. var ViveController = /** @class */ (function (_super) {
  78089. __extends(ViveController, _super);
  78090. /**
  78091. * Creates a new ViveController from a gamepad
  78092. * @param vrGamepad the gamepad that the controller should be created from
  78093. */
  78094. function ViveController(vrGamepad) {
  78095. var _this = _super.call(this, vrGamepad) || this;
  78096. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78097. _this._invertLeftStickY = true;
  78098. return _this;
  78099. }
  78100. /**
  78101. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78102. * @param scene scene in which to add meshes
  78103. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78104. */
  78105. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78106. var _this = this;
  78107. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78108. /*
  78109. Parent Mesh name: ViveWand
  78110. - body
  78111. - r_gripper
  78112. - l_gripper
  78113. - menu_button
  78114. - system_button
  78115. - trackpad
  78116. - trigger
  78117. - LED
  78118. */
  78119. _this._defaultModel = newMeshes[1];
  78120. _this.attachToMesh(_this._defaultModel);
  78121. if (meshLoaded) {
  78122. meshLoaded(_this._defaultModel);
  78123. }
  78124. });
  78125. };
  78126. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78127. /**
  78128. * Fired when the left button on this controller is modified
  78129. */
  78130. get: function () {
  78131. return this.onMainButtonStateChangedObservable;
  78132. },
  78133. enumerable: true,
  78134. configurable: true
  78135. });
  78136. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78137. /**
  78138. * Fired when the right button on this controller is modified
  78139. */
  78140. get: function () {
  78141. return this.onMainButtonStateChangedObservable;
  78142. },
  78143. enumerable: true,
  78144. configurable: true
  78145. });
  78146. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78147. /**
  78148. * Fired when the menu button on this controller is modified
  78149. */
  78150. get: function () {
  78151. return this.onSecondaryButtonStateChangedObservable;
  78152. },
  78153. enumerable: true,
  78154. configurable: true
  78155. });
  78156. /**
  78157. * Called once for each button that changed state since the last frame
  78158. * Vive mapping:
  78159. * 0: touchpad
  78160. * 1: trigger
  78161. * 2: left AND right buttons
  78162. * 3: menu button
  78163. * @param buttonIdx Which button index changed
  78164. * @param state New state of the button
  78165. * @param changes Which properties on the state changed since last frame
  78166. */
  78167. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78168. var notifyObject = state; //{ state: state, changes: changes };
  78169. switch (buttonIdx) {
  78170. case 0:
  78171. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78172. return;
  78173. case 1: // index trigger
  78174. if (this._defaultModel) {
  78175. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78176. }
  78177. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78178. return;
  78179. case 2: // left AND right button
  78180. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78181. return;
  78182. case 3:
  78183. if (this._defaultModel) {
  78184. if (notifyObject.pressed) {
  78185. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78186. }
  78187. else {
  78188. (this._defaultModel.getChildren()[2]).position.y = 0;
  78189. }
  78190. }
  78191. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78192. return;
  78193. }
  78194. };
  78195. /**
  78196. * Base Url for the controller model.
  78197. */
  78198. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78199. /**
  78200. * File name for the controller model.
  78201. */
  78202. ViveController.MODEL_FILENAME = 'wand.babylon';
  78203. return ViveController;
  78204. }(BABYLON.WebVRController));
  78205. BABYLON.ViveController = ViveController;
  78206. })(BABYLON || (BABYLON = {}));
  78207. //# sourceMappingURL=babylon.viveController.js.map
  78208. var BABYLON;
  78209. (function (BABYLON) {
  78210. /**
  78211. * Generic Controller
  78212. */
  78213. var GenericController = /** @class */ (function (_super) {
  78214. __extends(GenericController, _super);
  78215. /**
  78216. * Creates a new GenericController from a gamepad
  78217. * @param vrGamepad the gamepad that the controller should be created from
  78218. */
  78219. function GenericController(vrGamepad) {
  78220. return _super.call(this, vrGamepad) || this;
  78221. }
  78222. /**
  78223. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78224. * @param scene scene in which to add meshes
  78225. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78226. */
  78227. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78228. var _this = this;
  78229. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78230. _this._defaultModel = newMeshes[1];
  78231. _this.attachToMesh(_this._defaultModel);
  78232. if (meshLoaded) {
  78233. meshLoaded(_this._defaultModel);
  78234. }
  78235. });
  78236. };
  78237. /**
  78238. * Called once for each button that changed state since the last frame
  78239. * @param buttonIdx Which button index changed
  78240. * @param state New state of the button
  78241. * @param changes Which properties on the state changed since last frame
  78242. */
  78243. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78244. console.log("Button id: " + buttonIdx + "state: ");
  78245. console.dir(state);
  78246. };
  78247. /**
  78248. * Base Url for the controller model.
  78249. */
  78250. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78251. /**
  78252. * File name for the controller model.
  78253. */
  78254. GenericController.MODEL_FILENAME = 'generic.babylon';
  78255. return GenericController;
  78256. }(BABYLON.WebVRController));
  78257. BABYLON.GenericController = GenericController;
  78258. })(BABYLON || (BABYLON = {}));
  78259. //# sourceMappingURL=babylon.genericController.js.map
  78260. var BABYLON;
  78261. (function (BABYLON) {
  78262. /**
  78263. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78264. */
  78265. var LoadedMeshInfo = /** @class */ (function () {
  78266. function LoadedMeshInfo() {
  78267. /**
  78268. * Map of the button meshes contained in the controller
  78269. */
  78270. this.buttonMeshes = {};
  78271. /**
  78272. * Map of the axis meshes contained in the controller
  78273. */
  78274. this.axisMeshes = {};
  78275. }
  78276. return LoadedMeshInfo;
  78277. }());
  78278. /**
  78279. * Defines the WindowsMotionController object that the state of the windows motion controller
  78280. */
  78281. var WindowsMotionController = /** @class */ (function (_super) {
  78282. __extends(WindowsMotionController, _super);
  78283. /**
  78284. * Creates a new WindowsMotionController from a gamepad
  78285. * @param vrGamepad the gamepad that the controller should be created from
  78286. */
  78287. function WindowsMotionController(vrGamepad) {
  78288. var _this = _super.call(this, vrGamepad) || this;
  78289. _this._mapping = {
  78290. // Semantic button names
  78291. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78292. // A mapping of the button name to glTF model node name
  78293. // that should be transformed by button value.
  78294. buttonMeshNames: {
  78295. 'trigger': 'SELECT',
  78296. 'menu': 'MENU',
  78297. 'grip': 'GRASP',
  78298. 'thumbstick': 'THUMBSTICK_PRESS',
  78299. 'trackpad': 'TOUCHPAD_PRESS'
  78300. },
  78301. // This mapping is used to translate from the Motion Controller to Babylon semantics
  78302. buttonObservableNames: {
  78303. 'trigger': 'onTriggerStateChangedObservable',
  78304. 'menu': 'onSecondaryButtonStateChangedObservable',
  78305. 'grip': 'onMainButtonStateChangedObservable',
  78306. 'thumbstick': 'onPadStateChangedObservable',
  78307. 'trackpad': 'onTrackpadChangedObservable'
  78308. },
  78309. // A mapping of the axis name to glTF model node name
  78310. // that should be transformed by axis value.
  78311. // This array mirrors the browserGamepad.axes array, such that
  78312. // the mesh corresponding to axis 0 is in this array index 0.
  78313. axisMeshNames: [
  78314. 'THUMBSTICK_X',
  78315. 'THUMBSTICK_Y',
  78316. 'TOUCHPAD_TOUCH_X',
  78317. 'TOUCHPAD_TOUCH_Y'
  78318. ],
  78319. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  78320. };
  78321. /**
  78322. * Fired when the trackpad on this controller is clicked
  78323. */
  78324. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  78325. /**
  78326. * Fired when the trackpad on this controller is modified
  78327. */
  78328. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  78329. /**
  78330. * The current x and y values of this controller's trackpad
  78331. */
  78332. _this.trackpad = { x: 0, y: 0 };
  78333. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  78334. _this._loadedMeshInfo = null;
  78335. return _this;
  78336. }
  78337. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  78338. /**
  78339. * Fired when the trigger on this controller is modified
  78340. */
  78341. get: function () {
  78342. return this.onTriggerStateChangedObservable;
  78343. },
  78344. enumerable: true,
  78345. configurable: true
  78346. });
  78347. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  78348. /**
  78349. * Fired when the menu button on this controller is modified
  78350. */
  78351. get: function () {
  78352. return this.onSecondaryButtonStateChangedObservable;
  78353. },
  78354. enumerable: true,
  78355. configurable: true
  78356. });
  78357. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  78358. /**
  78359. * Fired when the grip button on this controller is modified
  78360. */
  78361. get: function () {
  78362. return this.onMainButtonStateChangedObservable;
  78363. },
  78364. enumerable: true,
  78365. configurable: true
  78366. });
  78367. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  78368. /**
  78369. * Fired when the thumbstick button on this controller is modified
  78370. */
  78371. get: function () {
  78372. return this.onPadStateChangedObservable;
  78373. },
  78374. enumerable: true,
  78375. configurable: true
  78376. });
  78377. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  78378. /**
  78379. * Fired when the touchpad button on this controller is modified
  78380. */
  78381. get: function () {
  78382. return this.onTrackpadChangedObservable;
  78383. },
  78384. enumerable: true,
  78385. configurable: true
  78386. });
  78387. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  78388. /**
  78389. * Fired when the touchpad values on this controller are modified
  78390. */
  78391. get: function () {
  78392. return this.onTrackpadValuesChangedObservable;
  78393. },
  78394. enumerable: true,
  78395. configurable: true
  78396. });
  78397. WindowsMotionController.prototype._updateTrackpad = function () {
  78398. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  78399. this.trackpad.x = this.browserGamepad["axes"][2];
  78400. this.trackpad.y = this.browserGamepad["axes"][3];
  78401. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  78402. }
  78403. };
  78404. /**
  78405. * Called once per frame by the engine.
  78406. */
  78407. WindowsMotionController.prototype.update = function () {
  78408. _super.prototype.update.call(this);
  78409. if (this.browserGamepad.axes) {
  78410. this._updateTrackpad();
  78411. // Only need to animate axes if there is a loaded mesh
  78412. if (this._loadedMeshInfo) {
  78413. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  78414. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  78415. }
  78416. }
  78417. }
  78418. };
  78419. /**
  78420. * Called once for each button that changed state since the last frame
  78421. * @param buttonIdx Which button index changed
  78422. * @param state New state of the button
  78423. * @param changes Which properties on the state changed since last frame
  78424. */
  78425. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78426. var buttonName = this._mapping.buttons[buttonIdx];
  78427. if (!buttonName) {
  78428. return;
  78429. }
  78430. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  78431. this._updateTrackpad();
  78432. // Only emit events for buttons that we know how to map from index to name
  78433. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  78434. if (observable) {
  78435. observable.notifyObservers(state);
  78436. }
  78437. this._lerpButtonTransform(buttonName, state.value);
  78438. };
  78439. /**
  78440. * Moves the buttons on the controller mesh based on their current state
  78441. * @param buttonName the name of the button to move
  78442. * @param buttonValue the value of the button which determines the buttons new position
  78443. */
  78444. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  78445. // If there is no loaded mesh, there is nothing to transform.
  78446. if (!this._loadedMeshInfo) {
  78447. return;
  78448. }
  78449. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  78450. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78451. return;
  78452. }
  78453. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  78454. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  78455. };
  78456. /**
  78457. * Moves the axis on the controller mesh based on its current state
  78458. * @param axis the index of the axis
  78459. * @param axisValue the value of the axis which determines the meshes new position
  78460. * @hidden
  78461. */
  78462. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  78463. if (!this._loadedMeshInfo) {
  78464. return;
  78465. }
  78466. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  78467. if (!meshInfo) {
  78468. return;
  78469. }
  78470. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78471. return;
  78472. }
  78473. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  78474. var lerpValue = axisValue * 0.5 + 0.5;
  78475. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  78476. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  78477. };
  78478. /**
  78479. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78480. * @param scene scene in which to add meshes
  78481. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78482. */
  78483. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  78484. var _this = this;
  78485. if (forceDefault === void 0) { forceDefault = false; }
  78486. var path;
  78487. var filename;
  78488. // Checking if GLB loader is present
  78489. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  78490. // Determine the device specific folder based on the ID suffix
  78491. var device = 'default';
  78492. if (this.id && !forceDefault) {
  78493. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  78494. device = ((match && match[0]) || device);
  78495. }
  78496. // Hand
  78497. if (this.hand === 'left') {
  78498. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  78499. }
  78500. else { // Right is the default if no hand is specified
  78501. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  78502. }
  78503. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  78504. }
  78505. else {
  78506. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  78507. path = BABYLON.GenericController.MODEL_BASE_URL;
  78508. filename = BABYLON.GenericController.MODEL_FILENAME;
  78509. }
  78510. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  78511. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  78512. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  78513. if (!_this._loadedMeshInfo) {
  78514. return;
  78515. }
  78516. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  78517. _this.attachToMesh(_this._defaultModel);
  78518. if (meshLoaded) {
  78519. meshLoaded(_this._defaultModel);
  78520. }
  78521. }, null, function (scene, message) {
  78522. BABYLON.Tools.Log(message);
  78523. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  78524. if (!forceDefault) {
  78525. _this.initControllerMesh(scene, meshLoaded, true);
  78526. }
  78527. });
  78528. };
  78529. /**
  78530. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  78531. * can be transformed by button presses and axes values, based on this._mapping.
  78532. *
  78533. * @param scene scene in which the meshes exist
  78534. * @param meshes list of meshes that make up the controller model to process
  78535. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  78536. */
  78537. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  78538. var loadedMeshInfo = null;
  78539. // Create a new mesh to contain the glTF hierarchy
  78540. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  78541. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  78542. var childMesh = null;
  78543. for (var i = 0; i < meshes.length; i++) {
  78544. var mesh = meshes[i];
  78545. if (!mesh.parent) {
  78546. // Exclude controller meshes from picking results
  78547. mesh.isPickable = false;
  78548. // Handle root node, attach to the new parentMesh
  78549. childMesh = mesh;
  78550. break;
  78551. }
  78552. }
  78553. if (childMesh) {
  78554. childMesh.setParent(parentMesh);
  78555. // Create our mesh info. Note that this method will always return non-null.
  78556. loadedMeshInfo = this.createMeshInfo(parentMesh);
  78557. }
  78558. else {
  78559. BABYLON.Tools.Warn('Could not find root node in model file.');
  78560. }
  78561. return loadedMeshInfo;
  78562. };
  78563. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  78564. var loadedMeshInfo = new LoadedMeshInfo();
  78565. var i;
  78566. loadedMeshInfo.rootNode = rootNode;
  78567. // Reset the caches
  78568. loadedMeshInfo.buttonMeshes = {};
  78569. loadedMeshInfo.axisMeshes = {};
  78570. // Button Meshes
  78571. for (i = 0; i < this._mapping.buttons.length; i++) {
  78572. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  78573. if (!buttonMeshName) {
  78574. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  78575. continue;
  78576. }
  78577. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  78578. if (!buttonMesh) {
  78579. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  78580. continue;
  78581. }
  78582. var buttonMeshInfo = {
  78583. index: i,
  78584. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  78585. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  78586. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  78587. };
  78588. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  78589. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  78590. }
  78591. else {
  78592. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  78593. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  78594. '(VALUE: ' + !!buttonMeshInfo.value +
  78595. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  78596. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  78597. ')');
  78598. }
  78599. }
  78600. // Axis Meshes
  78601. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  78602. var axisMeshName = this._mapping.axisMeshNames[i];
  78603. if (!axisMeshName) {
  78604. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  78605. continue;
  78606. }
  78607. var axisMesh = getChildByName(rootNode, axisMeshName);
  78608. if (!axisMesh) {
  78609. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  78610. continue;
  78611. }
  78612. var axisMeshInfo = {
  78613. index: i,
  78614. value: getImmediateChildByName(axisMesh, 'VALUE'),
  78615. min: getImmediateChildByName(axisMesh, 'MIN'),
  78616. max: getImmediateChildByName(axisMesh, 'MAX')
  78617. };
  78618. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  78619. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  78620. }
  78621. else {
  78622. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  78623. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  78624. '(VALUE: ' + !!axisMeshInfo.value +
  78625. ', MIN: ' + !!axisMeshInfo.min +
  78626. ', MAX:' + !!axisMeshInfo.max +
  78627. ')');
  78628. }
  78629. }
  78630. // Pointing Ray
  78631. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  78632. if (!loadedMeshInfo.pointingPoseNode) {
  78633. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  78634. }
  78635. else {
  78636. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  78637. }
  78638. return loadedMeshInfo;
  78639. // Look through all children recursively. This will return null if no mesh exists with the given name.
  78640. function getChildByName(node, name) {
  78641. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  78642. }
  78643. // Look through only immediate children. This will return null if no mesh exists with the given name.
  78644. function getImmediateChildByName(node, name) {
  78645. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  78646. }
  78647. };
  78648. /**
  78649. * Gets the ray of the controller in the direction the controller is pointing
  78650. * @param length the length the resulting ray should be
  78651. * @returns a ray in the direction the controller is pointing
  78652. */
  78653. WindowsMotionController.prototype.getForwardRay = function (length) {
  78654. if (length === void 0) { length = 100; }
  78655. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  78656. return _super.prototype.getForwardRay.call(this, length);
  78657. }
  78658. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  78659. var origin = m.getTranslation();
  78660. var forward = new BABYLON.Vector3(0, 0, -1);
  78661. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78662. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78663. return new BABYLON.Ray(origin, direction, length);
  78664. };
  78665. /**
  78666. * Disposes of the controller
  78667. */
  78668. WindowsMotionController.prototype.dispose = function () {
  78669. _super.prototype.dispose.call(this);
  78670. this.onTrackpadChangedObservable.clear();
  78671. };
  78672. /**
  78673. * The base url used to load the left and right controller models
  78674. */
  78675. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  78676. /**
  78677. * The name of the left controller model file
  78678. */
  78679. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  78680. /**
  78681. * The name of the right controller model file
  78682. */
  78683. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  78684. /**
  78685. * The controller name prefix for this controller type
  78686. */
  78687. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  78688. /**
  78689. * The controller id pattern for this controller type
  78690. */
  78691. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  78692. return WindowsMotionController;
  78693. }(BABYLON.WebVRController));
  78694. BABYLON.WindowsMotionController = WindowsMotionController;
  78695. })(BABYLON || (BABYLON = {}));
  78696. //# sourceMappingURL=babylon.windowsMotionController.js.map
  78697. var BABYLON;
  78698. (function (BABYLON) {
  78699. /**
  78700. * Gear VR Controller
  78701. */
  78702. var GearVRController = /** @class */ (function (_super) {
  78703. __extends(GearVRController, _super);
  78704. /**
  78705. * Creates a new GearVRController from a gamepad
  78706. * @param vrGamepad the gamepad that the controller should be created from
  78707. */
  78708. function GearVRController(vrGamepad) {
  78709. var _this = _super.call(this, vrGamepad) || this;
  78710. _this._buttonIndexToObservableNameMap = [
  78711. 'onTrackpadChangedObservable',
  78712. 'onTriggerStateChangedObservable' // Trigger
  78713. ];
  78714. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  78715. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  78716. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  78717. _this._disableTrackPosition(_this._calculatedPosition);
  78718. return _this;
  78719. }
  78720. /**
  78721. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78722. * @param scene scene in which to add meshes
  78723. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78724. */
  78725. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78726. var _this = this;
  78727. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  78728. // Offset the controller so it will rotate around the users wrist
  78729. var mesh = new BABYLON.Mesh("", scene);
  78730. newMeshes[1].parent = mesh;
  78731. newMeshes[1].position.z = -0.15;
  78732. _this._defaultModel = mesh;
  78733. _this.attachToMesh(_this._defaultModel);
  78734. if (meshLoaded) {
  78735. meshLoaded(_this._defaultModel);
  78736. }
  78737. });
  78738. };
  78739. /**
  78740. * Called once for each button that changed state since the last frame
  78741. * @param buttonIdx Which button index changed
  78742. * @param state New state of the button
  78743. * @param changes Which properties on the state changed since last frame
  78744. */
  78745. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78746. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  78747. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  78748. // Only emit events for buttons that we know how to map from index to observable
  78749. var observable = this[observableName];
  78750. if (observable) {
  78751. observable.notifyObservers(state);
  78752. }
  78753. }
  78754. };
  78755. /**
  78756. * Base Url for the controller model.
  78757. */
  78758. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78759. /**
  78760. * File name for the controller model.
  78761. */
  78762. GearVRController.MODEL_FILENAME = 'generic.babylon';
  78763. /**
  78764. * Gamepad Id prefix used to identify this controller.
  78765. */
  78766. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  78767. return GearVRController;
  78768. }(BABYLON.WebVRController));
  78769. BABYLON.GearVRController = GearVRController;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.gearVRController.js.map
  78772. var BABYLON;
  78773. (function (BABYLON) {
  78774. /**
  78775. * Google Daydream controller
  78776. */
  78777. var DaydreamController = /** @class */ (function (_super) {
  78778. __extends(DaydreamController, _super);
  78779. /**
  78780. * Creates a new DaydreamController from a gamepad
  78781. * @param vrGamepad the gamepad that the controller should be created from
  78782. */
  78783. function DaydreamController(vrGamepad) {
  78784. var _this = _super.call(this, vrGamepad) || this;
  78785. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  78786. return _this;
  78787. }
  78788. /**
  78789. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78790. * @param scene scene in which to add meshes
  78791. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78792. */
  78793. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78794. var _this = this;
  78795. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  78796. _this._defaultModel = newMeshes[1];
  78797. _this.attachToMesh(_this._defaultModel);
  78798. if (meshLoaded) {
  78799. meshLoaded(_this._defaultModel);
  78800. }
  78801. });
  78802. };
  78803. /**
  78804. * Called once for each button that changed state since the last frame
  78805. * @param buttonIdx Which button index changed
  78806. * @param state New state of the button
  78807. * @param changes Which properties on the state changed since last frame
  78808. */
  78809. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78810. // Daydream controller only has 1 GamepadButton (on the trackpad).
  78811. if (buttonIdx === 0) {
  78812. var observable = this.onTriggerStateChangedObservable;
  78813. if (observable) {
  78814. observable.notifyObservers(state);
  78815. }
  78816. }
  78817. else {
  78818. // If the app or home buttons are ever made available
  78819. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  78820. }
  78821. };
  78822. /**
  78823. * Base Url for the controller model.
  78824. */
  78825. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78826. /**
  78827. * File name for the controller model.
  78828. */
  78829. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  78830. /**
  78831. * Gamepad Id prefix used to identify Daydream Controller.
  78832. */
  78833. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  78834. return DaydreamController;
  78835. }(BABYLON.WebVRController));
  78836. BABYLON.DaydreamController = DaydreamController;
  78837. })(BABYLON || (BABYLON = {}));
  78838. //# sourceMappingURL=babylon.daydreamController.js.map
  78839. var BABYLON;
  78840. (function (BABYLON) {
  78841. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  78842. get: function () {
  78843. if (!this._gamepadManager) {
  78844. this._gamepadManager = new BABYLON.GamepadManager(this);
  78845. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  78846. if (!component) {
  78847. component = new GamepadSystemSceneComponent(this);
  78848. this._addComponent(component);
  78849. }
  78850. }
  78851. return this._gamepadManager;
  78852. },
  78853. enumerable: true,
  78854. configurable: true
  78855. });
  78856. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  78857. this.add(new BABYLON.FreeCameraGamepadInput());
  78858. return this;
  78859. };
  78860. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  78861. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  78862. return this;
  78863. };
  78864. /**
  78865. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  78866. */
  78867. var GamepadSystemSceneComponent = /** @class */ (function () {
  78868. /**
  78869. * Creates a new instance of the component for the given scene
  78870. * @param scene Defines the scene to register the component in
  78871. */
  78872. function GamepadSystemSceneComponent(scene) {
  78873. /**
  78874. * The component name helpfull to identify the component in the list of scene components.
  78875. */
  78876. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  78877. this.scene = scene;
  78878. }
  78879. /**
  78880. * Registers the component in a given scene
  78881. */
  78882. GamepadSystemSceneComponent.prototype.register = function () {
  78883. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  78884. };
  78885. /**
  78886. * Rebuilds the elements related to this component in case of
  78887. * context lost for instance.
  78888. */
  78889. GamepadSystemSceneComponent.prototype.rebuild = function () {
  78890. // Nothing to do for gamepads
  78891. };
  78892. /**
  78893. * Disposes the component and the associated ressources
  78894. */
  78895. GamepadSystemSceneComponent.prototype.dispose = function () {
  78896. var gamepadManager = this.scene._gamepadManager;
  78897. if (gamepadManager) {
  78898. gamepadManager.dispose();
  78899. this.scene._gamepadManager = null;
  78900. }
  78901. };
  78902. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  78903. var gamepadManager = this.scene._gamepadManager;
  78904. if (gamepadManager && gamepadManager._isMonitoring) {
  78905. gamepadManager._checkGamepadsStatus();
  78906. }
  78907. };
  78908. return GamepadSystemSceneComponent;
  78909. }());
  78910. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  78911. })(BABYLON || (BABYLON = {}));
  78912. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  78913. var BABYLON;
  78914. (function (BABYLON) {
  78915. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  78916. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  78917. });
  78918. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  78919. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  78920. });
  78921. /**
  78922. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  78923. * an arc rotate version arcFollowCamera are available.
  78924. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78925. */
  78926. var FollowCamera = /** @class */ (function (_super) {
  78927. __extends(FollowCamera, _super);
  78928. /**
  78929. * Instantiates the follow camera.
  78930. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78931. * @param name Define the name of the camera in the scene
  78932. * @param position Define the position of the camera
  78933. * @param scene Define the scene the camera belong to
  78934. * @param lockedTarget Define the target of the camera
  78935. */
  78936. function FollowCamera(name, position, scene, lockedTarget) {
  78937. if (lockedTarget === void 0) { lockedTarget = null; }
  78938. var _this = _super.call(this, name, position, scene) || this;
  78939. /**
  78940. * Distance the follow camera should follow an object at
  78941. */
  78942. _this.radius = 12;
  78943. /**
  78944. * Define a rotation offset between the camera and the object it follows
  78945. */
  78946. _this.rotationOffset = 0;
  78947. /**
  78948. * Define a height offset between the camera and the object it follows.
  78949. * It can help following an object from the top (like a car chaing a plane)
  78950. */
  78951. _this.heightOffset = 4;
  78952. /**
  78953. * Define how fast the camera can accelerate to follow it s target.
  78954. */
  78955. _this.cameraAcceleration = 0.05;
  78956. /**
  78957. * Define the speed limit of the camera following an object.
  78958. */
  78959. _this.maxCameraSpeed = 20;
  78960. _this.lockedTarget = lockedTarget;
  78961. return _this;
  78962. }
  78963. FollowCamera.prototype._follow = function (cameraTarget) {
  78964. if (!cameraTarget)
  78965. return;
  78966. var yRotation;
  78967. if (cameraTarget.rotationQuaternion) {
  78968. var rotMatrix = new BABYLON.Matrix();
  78969. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  78970. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  78971. }
  78972. else {
  78973. yRotation = cameraTarget.rotation.y;
  78974. }
  78975. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  78976. var targetPosition = cameraTarget.getAbsolutePosition();
  78977. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  78978. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  78979. var dx = targetX - this.position.x;
  78980. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  78981. var dz = (targetZ) - this.position.z;
  78982. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  78983. var vy = dy * this.cameraAcceleration;
  78984. var vz = dz * this.cameraAcceleration * 2;
  78985. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  78986. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78987. }
  78988. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  78989. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78990. }
  78991. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  78992. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78993. }
  78994. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  78995. this.setTarget(targetPosition);
  78996. };
  78997. /** @hidden */
  78998. FollowCamera.prototype._checkInputs = function () {
  78999. _super.prototype._checkInputs.call(this);
  79000. if (this.lockedTarget) {
  79001. this._follow(this.lockedTarget);
  79002. }
  79003. };
  79004. /**
  79005. * Gets the camera class name.
  79006. * @returns the class name
  79007. */
  79008. FollowCamera.prototype.getClassName = function () {
  79009. return "FollowCamera";
  79010. };
  79011. __decorate([
  79012. BABYLON.serialize()
  79013. ], FollowCamera.prototype, "radius", void 0);
  79014. __decorate([
  79015. BABYLON.serialize()
  79016. ], FollowCamera.prototype, "rotationOffset", void 0);
  79017. __decorate([
  79018. BABYLON.serialize()
  79019. ], FollowCamera.prototype, "heightOffset", void 0);
  79020. __decorate([
  79021. BABYLON.serialize()
  79022. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79023. __decorate([
  79024. BABYLON.serialize()
  79025. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79026. __decorate([
  79027. BABYLON.serializeAsMeshReference("lockedTargetId")
  79028. ], FollowCamera.prototype, "lockedTarget", void 0);
  79029. return FollowCamera;
  79030. }(BABYLON.TargetCamera));
  79031. BABYLON.FollowCamera = FollowCamera;
  79032. /**
  79033. * Arc Rotate version of the follow camera.
  79034. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79035. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79036. */
  79037. var ArcFollowCamera = /** @class */ (function (_super) {
  79038. __extends(ArcFollowCamera, _super);
  79039. /**
  79040. * Instantiates a new ArcFollowCamera
  79041. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79042. * @param name Define the name of the camera
  79043. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79044. * @param beta Define the rotation angle of the camera around the elevation axis
  79045. * @param radius Define the radius of the camera from its target point
  79046. * @param target Define the target of the camera
  79047. * @param scene Define the scene the camera belongs to
  79048. */
  79049. function ArcFollowCamera(name,
  79050. /** The longitudinal angle of the camera */
  79051. alpha,
  79052. /** The latitudinal angle of the camera */
  79053. beta,
  79054. /** The radius of the camera from its target */
  79055. radius,
  79056. /** Define the camera target (the messh it should follow) */
  79057. target, scene) {
  79058. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79059. _this.alpha = alpha;
  79060. _this.beta = beta;
  79061. _this.radius = radius;
  79062. _this.target = target;
  79063. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79064. _this._follow();
  79065. return _this;
  79066. }
  79067. ArcFollowCamera.prototype._follow = function () {
  79068. if (!this.target) {
  79069. return;
  79070. }
  79071. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79072. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79073. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79074. var targetPosition = this.target.getAbsolutePosition();
  79075. this.position = targetPosition.add(this._cartesianCoordinates);
  79076. this.setTarget(targetPosition);
  79077. };
  79078. /** @hidden */
  79079. ArcFollowCamera.prototype._checkInputs = function () {
  79080. _super.prototype._checkInputs.call(this);
  79081. this._follow();
  79082. };
  79083. /**
  79084. * Returns the class name of the object.
  79085. * It is mostly used internally for serialization purposes.
  79086. */
  79087. ArcFollowCamera.prototype.getClassName = function () {
  79088. return "ArcFollowCamera";
  79089. };
  79090. return ArcFollowCamera;
  79091. }(BABYLON.TargetCamera));
  79092. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79093. })(BABYLON || (BABYLON = {}));
  79094. //# sourceMappingURL=babylon.followCamera.js.map
  79095. var BABYLON;
  79096. (function (BABYLON) {
  79097. /**
  79098. * 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,
  79099. * which still works and will still be found in many Playgrounds.
  79100. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79101. */
  79102. var UniversalCamera = /** @class */ (function (_super) {
  79103. __extends(UniversalCamera, _super);
  79104. /**
  79105. * 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,
  79106. * which still works and will still be found in many Playgrounds.
  79107. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79108. * @param name Define the name of the camera in the scene
  79109. * @param position Define the start position of the camera in the scene
  79110. * @param scene Define the scene the camera belongs to
  79111. */
  79112. function UniversalCamera(name, position, scene) {
  79113. var _this = _super.call(this, name, position, scene) || this;
  79114. _this.inputs.addGamepad();
  79115. return _this;
  79116. }
  79117. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79118. /**
  79119. * Defines the gamepad rotation sensiblity.
  79120. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79121. */
  79122. get: function () {
  79123. var gamepad = this.inputs.attached["gamepad"];
  79124. if (gamepad)
  79125. return gamepad.gamepadAngularSensibility;
  79126. return 0;
  79127. },
  79128. set: function (value) {
  79129. var gamepad = this.inputs.attached["gamepad"];
  79130. if (gamepad)
  79131. gamepad.gamepadAngularSensibility = value;
  79132. },
  79133. enumerable: true,
  79134. configurable: true
  79135. });
  79136. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79137. /**
  79138. * Defines the gamepad move sensiblity.
  79139. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79140. */
  79141. get: function () {
  79142. var gamepad = this.inputs.attached["gamepad"];
  79143. if (gamepad)
  79144. return gamepad.gamepadMoveSensibility;
  79145. return 0;
  79146. },
  79147. set: function (value) {
  79148. var gamepad = this.inputs.attached["gamepad"];
  79149. if (gamepad)
  79150. gamepad.gamepadMoveSensibility = value;
  79151. },
  79152. enumerable: true,
  79153. configurable: true
  79154. });
  79155. /**
  79156. * Gets the current object class name.
  79157. * @return the class name
  79158. */
  79159. UniversalCamera.prototype.getClassName = function () {
  79160. return "UniversalCamera";
  79161. };
  79162. return UniversalCamera;
  79163. }(BABYLON.TouchCamera));
  79164. BABYLON.UniversalCamera = UniversalCamera;
  79165. })(BABYLON || (BABYLON = {}));
  79166. //# sourceMappingURL=babylon.universalCamera.js.map
  79167. var BABYLON;
  79168. (function (BABYLON) {
  79169. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79170. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79171. });
  79172. /**
  79173. * This represents a FPS type of camera. This is only here for back compat purpose.
  79174. * Please use the UniversalCamera instead as both are identical.
  79175. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79176. */
  79177. var GamepadCamera = /** @class */ (function (_super) {
  79178. __extends(GamepadCamera, _super);
  79179. /**
  79180. * Instantiates a new Gamepad Camera
  79181. * This represents a FPS type of camera. This is only here for back compat purpose.
  79182. * Please use the UniversalCamera instead as both are identical.
  79183. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79184. * @param name Define the name of the camera in the scene
  79185. * @param position Define the start position of the camera in the scene
  79186. * @param scene Define the scene the camera belongs to
  79187. */
  79188. function GamepadCamera(name, position, scene) {
  79189. return _super.call(this, name, position, scene) || this;
  79190. }
  79191. /**
  79192. * Gets the current object class name.
  79193. * @return the class name
  79194. */
  79195. GamepadCamera.prototype.getClassName = function () {
  79196. return "GamepadCamera";
  79197. };
  79198. return GamepadCamera;
  79199. }(BABYLON.UniversalCamera));
  79200. BABYLON.GamepadCamera = GamepadCamera;
  79201. })(BABYLON || (BABYLON = {}));
  79202. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79203. var BABYLON;
  79204. (function (BABYLON) {
  79205. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79206. function PostProcessRenderPipelineManager() {
  79207. this._renderPipelines = {};
  79208. }
  79209. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79210. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79211. };
  79212. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79213. if (unique === void 0) { unique = false; }
  79214. var renderPipeline = this._renderPipelines[renderPipelineName];
  79215. if (!renderPipeline) {
  79216. return;
  79217. }
  79218. renderPipeline._attachCameras(cameras, unique);
  79219. };
  79220. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79221. var renderPipeline = this._renderPipelines[renderPipelineName];
  79222. if (!renderPipeline) {
  79223. return;
  79224. }
  79225. renderPipeline._detachCameras(cameras);
  79226. };
  79227. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79228. var renderPipeline = this._renderPipelines[renderPipelineName];
  79229. if (!renderPipeline) {
  79230. return;
  79231. }
  79232. renderPipeline._enableEffect(renderEffectName, cameras);
  79233. };
  79234. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79235. var renderPipeline = this._renderPipelines[renderPipelineName];
  79236. if (!renderPipeline) {
  79237. return;
  79238. }
  79239. renderPipeline._disableEffect(renderEffectName, cameras);
  79240. };
  79241. PostProcessRenderPipelineManager.prototype.update = function () {
  79242. for (var renderPipelineName in this._renderPipelines) {
  79243. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79244. var pipeline = this._renderPipelines[renderPipelineName];
  79245. if (!pipeline.isSupported) {
  79246. pipeline.dispose();
  79247. delete this._renderPipelines[renderPipelineName];
  79248. }
  79249. else {
  79250. pipeline._update();
  79251. }
  79252. }
  79253. }
  79254. };
  79255. /** @hidden */
  79256. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79257. for (var renderPipelineName in this._renderPipelines) {
  79258. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79259. var pipeline = this._renderPipelines[renderPipelineName];
  79260. pipeline._rebuild();
  79261. }
  79262. }
  79263. };
  79264. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79265. for (var renderPipelineName in this._renderPipelines) {
  79266. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79267. var pipeline = this._renderPipelines[renderPipelineName];
  79268. pipeline.dispose();
  79269. }
  79270. }
  79271. };
  79272. return PostProcessRenderPipelineManager;
  79273. }());
  79274. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79275. })(BABYLON || (BABYLON = {}));
  79276. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79277. var BABYLON;
  79278. (function (BABYLON) {
  79279. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79280. get: function () {
  79281. if (!this._postProcessRenderPipelineManager) {
  79282. // Register the G Buffer component to the scene.
  79283. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79284. if (!component) {
  79285. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79286. this._addComponent(component);
  79287. }
  79288. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  79289. }
  79290. return this._postProcessRenderPipelineManager;
  79291. },
  79292. enumerable: true,
  79293. configurable: true
  79294. });
  79295. /**
  79296. * Defines the Render Pipeline scene component responsible to rendering pipelines
  79297. */
  79298. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  79299. /**
  79300. * Creates a new instance of the component for the given scene
  79301. * @param scene Defines the scene to register the component in
  79302. */
  79303. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  79304. /**
  79305. * The component name helpfull to identify the component in the list of scene components.
  79306. */
  79307. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  79308. this.scene = scene;
  79309. }
  79310. /**
  79311. * Registers the component in a given scene
  79312. */
  79313. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  79314. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  79315. };
  79316. /**
  79317. * Rebuilds the elements related to this component in case of
  79318. * context lost for instance.
  79319. */
  79320. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  79321. if (this.scene._postProcessRenderPipelineManager) {
  79322. this.scene._postProcessRenderPipelineManager._rebuild();
  79323. }
  79324. };
  79325. /**
  79326. * Disposes the component and the associated ressources
  79327. */
  79328. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  79329. if (this.scene._postProcessRenderPipelineManager) {
  79330. this.scene._postProcessRenderPipelineManager.dispose();
  79331. }
  79332. };
  79333. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79334. if (this.scene._postProcessRenderPipelineManager) {
  79335. this.scene._postProcessRenderPipelineManager.update();
  79336. }
  79337. };
  79338. return PostProcessRenderPipelineManagerSceneComponent;
  79339. }());
  79340. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  79341. })(BABYLON || (BABYLON = {}));
  79342. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  79343. var BABYLON;
  79344. (function (BABYLON) {
  79345. /**
  79346. * This represents a set of one or more post processes in Babylon.
  79347. * A post process can be used to apply a shader to a texture after it is rendered.
  79348. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  79349. */
  79350. var PostProcessRenderEffect = /** @class */ (function () {
  79351. /**
  79352. * Instantiates a post process render effect.
  79353. * A post process can be used to apply a shader to a texture after it is rendered.
  79354. * @param engine The engine the effect is tied to
  79355. * @param name The name of the effect
  79356. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  79357. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  79358. */
  79359. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  79360. this._name = name;
  79361. this._singleInstance = singleInstance || true;
  79362. this._getPostProcesses = getPostProcesses;
  79363. this._cameras = {};
  79364. this._indicesForCamera = {};
  79365. this._postProcesses = {};
  79366. }
  79367. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  79368. /**
  79369. * Checks if all the post processes in the effect are supported.
  79370. */
  79371. get: function () {
  79372. for (var index in this._postProcesses) {
  79373. if (this._postProcesses.hasOwnProperty(index)) {
  79374. var pps = this._postProcesses[index];
  79375. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  79376. if (!pps[ppIndex].isSupported) {
  79377. return false;
  79378. }
  79379. }
  79380. }
  79381. }
  79382. return true;
  79383. },
  79384. enumerable: true,
  79385. configurable: true
  79386. });
  79387. /**
  79388. * Updates the current state of the effect
  79389. * @hidden
  79390. */
  79391. PostProcessRenderEffect.prototype._update = function () {
  79392. };
  79393. /**
  79394. * Attaches the effect on cameras
  79395. * @param cameras The camera to attach to.
  79396. * @hidden
  79397. */
  79398. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  79399. var _this = this;
  79400. var cameraKey;
  79401. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79402. if (!cams) {
  79403. return;
  79404. }
  79405. for (var i = 0; i < cams.length; i++) {
  79406. var camera = cams[i];
  79407. var cameraName = camera.name;
  79408. if (this._singleInstance) {
  79409. cameraKey = 0;
  79410. }
  79411. else {
  79412. cameraKey = cameraName;
  79413. }
  79414. if (!this._postProcesses[cameraKey]) {
  79415. var postProcess = this._getPostProcesses();
  79416. if (postProcess) {
  79417. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  79418. }
  79419. }
  79420. if (!this._indicesForCamera[cameraName]) {
  79421. this._indicesForCamera[cameraName] = [];
  79422. }
  79423. this._postProcesses[cameraKey].forEach(function (postProcess) {
  79424. var index = camera.attachPostProcess(postProcess);
  79425. _this._indicesForCamera[cameraName].push(index);
  79426. });
  79427. if (!this._cameras[cameraName]) {
  79428. this._cameras[cameraName] = camera;
  79429. }
  79430. }
  79431. };
  79432. /**
  79433. * Detatches the effect on cameras
  79434. * @param cameras The camera to detatch from.
  79435. * @hidden
  79436. */
  79437. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  79438. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79439. if (!cams) {
  79440. return;
  79441. }
  79442. for (var i = 0; i < cams.length; i++) {
  79443. var camera = cams[i];
  79444. var cameraName = camera.name;
  79445. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79446. camera.detachPostProcess(postProcess);
  79447. });
  79448. if (this._cameras[cameraName]) {
  79449. //this._indicesForCamera.splice(index, 1);
  79450. this._cameras[cameraName] = null;
  79451. }
  79452. }
  79453. };
  79454. /**
  79455. * Enables the effect on given cameras
  79456. * @param cameras The camera to enable.
  79457. * @hidden
  79458. */
  79459. PostProcessRenderEffect.prototype._enable = function (cameras) {
  79460. var _this = this;
  79461. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79462. if (!cams) {
  79463. return;
  79464. }
  79465. for (var i = 0; i < cams.length; i++) {
  79466. var camera = cams[i];
  79467. var cameraName = camera.name;
  79468. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  79469. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  79470. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79471. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  79472. });
  79473. }
  79474. }
  79475. }
  79476. };
  79477. /**
  79478. * Disables the effect on the given cameras
  79479. * @param cameras The camera to disable.
  79480. * @hidden
  79481. */
  79482. PostProcessRenderEffect.prototype._disable = function (cameras) {
  79483. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79484. if (!cams) {
  79485. return;
  79486. }
  79487. for (var i = 0; i < cams.length; i++) {
  79488. var camera = cams[i];
  79489. var cameraName = camera.name;
  79490. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79491. camera.detachPostProcess(postProcess);
  79492. });
  79493. }
  79494. };
  79495. /**
  79496. * Gets a list of the post processes contained in the effect.
  79497. * @param camera The camera to get the post processes on.
  79498. * @returns The list of the post processes in the effect.
  79499. */
  79500. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  79501. if (this._singleInstance) {
  79502. return this._postProcesses[0];
  79503. }
  79504. else {
  79505. if (!camera) {
  79506. return null;
  79507. }
  79508. return this._postProcesses[camera.name];
  79509. }
  79510. };
  79511. return PostProcessRenderEffect;
  79512. }());
  79513. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  79514. })(BABYLON || (BABYLON = {}));
  79515. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  79516. var BABYLON;
  79517. (function (BABYLON) {
  79518. var PostProcessRenderPipeline = /** @class */ (function () {
  79519. function PostProcessRenderPipeline(engine, name) {
  79520. this.engine = engine;
  79521. this._name = name;
  79522. this._renderEffects = {};
  79523. this._renderEffectsForIsolatedPass = new Array();
  79524. this._cameras = [];
  79525. }
  79526. PostProcessRenderPipeline.prototype.getClassName = function () {
  79527. return "PostProcessRenderPipeline";
  79528. };
  79529. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  79530. get: function () {
  79531. for (var renderEffectName in this._renderEffects) {
  79532. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79533. if (!this._renderEffects[renderEffectName].isSupported) {
  79534. return false;
  79535. }
  79536. }
  79537. }
  79538. return true;
  79539. },
  79540. enumerable: true,
  79541. configurable: true
  79542. });
  79543. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  79544. this._renderEffects[renderEffect._name] = renderEffect;
  79545. };
  79546. // private
  79547. /** @hidden */
  79548. PostProcessRenderPipeline.prototype._rebuild = function () {
  79549. };
  79550. /** @hidden */
  79551. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  79552. var renderEffects = this._renderEffects[renderEffectName];
  79553. if (!renderEffects) {
  79554. return;
  79555. }
  79556. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79557. };
  79558. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  79559. var renderEffects = this._renderEffects[renderEffectName];
  79560. if (!renderEffects) {
  79561. return;
  79562. }
  79563. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79564. };
  79565. /** @hidden */
  79566. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  79567. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79568. if (!cams) {
  79569. return;
  79570. }
  79571. var indicesToDelete = [];
  79572. var i;
  79573. for (i = 0; i < cams.length; i++) {
  79574. var camera = cams[i];
  79575. var cameraName = camera.name;
  79576. if (this._cameras.indexOf(camera) === -1) {
  79577. this._cameras[cameraName] = camera;
  79578. }
  79579. else if (unique) {
  79580. indicesToDelete.push(i);
  79581. }
  79582. }
  79583. for (i = 0; i < indicesToDelete.length; i++) {
  79584. cameras.splice(indicesToDelete[i], 1);
  79585. }
  79586. for (var renderEffectName in this._renderEffects) {
  79587. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79588. this._renderEffects[renderEffectName]._attachCameras(cams);
  79589. }
  79590. }
  79591. };
  79592. /** @hidden */
  79593. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  79594. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79595. if (!cams) {
  79596. return;
  79597. }
  79598. for (var renderEffectName in this._renderEffects) {
  79599. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79600. this._renderEffects[renderEffectName]._detachCameras(cams);
  79601. }
  79602. }
  79603. for (var i = 0; i < cams.length; i++) {
  79604. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  79605. }
  79606. };
  79607. /** @hidden */
  79608. PostProcessRenderPipeline.prototype._update = function () {
  79609. for (var renderEffectName in this._renderEffects) {
  79610. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79611. this._renderEffects[renderEffectName]._update();
  79612. }
  79613. }
  79614. for (var i = 0; i < this._cameras.length; i++) {
  79615. var cameraName = this._cameras[i].name;
  79616. if (this._renderEffectsForIsolatedPass[cameraName]) {
  79617. this._renderEffectsForIsolatedPass[cameraName]._update();
  79618. }
  79619. }
  79620. };
  79621. /** @hidden */
  79622. PostProcessRenderPipeline.prototype._reset = function () {
  79623. this._renderEffects = {};
  79624. this._renderEffectsForIsolatedPass = new Array();
  79625. };
  79626. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  79627. // 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)
  79628. var effectKeys = Object.keys(this._renderEffects);
  79629. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  79630. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  79631. if (postProcesses) {
  79632. postProcesses[0].samples = sampleCount;
  79633. return true;
  79634. }
  79635. }
  79636. return false;
  79637. };
  79638. PostProcessRenderPipeline.prototype.dispose = function () {
  79639. // Must be implemented by children
  79640. };
  79641. __decorate([
  79642. BABYLON.serialize()
  79643. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  79644. return PostProcessRenderPipeline;
  79645. }());
  79646. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  79647. })(BABYLON || (BABYLON = {}));
  79648. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  79649. var BABYLON;
  79650. (function (BABYLON) {
  79651. /**
  79652. * This represents a depth renderer in Babylon.
  79653. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  79654. */
  79655. var DepthRenderer = /** @class */ (function () {
  79656. /**
  79657. * Instantiates a depth renderer
  79658. * @param scene The scene the renderer belongs to
  79659. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  79660. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  79661. */
  79662. function DepthRenderer(scene, type, camera) {
  79663. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  79664. if (camera === void 0) { camera = null; }
  79665. var _this = this;
  79666. /**
  79667. * Specifiess that the depth renderer will only be used within
  79668. * the camera it is created for.
  79669. * This can help forcing its rendering during the camera processing.
  79670. */
  79671. this.useOnlyInActiveCamera = false;
  79672. this._scene = scene;
  79673. // Register the G Buffer component to the scene.
  79674. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  79675. if (!component) {
  79676. component = new BABYLON.DepthRendererSceneComponent(scene);
  79677. scene._addComponent(component);
  79678. }
  79679. this._camera = camera;
  79680. var engine = scene.getEngine();
  79681. // Render target
  79682. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  79683. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79684. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79685. this._depthMap.refreshRate = 1;
  79686. this._depthMap.renderParticles = false;
  79687. this._depthMap.renderList = null;
  79688. // Camera to get depth map from to support multiple concurrent cameras
  79689. this._depthMap.activeCamera = this._camera;
  79690. this._depthMap.ignoreCameraViewport = true;
  79691. this._depthMap.useCameraPostProcesses = false;
  79692. // set default depth value to 1.0 (far away)
  79693. this._depthMap.onClearObservable.add(function (engine) {
  79694. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  79695. });
  79696. // Custom render function
  79697. var renderSubMesh = function (subMesh) {
  79698. var mesh = subMesh.getRenderingMesh();
  79699. var scene = _this._scene;
  79700. var engine = scene.getEngine();
  79701. var material = subMesh.getMaterial();
  79702. if (!material) {
  79703. return;
  79704. }
  79705. // Culling and reverse (right handed system)
  79706. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79707. // Managing instances
  79708. var batch = mesh._getInstancesRenderList(subMesh._id);
  79709. if (batch.mustReturn) {
  79710. return;
  79711. }
  79712. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79713. var camera = _this._camera || scene.activeCamera;
  79714. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  79715. engine.enableEffect(_this._effect);
  79716. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79717. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79718. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  79719. // Alpha test
  79720. if (material && material.needAlphaTesting()) {
  79721. var alphaTexture = material.getAlphaTestTexture();
  79722. if (alphaTexture) {
  79723. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79724. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79725. }
  79726. }
  79727. // Bones
  79728. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79729. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79730. }
  79731. // Draw
  79732. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79733. }
  79734. };
  79735. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79736. var index;
  79737. if (depthOnlySubMeshes.length) {
  79738. engine.setColorWrite(false);
  79739. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79740. renderSubMesh(depthOnlySubMeshes.data[index]);
  79741. }
  79742. engine.setColorWrite(true);
  79743. }
  79744. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79745. renderSubMesh(opaqueSubMeshes.data[index]);
  79746. }
  79747. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79748. renderSubMesh(alphaTestSubMeshes.data[index]);
  79749. }
  79750. };
  79751. }
  79752. /**
  79753. * Creates the depth rendering effect and checks if the effect is ready.
  79754. * @param subMesh The submesh to be used to render the depth map of
  79755. * @param useInstances If multiple world instances should be used
  79756. * @returns if the depth renderer is ready to render the depth map
  79757. */
  79758. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  79759. var material = subMesh.getMaterial();
  79760. if (material.disableDepthWrite) {
  79761. return false;
  79762. }
  79763. var defines = [];
  79764. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79765. var mesh = subMesh.getMesh();
  79766. // Alpha test
  79767. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  79768. defines.push("#define ALPHATEST");
  79769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79770. attribs.push(BABYLON.VertexBuffer.UVKind);
  79771. defines.push("#define UV1");
  79772. }
  79773. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79774. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79775. defines.push("#define UV2");
  79776. }
  79777. }
  79778. // Bones
  79779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79782. if (mesh.numBoneInfluencers > 4) {
  79783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79785. }
  79786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79787. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79788. }
  79789. else {
  79790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79791. }
  79792. // Instances
  79793. if (useInstances) {
  79794. defines.push("#define INSTANCES");
  79795. attribs.push("world0");
  79796. attribs.push("world1");
  79797. attribs.push("world2");
  79798. attribs.push("world3");
  79799. }
  79800. // Get correct effect
  79801. var join = defines.join("\n");
  79802. if (this._cachedDefines !== join) {
  79803. this._cachedDefines = join;
  79804. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  79805. }
  79806. return this._effect.isReady();
  79807. };
  79808. /**
  79809. * Gets the texture which the depth map will be written to.
  79810. * @returns The depth map texture
  79811. */
  79812. DepthRenderer.prototype.getDepthMap = function () {
  79813. return this._depthMap;
  79814. };
  79815. /**
  79816. * Disposes of the depth renderer.
  79817. */
  79818. DepthRenderer.prototype.dispose = function () {
  79819. this._depthMap.dispose();
  79820. };
  79821. return DepthRenderer;
  79822. }());
  79823. BABYLON.DepthRenderer = DepthRenderer;
  79824. })(BABYLON || (BABYLON = {}));
  79825. //# sourceMappingURL=babylon.depthRenderer.js.map
  79826. var BABYLON;
  79827. (function (BABYLON) {
  79828. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  79829. camera = camera || this.activeCamera;
  79830. if (!camera) {
  79831. throw "No camera available to enable depth renderer";
  79832. }
  79833. if (!this._depthRenderer) {
  79834. this._depthRenderer = {};
  79835. }
  79836. if (!this._depthRenderer[camera.id]) {
  79837. var textureType = 0;
  79838. if (this.getEngine().getCaps().textureHalfFloatRender) {
  79839. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79840. }
  79841. else if (this.getEngine().getCaps().textureFloatRender) {
  79842. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79843. }
  79844. else {
  79845. throw "Depth renderer does not support int texture type";
  79846. }
  79847. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  79848. }
  79849. return this._depthRenderer[camera.id];
  79850. };
  79851. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  79852. camera = camera || this.activeCamera;
  79853. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  79854. return;
  79855. }
  79856. this._depthRenderer[camera.id].dispose();
  79857. delete this._depthRenderer[camera.id];
  79858. };
  79859. /**
  79860. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  79861. * in several rendering techniques.
  79862. */
  79863. var DepthRendererSceneComponent = /** @class */ (function () {
  79864. /**
  79865. * Creates a new instance of the component for the given scene
  79866. * @param scene Defines the scene to register the component in
  79867. */
  79868. function DepthRendererSceneComponent(scene) {
  79869. /**
  79870. * The component name helpfull to identify the component in the list of scene components.
  79871. */
  79872. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  79873. this.scene = scene;
  79874. }
  79875. /**
  79876. * Registers the component in a given scene
  79877. */
  79878. DepthRendererSceneComponent.prototype.register = function () {
  79879. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  79880. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  79881. };
  79882. /**
  79883. * Rebuilds the elements related to this component in case of
  79884. * context lost for instance.
  79885. */
  79886. DepthRendererSceneComponent.prototype.rebuild = function () {
  79887. // Nothing to do for this component
  79888. };
  79889. /**
  79890. * Disposes the component and the associated ressources
  79891. */
  79892. DepthRendererSceneComponent.prototype.dispose = function () {
  79893. for (var key in this.scene._depthRenderer) {
  79894. this.scene._depthRenderer[key].dispose();
  79895. }
  79896. };
  79897. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79898. if (this.scene._depthRenderer) {
  79899. for (var key in this.scene._depthRenderer) {
  79900. var depthRenderer = this.scene._depthRenderer[key];
  79901. if (!depthRenderer.useOnlyInActiveCamera) {
  79902. renderTargets.push(depthRenderer.getDepthMap());
  79903. }
  79904. }
  79905. }
  79906. };
  79907. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  79908. if (this.scene._depthRenderer) {
  79909. for (var key in this.scene._depthRenderer) {
  79910. var depthRenderer = this.scene._depthRenderer[key];
  79911. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  79912. renderTargets.push(depthRenderer.getDepthMap());
  79913. }
  79914. }
  79915. }
  79916. };
  79917. return DepthRendererSceneComponent;
  79918. }());
  79919. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  79920. })(BABYLON || (BABYLON = {}));
  79921. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  79922. var BABYLON;
  79923. (function (BABYLON) {
  79924. /**
  79925. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  79926. */
  79927. var GeometryBufferRenderer = /** @class */ (function () {
  79928. /**
  79929. * Creates a new G Buffer for the scene
  79930. * @param scene The scene the buffer belongs to
  79931. * @param ratio How big is the buffer related to the main canvas.
  79932. */
  79933. function GeometryBufferRenderer(scene, ratio) {
  79934. if (ratio === void 0) { ratio = 1; }
  79935. this._enablePosition = false;
  79936. this._scene = scene;
  79937. this._ratio = ratio;
  79938. // Register the G Buffer component to the scene.
  79939. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  79940. if (!component) {
  79941. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  79942. scene._addComponent(component);
  79943. }
  79944. // Render target
  79945. this._createRenderTargets();
  79946. }
  79947. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  79948. /**
  79949. * Set the render list (meshes to be rendered) used in the G buffer.
  79950. */
  79951. set: function (meshes) {
  79952. this._multiRenderTarget.renderList = meshes;
  79953. },
  79954. enumerable: true,
  79955. configurable: true
  79956. });
  79957. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  79958. /**
  79959. * Gets wether or not G buffer are supported by the running hardware.
  79960. * This requires draw buffer supports
  79961. */
  79962. get: function () {
  79963. return this._multiRenderTarget.isSupported;
  79964. },
  79965. enumerable: true,
  79966. configurable: true
  79967. });
  79968. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  79969. /**
  79970. * Gets wether or not position are enabled for the G buffer.
  79971. */
  79972. get: function () {
  79973. return this._enablePosition;
  79974. },
  79975. /**
  79976. * Sets wether or not position are enabled for the G buffer.
  79977. */
  79978. set: function (enable) {
  79979. this._enablePosition = enable;
  79980. this.dispose();
  79981. this._createRenderTargets();
  79982. },
  79983. enumerable: true,
  79984. configurable: true
  79985. });
  79986. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  79987. /**
  79988. * Gets the scene associated with the buffer.
  79989. */
  79990. get: function () {
  79991. return this._scene;
  79992. },
  79993. enumerable: true,
  79994. configurable: true
  79995. });
  79996. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79997. /**
  79998. * Gets the ratio used by the buffer during its creation.
  79999. * How big is the buffer related to the main canvas.
  80000. */
  80001. get: function () {
  80002. return this._ratio;
  80003. },
  80004. enumerable: true,
  80005. configurable: true
  80006. });
  80007. /**
  80008. * Checks wether everything is ready to render a submesh to the G buffer.
  80009. * @param subMesh the submesh to check readiness for
  80010. * @param useInstances is the mesh drawn using instance or not
  80011. * @returns true if ready otherwise false
  80012. */
  80013. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80014. var material = subMesh.getMaterial();
  80015. if (material && material.disableDepthWrite) {
  80016. return false;
  80017. }
  80018. var defines = [];
  80019. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80020. var mesh = subMesh.getMesh();
  80021. // Alpha test
  80022. if (material && material.needAlphaTesting()) {
  80023. defines.push("#define ALPHATEST");
  80024. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80025. attribs.push(BABYLON.VertexBuffer.UVKind);
  80026. defines.push("#define UV1");
  80027. }
  80028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80030. defines.push("#define UV2");
  80031. }
  80032. }
  80033. // Buffers
  80034. if (this._enablePosition) {
  80035. defines.push("#define POSITION");
  80036. }
  80037. // Bones
  80038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80041. if (mesh.numBoneInfluencers > 4) {
  80042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80044. }
  80045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80046. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80047. }
  80048. else {
  80049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80050. }
  80051. // Instances
  80052. if (useInstances) {
  80053. defines.push("#define INSTANCES");
  80054. attribs.push("world0");
  80055. attribs.push("world1");
  80056. attribs.push("world2");
  80057. attribs.push("world3");
  80058. }
  80059. // Get correct effect
  80060. var join = defines.join("\n");
  80061. if (this._cachedDefines !== join) {
  80062. this._cachedDefines = join;
  80063. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80064. }
  80065. return this._effect.isReady();
  80066. };
  80067. /**
  80068. * Gets the current underlying G Buffer.
  80069. * @returns the buffer
  80070. */
  80071. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80072. return this._multiRenderTarget;
  80073. };
  80074. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80075. /**
  80076. * Gets the number of samples used to render the buffer (anti aliasing).
  80077. */
  80078. get: function () {
  80079. return this._multiRenderTarget.samples;
  80080. },
  80081. /**
  80082. * Sets the number of samples used to render the buffer (anti aliasing).
  80083. */
  80084. set: function (value) {
  80085. this._multiRenderTarget.samples = value;
  80086. },
  80087. enumerable: true,
  80088. configurable: true
  80089. });
  80090. /**
  80091. * Disposes the renderer and frees up associated resources.
  80092. */
  80093. GeometryBufferRenderer.prototype.dispose = function () {
  80094. this.getGBuffer().dispose();
  80095. };
  80096. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80097. var _this = this;
  80098. var engine = this._scene.getEngine();
  80099. var count = this._enablePosition ? 3 : 2;
  80100. 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 });
  80101. if (!this.isSupported) {
  80102. return;
  80103. }
  80104. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80105. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80106. this._multiRenderTarget.refreshRate = 1;
  80107. this._multiRenderTarget.renderParticles = false;
  80108. this._multiRenderTarget.renderList = null;
  80109. // set default depth value to 1.0 (far away)
  80110. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80111. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80112. });
  80113. // Custom render function
  80114. var renderSubMesh = function (subMesh) {
  80115. var mesh = subMesh.getRenderingMesh();
  80116. var scene = _this._scene;
  80117. var engine = scene.getEngine();
  80118. var material = subMesh.getMaterial();
  80119. if (!material) {
  80120. return;
  80121. }
  80122. // Culling
  80123. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80124. // Managing instances
  80125. var batch = mesh._getInstancesRenderList(subMesh._id);
  80126. if (batch.mustReturn) {
  80127. return;
  80128. }
  80129. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80130. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80131. engine.enableEffect(_this._effect);
  80132. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80133. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80134. _this._effect.setMatrix("view", scene.getViewMatrix());
  80135. // Alpha test
  80136. if (material && material.needAlphaTesting()) {
  80137. var alphaTexture = material.getAlphaTestTexture();
  80138. if (alphaTexture) {
  80139. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80140. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80141. }
  80142. }
  80143. // Bones
  80144. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80145. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80146. }
  80147. // Draw
  80148. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80149. }
  80150. };
  80151. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80152. var index;
  80153. if (depthOnlySubMeshes.length) {
  80154. engine.setColorWrite(false);
  80155. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80156. renderSubMesh(depthOnlySubMeshes.data[index]);
  80157. }
  80158. engine.setColorWrite(true);
  80159. }
  80160. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80161. renderSubMesh(opaqueSubMeshes.data[index]);
  80162. }
  80163. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80164. renderSubMesh(alphaTestSubMeshes.data[index]);
  80165. }
  80166. };
  80167. };
  80168. return GeometryBufferRenderer;
  80169. }());
  80170. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80171. })(BABYLON || (BABYLON = {}));
  80172. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80173. var BABYLON;
  80174. (function (BABYLON) {
  80175. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80176. get: function () {
  80177. this._geometryBufferRenderer;
  80178. },
  80179. set: function (value) {
  80180. if (value && value.isSupported) {
  80181. this._geometryBufferRenderer = value;
  80182. }
  80183. ;
  80184. },
  80185. enumerable: true,
  80186. configurable: true
  80187. });
  80188. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80189. if (ratio === void 0) { ratio = 1; }
  80190. if (this._geometryBufferRenderer) {
  80191. return this._geometryBufferRenderer;
  80192. }
  80193. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80194. if (!this._geometryBufferRenderer.isSupported) {
  80195. this._geometryBufferRenderer = null;
  80196. }
  80197. return this._geometryBufferRenderer;
  80198. };
  80199. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80200. if (!this._geometryBufferRenderer) {
  80201. return;
  80202. }
  80203. this._geometryBufferRenderer.dispose();
  80204. this._geometryBufferRenderer = null;
  80205. };
  80206. /**
  80207. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80208. * in several rendering techniques.
  80209. */
  80210. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80211. /**
  80212. * Creates a new instance of the component for the given scene
  80213. * @param scene Defines the scene to register the component in
  80214. */
  80215. function GeometryBufferRendererSceneComponent(scene) {
  80216. /**
  80217. * The component name helpful to identify the component in the list of scene components.
  80218. */
  80219. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80220. this.scene = scene;
  80221. }
  80222. /**
  80223. * Registers the component in a given scene
  80224. */
  80225. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80226. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80227. };
  80228. /**
  80229. * Rebuilds the elements related to this component in case of
  80230. * context lost for instance.
  80231. */
  80232. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80233. // Nothing to do for this component
  80234. };
  80235. /**
  80236. * Disposes the component and the associated ressources
  80237. */
  80238. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80239. // Nothing to do for this component
  80240. };
  80241. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80242. if (this.scene._geometryBufferRenderer) {
  80243. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80244. }
  80245. };
  80246. return GeometryBufferRendererSceneComponent;
  80247. }());
  80248. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80249. })(BABYLON || (BABYLON = {}));
  80250. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80251. var BABYLON;
  80252. (function (BABYLON) {
  80253. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80254. __extends(SSAORenderingPipeline, _super);
  80255. /**
  80256. * @constructor
  80257. * @param {string} name - The rendering pipeline name
  80258. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80259. * @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 }
  80260. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80261. */
  80262. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80263. var _this = _super.call(this, scene.getEngine(), name) || this;
  80264. // Members
  80265. /**
  80266. * The PassPostProcess id in the pipeline that contains the original scene color
  80267. */
  80268. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80269. /**
  80270. * The SSAO PostProcess id in the pipeline
  80271. */
  80272. _this.SSAORenderEffect = "SSAORenderEffect";
  80273. /**
  80274. * The horizontal blur PostProcess id in the pipeline
  80275. */
  80276. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80277. /**
  80278. * The vertical blur PostProcess id in the pipeline
  80279. */
  80280. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80281. /**
  80282. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80283. */
  80284. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80285. /**
  80286. * The output strength of the SSAO post-process. Default value is 1.0.
  80287. */
  80288. _this.totalStrength = 1.0;
  80289. /**
  80290. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  80291. */
  80292. _this.radius = 0.0001;
  80293. /**
  80294. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  80295. * Must not be equal to fallOff and superior to fallOff.
  80296. * Default value is 0.975
  80297. */
  80298. _this.area = 0.0075;
  80299. /**
  80300. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  80301. * Must not be equal to area and inferior to area.
  80302. * Default value is 0.0
  80303. */
  80304. _this.fallOff = 0.000001;
  80305. /**
  80306. * The base color of the SSAO post-process
  80307. * The final result is "base + ssao" between [0, 1]
  80308. */
  80309. _this.base = 0.5;
  80310. _this._firstUpdate = true;
  80311. _this._scene = scene;
  80312. // Set up assets
  80313. _this._createRandomTexture();
  80314. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80315. var ssaoRatio = ratio.ssaoRatio || ratio;
  80316. var combineRatio = ratio.combineRatio || ratio;
  80317. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80318. _this._createSSAOPostProcess(ssaoRatio);
  80319. _this._createBlurPostProcess(ssaoRatio);
  80320. _this._createSSAOCombinePostProcess(combineRatio);
  80321. // Set up pipeline
  80322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80327. // Finish
  80328. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80329. if (cameras)
  80330. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80331. return _this;
  80332. }
  80333. // Public Methods
  80334. /**
  80335. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80336. */
  80337. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80338. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80339. for (var i = 0; i < this._scene.cameras.length; i++) {
  80340. var camera = this._scene.cameras[i];
  80341. this._originalColorPostProcess.dispose(camera);
  80342. this._ssaoPostProcess.dispose(camera);
  80343. this._blurHPostProcess.dispose(camera);
  80344. this._blurVPostProcess.dispose(camera);
  80345. this._ssaoCombinePostProcess.dispose(camera);
  80346. }
  80347. this._randomTexture.dispose();
  80348. if (disableDepthRender)
  80349. this._scene.disableDepthRenderer();
  80350. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80351. _super.prototype.dispose.call(this);
  80352. };
  80353. // Private Methods
  80354. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  80355. var _this = this;
  80356. var size = 16;
  80357. 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);
  80358. 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);
  80359. this._blurHPostProcess.onActivateObservable.add(function () {
  80360. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  80361. _this._blurHPostProcess.kernel = size * dw;
  80362. });
  80363. this._blurVPostProcess.onActivateObservable.add(function () {
  80364. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  80365. _this._blurVPostProcess.kernel = size * dw;
  80366. });
  80367. };
  80368. /** @hidden */
  80369. SSAORenderingPipeline.prototype._rebuild = function () {
  80370. this._firstUpdate = true;
  80371. _super.prototype._rebuild.call(this);
  80372. };
  80373. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80374. var _this = this;
  80375. var numSamples = 16;
  80376. var sampleSphere = [
  80377. 0.5381, 0.1856, -0.4319,
  80378. 0.1379, 0.2486, 0.4430,
  80379. 0.3371, 0.5679, -0.0057,
  80380. -0.6999, -0.0451, -0.0019,
  80381. 0.0689, -0.1598, -0.8547,
  80382. 0.0560, 0.0069, -0.1843,
  80383. -0.0146, 0.1402, 0.0762,
  80384. 0.0100, -0.1924, -0.0344,
  80385. -0.3577, -0.5301, -0.4358,
  80386. -0.3169, 0.1063, 0.0158,
  80387. 0.0103, -0.5869, 0.0046,
  80388. -0.0897, -0.4940, 0.3287,
  80389. 0.7119, -0.0154, -0.0918,
  80390. -0.0533, 0.0596, -0.5411,
  80391. 0.0352, -0.0631, 0.5460,
  80392. -0.4776, 0.2847, -0.0271
  80393. ];
  80394. var samplesFactor = 1.0 / numSamples;
  80395. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  80396. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80397. "area", "fallOff", "base", "range", "viewport"
  80398. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80399. this._ssaoPostProcess.onApply = function (effect) {
  80400. if (_this._firstUpdate) {
  80401. effect.setArray3("sampleSphere", sampleSphere);
  80402. effect.setFloat("samplesFactor", samplesFactor);
  80403. effect.setFloat("randTextureTiles", 4.0);
  80404. }
  80405. effect.setFloat("totalStrength", _this.totalStrength);
  80406. effect.setFloat("radius", _this.radius);
  80407. effect.setFloat("area", _this.area);
  80408. effect.setFloat("fallOff", _this.fallOff);
  80409. effect.setFloat("base", _this.base);
  80410. effect.setTexture("textureSampler", _this._depthTexture);
  80411. effect.setTexture("randomSampler", _this._randomTexture);
  80412. };
  80413. };
  80414. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80415. var _this = this;
  80416. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80417. this._ssaoCombinePostProcess.onApply = function (effect) {
  80418. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  80419. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80420. };
  80421. };
  80422. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  80423. var size = 512;
  80424. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80425. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80426. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80427. var context = this._randomTexture.getContext();
  80428. var rand = function (min, max) {
  80429. return Math.random() * (max - min) + min;
  80430. };
  80431. var randVector = BABYLON.Vector3.Zero();
  80432. for (var x = 0; x < size; x++) {
  80433. for (var y = 0; y < size; y++) {
  80434. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  80435. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  80436. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  80437. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80438. context.fillRect(x, y, 1, 1);
  80439. }
  80440. }
  80441. this._randomTexture.update(false);
  80442. };
  80443. __decorate([
  80444. BABYLON.serialize()
  80445. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  80446. __decorate([
  80447. BABYLON.serialize()
  80448. ], SSAORenderingPipeline.prototype, "radius", void 0);
  80449. __decorate([
  80450. BABYLON.serialize()
  80451. ], SSAORenderingPipeline.prototype, "area", void 0);
  80452. __decorate([
  80453. BABYLON.serialize()
  80454. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  80455. __decorate([
  80456. BABYLON.serialize()
  80457. ], SSAORenderingPipeline.prototype, "base", void 0);
  80458. return SSAORenderingPipeline;
  80459. }(BABYLON.PostProcessRenderPipeline));
  80460. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  80461. })(BABYLON || (BABYLON = {}));
  80462. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  80463. var BABYLON;
  80464. (function (BABYLON) {
  80465. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  80466. __extends(SSAO2RenderingPipeline, _super);
  80467. /**
  80468. * @constructor
  80469. * @param {string} name - The rendering pipeline name
  80470. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80471. * @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 }
  80472. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80473. */
  80474. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  80475. var _this = _super.call(this, scene.getEngine(), name) || this;
  80476. // Members
  80477. /**
  80478. * The PassPostProcess id in the pipeline that contains the original scene color
  80479. */
  80480. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80481. /**
  80482. * The SSAO PostProcess id in the pipeline
  80483. */
  80484. _this.SSAORenderEffect = "SSAORenderEffect";
  80485. /**
  80486. * The horizontal blur PostProcess id in the pipeline
  80487. */
  80488. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80489. /**
  80490. * The vertical blur PostProcess id in the pipeline
  80491. */
  80492. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80493. /**
  80494. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80495. */
  80496. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80497. /**
  80498. * The output strength of the SSAO post-process. Default value is 1.0.
  80499. */
  80500. _this.totalStrength = 1.0;
  80501. /**
  80502. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  80503. */
  80504. _this.maxZ = 100.0;
  80505. /**
  80506. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  80507. */
  80508. _this.minZAspect = 0.2;
  80509. _this._samples = 8;
  80510. _this._textureSamples = 1;
  80511. /**
  80512. * Are we using bilateral blur ?
  80513. */
  80514. _this._expensiveBlur = true;
  80515. /**
  80516. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  80517. */
  80518. _this.radius = 2.0;
  80519. /**
  80520. * The base color of the SSAO post-process
  80521. * The final result is "base + ssao" between [0, 1]
  80522. */
  80523. _this.base = 0;
  80524. _this._firstUpdate = true;
  80525. _this._bits = new Uint32Array(1);
  80526. _this._scene = scene;
  80527. _this._ratio = ratio;
  80528. if (!_this.isSupported) {
  80529. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  80530. return _this;
  80531. }
  80532. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  80533. var blurRatio = _this._ratio.blurRatio || ratio;
  80534. // Set up assets
  80535. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  80536. _this._createRandomTexture();
  80537. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  80538. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  80539. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80540. _this._originalColorPostProcess.samples = _this.textureSamples;
  80541. _this._createSSAOPostProcess(1.0);
  80542. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  80543. _this._createSSAOCombinePostProcess(blurRatio);
  80544. // Set up pipeline
  80545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80547. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80548. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80549. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80550. // Finish
  80551. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80552. if (cameras)
  80553. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80554. return _this;
  80555. }
  80556. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  80557. get: function () {
  80558. return this._samples;
  80559. },
  80560. /**
  80561. * Number of samples used for the SSAO calculations. Default value is 8
  80562. */
  80563. set: function (n) {
  80564. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  80565. this._samples = n;
  80566. this._sampleSphere = this._generateHemisphere();
  80567. this._firstUpdate = true;
  80568. },
  80569. enumerable: true,
  80570. configurable: true
  80571. });
  80572. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  80573. get: function () {
  80574. return this._textureSamples;
  80575. },
  80576. /**
  80577. * Number of samples to use for antialiasing
  80578. */
  80579. set: function (n) {
  80580. this._textureSamples = n;
  80581. this._originalColorPostProcess.samples = n;
  80582. this._blurHPostProcess.samples = n;
  80583. this._blurVPostProcess.samples = n;
  80584. this._ssaoPostProcess.samples = n;
  80585. this._ssaoCombinePostProcess.samples = n;
  80586. },
  80587. enumerable: true,
  80588. configurable: true
  80589. });
  80590. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  80591. get: function () {
  80592. return this._expensiveBlur;
  80593. },
  80594. set: function (b) {
  80595. 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"]);
  80596. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  80597. this._expensiveBlur = b;
  80598. this._firstUpdate = true;
  80599. },
  80600. enumerable: true,
  80601. configurable: true
  80602. });
  80603. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  80604. /**
  80605. * Support test.
  80606. */
  80607. get: function () {
  80608. var engine = BABYLON.Engine.LastCreatedEngine;
  80609. if (!engine) {
  80610. return false;
  80611. }
  80612. return engine.getCaps().drawBuffersExtension;
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. // Public Methods
  80618. /**
  80619. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80620. */
  80621. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  80622. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  80623. for (var i = 0; i < this._scene.cameras.length; i++) {
  80624. var camera = this._scene.cameras[i];
  80625. this._originalColorPostProcess.dispose(camera);
  80626. this._ssaoPostProcess.dispose(camera);
  80627. this._blurHPostProcess.dispose(camera);
  80628. this._blurVPostProcess.dispose(camera);
  80629. this._ssaoCombinePostProcess.dispose(camera);
  80630. }
  80631. this._randomTexture.dispose();
  80632. if (disableGeometryBufferRenderer)
  80633. this._scene.disableGeometryBufferRenderer();
  80634. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80635. _super.prototype.dispose.call(this);
  80636. };
  80637. // Private Methods
  80638. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  80639. var _this = this;
  80640. this._samplerOffsets = [];
  80641. var expensive = this.expensiveBlur;
  80642. for (var i = -8; i < 8; i++) {
  80643. this._samplerOffsets.push(i * 2 + 0.5);
  80644. }
  80645. 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");
  80646. this._blurHPostProcess.onApply = function (effect) {
  80647. if (!_this._scene.activeCamera) {
  80648. return;
  80649. }
  80650. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  80651. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80652. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80653. effect.setFloat("radius", _this.radius);
  80654. effect.setTexture("depthSampler", _this._depthTexture);
  80655. if (_this._firstUpdate) {
  80656. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80657. }
  80658. };
  80659. 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");
  80660. this._blurVPostProcess.onApply = function (effect) {
  80661. if (!_this._scene.activeCamera) {
  80662. return;
  80663. }
  80664. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  80665. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80666. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80667. effect.setFloat("radius", _this.radius);
  80668. effect.setTexture("depthSampler", _this._depthTexture);
  80669. if (_this._firstUpdate) {
  80670. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80671. _this._firstUpdate = false;
  80672. }
  80673. };
  80674. this._blurHPostProcess.samples = this.textureSamples;
  80675. this._blurVPostProcess.samples = this.textureSamples;
  80676. };
  80677. /** @hidden */
  80678. SSAO2RenderingPipeline.prototype._rebuild = function () {
  80679. this._firstUpdate = true;
  80680. _super.prototype._rebuild.call(this);
  80681. };
  80682. //Van der Corput radical inverse
  80683. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  80684. this._bits[0] = i;
  80685. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  80686. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  80687. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  80688. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  80689. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  80690. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  80691. };
  80692. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  80693. return [i / n, this._radicalInverse_VdC(i)];
  80694. };
  80695. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  80696. var phi = v * 2.0 * Math.PI;
  80697. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  80698. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  80699. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  80700. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  80701. };
  80702. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  80703. var numSamples = this.samples;
  80704. var result = [];
  80705. var vector;
  80706. var i = 0;
  80707. while (i < numSamples) {
  80708. if (numSamples < 16) {
  80709. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  80710. }
  80711. else {
  80712. var rand = this._hammersley(i, numSamples);
  80713. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  80714. }
  80715. result.push(vector.x, vector.y, vector.z);
  80716. i++;
  80717. }
  80718. return result;
  80719. };
  80720. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80721. var _this = this;
  80722. var numSamples = this.samples;
  80723. this._sampleSphere = this._generateHemisphere();
  80724. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  80725. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80726. "base", "range", "projection", "near", "far", "texelSize",
  80727. "xViewport", "yViewport", "maxZ", "minZAspect"
  80728. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80729. this._ssaoPostProcess.onApply = function (effect) {
  80730. if (_this._firstUpdate) {
  80731. effect.setArray3("sampleSphere", _this._sampleSphere);
  80732. effect.setFloat("randTextureTiles", 32.0);
  80733. }
  80734. if (!_this._scene.activeCamera) {
  80735. return;
  80736. }
  80737. effect.setFloat("samplesFactor", 1 / _this.samples);
  80738. effect.setFloat("totalStrength", _this.totalStrength);
  80739. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  80740. effect.setFloat("radius", _this.radius);
  80741. effect.setFloat("maxZ", _this.maxZ);
  80742. effect.setFloat("minZAspect", _this.minZAspect);
  80743. effect.setFloat("base", _this.base);
  80744. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80745. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80746. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  80747. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  80748. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  80749. effect.setTexture("textureSampler", _this._depthTexture);
  80750. effect.setTexture("normalSampler", _this._normalTexture);
  80751. effect.setTexture("randomSampler", _this._randomTexture);
  80752. };
  80753. this._ssaoPostProcess.samples = this.textureSamples;
  80754. };
  80755. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80756. var _this = this;
  80757. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80758. this._ssaoCombinePostProcess.onApply = function (effect) {
  80759. var viewport = _this._scene.activeCamera.viewport;
  80760. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  80761. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80762. };
  80763. this._ssaoCombinePostProcess.samples = this.textureSamples;
  80764. };
  80765. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  80766. var size = 128;
  80767. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80768. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80769. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80770. var context = this._randomTexture.getContext();
  80771. var rand = function (min, max) {
  80772. return Math.random() * (max - min) + min;
  80773. };
  80774. var randVector = BABYLON.Vector3.Zero();
  80775. for (var x = 0; x < size; x++) {
  80776. for (var y = 0; y < size; y++) {
  80777. randVector.x = rand(0.0, 1.0);
  80778. randVector.y = rand(0.0, 1.0);
  80779. randVector.z = 0.0;
  80780. randVector.normalize();
  80781. randVector.scaleInPlace(255);
  80782. randVector.x = Math.floor(randVector.x);
  80783. randVector.y = Math.floor(randVector.y);
  80784. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80785. context.fillRect(x, y, 1, 1);
  80786. }
  80787. }
  80788. this._randomTexture.update(false);
  80789. };
  80790. /**
  80791. * Serialize the rendering pipeline (Used when exporting)
  80792. * @returns the serialized object
  80793. */
  80794. SSAO2RenderingPipeline.prototype.serialize = function () {
  80795. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80796. serializationObject.customType = "SSAO2RenderingPipeline";
  80797. return serializationObject;
  80798. };
  80799. /**
  80800. * Parse the serialized pipeline
  80801. * @param source Source pipeline.
  80802. * @param scene The scene to load the pipeline to.
  80803. * @param rootUrl The URL of the serialized pipeline.
  80804. * @returns An instantiated pipeline from the serialized object.
  80805. */
  80806. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  80807. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80808. };
  80809. __decorate([
  80810. BABYLON.serialize()
  80811. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  80812. __decorate([
  80813. BABYLON.serialize()
  80814. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  80815. __decorate([
  80816. BABYLON.serialize()
  80817. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  80818. __decorate([
  80819. BABYLON.serialize("samples")
  80820. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  80821. __decorate([
  80822. BABYLON.serialize("textureSamples")
  80823. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  80824. __decorate([
  80825. BABYLON.serialize()
  80826. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  80827. __decorate([
  80828. BABYLON.serialize("expensiveBlur")
  80829. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  80830. __decorate([
  80831. BABYLON.serialize()
  80832. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  80833. __decorate([
  80834. BABYLON.serialize()
  80835. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  80836. return SSAO2RenderingPipeline;
  80837. }(BABYLON.PostProcessRenderPipeline));
  80838. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  80839. })(BABYLON || (BABYLON = {}));
  80840. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  80841. // BABYLON.JS Chromatic Aberration GLSL Shader
  80842. // Author: Olivier Guyot
  80843. // Separates very slightly R, G and B colors on the edges of the screen
  80844. // Inspired by Francois Tarlier & Martins Upitis
  80845. var BABYLON;
  80846. (function (BABYLON) {
  80847. var LensRenderingPipeline = /** @class */ (function (_super) {
  80848. __extends(LensRenderingPipeline, _super);
  80849. /**
  80850. * @constructor
  80851. *
  80852. * Effect parameters are as follow:
  80853. * {
  80854. * chromatic_aberration: number; // from 0 to x (1 for realism)
  80855. * edge_blur: number; // from 0 to x (1 for realism)
  80856. * distortion: number; // from 0 to x (1 for realism)
  80857. * grain_amount: number; // from 0 to 1
  80858. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  80859. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  80860. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  80861. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  80862. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  80863. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  80864. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  80865. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  80866. * }
  80867. * Note: if an effect parameter is unset, effect is disabled
  80868. *
  80869. * @param {string} name - The rendering pipeline name
  80870. * @param {object} parameters - An object containing all parameters (see above)
  80871. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80872. * @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)
  80873. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80874. */
  80875. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  80876. if (ratio === void 0) { ratio = 1.0; }
  80877. var _this = _super.call(this, scene.getEngine(), name) || this;
  80878. // Lens effects can be of the following:
  80879. // - chromatic aberration (slight shift of RGB colors)
  80880. // - blur on the edge of the lens
  80881. // - lens distortion
  80882. // - depth-of-field blur & highlights enhancing
  80883. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  80884. // - grain effect (noise or custom texture)
  80885. // Two additional texture samplers are needed:
  80886. // - depth map (for depth-of-field)
  80887. // - grain texture
  80888. /**
  80889. * The chromatic aberration PostProcess id in the pipeline
  80890. */
  80891. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  80892. /**
  80893. * The highlights enhancing PostProcess id in the pipeline
  80894. */
  80895. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  80896. /**
  80897. * The depth-of-field PostProcess id in the pipeline
  80898. */
  80899. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  80900. _this._scene = scene;
  80901. // Fetch texture samplers
  80902. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80903. if (parameters.grain_texture) {
  80904. _this._grainTexture = parameters.grain_texture;
  80905. }
  80906. else {
  80907. _this._createGrainTexture();
  80908. }
  80909. // save parameters
  80910. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  80911. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  80912. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  80913. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  80914. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  80915. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  80916. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  80917. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  80918. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  80919. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  80920. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  80921. // Create effects
  80922. _this._createChromaticAberrationPostProcess(ratio);
  80923. _this._createHighlightsPostProcess(ratio);
  80924. _this._createDepthOfFieldPostProcess(ratio / 4);
  80925. // Set up pipeline
  80926. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  80927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  80928. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  80929. if (_this._highlightsGain === -1) {
  80930. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  80931. }
  80932. // Finish
  80933. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80934. if (cameras) {
  80935. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80936. }
  80937. return _this;
  80938. }
  80939. // public methods (self explanatory)
  80940. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  80941. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  80942. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  80943. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  80944. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  80945. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  80946. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  80947. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  80948. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  80949. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  80950. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  80951. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  80952. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  80953. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  80954. };
  80955. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  80956. this._highlightsPostProcess.updateEffect();
  80957. };
  80958. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  80959. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  80960. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  80961. this._highlightsGain = amount;
  80962. };
  80963. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  80964. if (this._highlightsGain === -1) {
  80965. this._highlightsGain = 1.0;
  80966. }
  80967. this._highlightsThreshold = amount;
  80968. };
  80969. LensRenderingPipeline.prototype.disableHighlights = function () {
  80970. this._highlightsGain = -1;
  80971. };
  80972. /**
  80973. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  80974. */
  80975. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80976. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80977. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80978. this._chromaticAberrationPostProcess = null;
  80979. this._highlightsPostProcess = null;
  80980. this._depthOfFieldPostProcess = null;
  80981. this._grainTexture.dispose();
  80982. if (disableDepthRender)
  80983. this._scene.disableDepthRenderer();
  80984. };
  80985. // colors shifting and distortion
  80986. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  80987. var _this = this;
  80988. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  80989. [], // samplers
  80990. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80991. this._chromaticAberrationPostProcess.onApply = function (effect) {
  80992. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  80993. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80994. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80995. effect.setFloat('radialIntensity', 1);
  80996. effect.setFloat2('direction', 17, 17);
  80997. effect.setFloat2('centerPosition', 0.5, 0.5);
  80998. };
  80999. };
  81000. // highlights enhancing
  81001. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81002. var _this = this;
  81003. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81004. [], // samplers
  81005. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81006. this._highlightsPostProcess.onApply = function (effect) {
  81007. effect.setFloat('gain', _this._highlightsGain);
  81008. effect.setFloat('threshold', _this._highlightsThreshold);
  81009. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81010. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81011. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81012. };
  81013. };
  81014. // colors shifting and distortion
  81015. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81016. var _this = this;
  81017. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81018. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81019. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81020. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81021. this._depthOfFieldPostProcess.onApply = function (effect) {
  81022. effect.setTexture("depthSampler", _this._depthTexture);
  81023. effect.setTexture("grainSampler", _this._grainTexture);
  81024. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81025. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81026. effect.setFloat('grain_amount', _this._grainAmount);
  81027. effect.setBool('blur_noise', _this._blurNoise);
  81028. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81029. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81030. effect.setFloat('distortion', _this._distortion);
  81031. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81032. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81033. effect.setFloat('aperture', _this._dofAperture);
  81034. effect.setFloat('darken', _this._dofDarken);
  81035. effect.setFloat('edge_blur', _this._edgeBlur);
  81036. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81037. if (_this._scene.activeCamera) {
  81038. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81039. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81040. }
  81041. };
  81042. };
  81043. // creates a black and white random noise texture, 512x512
  81044. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81045. var size = 512;
  81046. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81047. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81048. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81049. var context = this._grainTexture.getContext();
  81050. var rand = function (min, max) {
  81051. return Math.random() * (max - min) + min;
  81052. };
  81053. var value;
  81054. for (var x = 0; x < size; x++) {
  81055. for (var y = 0; y < size; y++) {
  81056. value = Math.floor(rand(0.42, 0.58) * 255);
  81057. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81058. context.fillRect(x, y, 1, 1);
  81059. }
  81060. }
  81061. this._grainTexture.update(false);
  81062. };
  81063. return LensRenderingPipeline;
  81064. }(BABYLON.PostProcessRenderPipeline));
  81065. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81066. })(BABYLON || (BABYLON = {}));
  81067. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81068. var BABYLON;
  81069. (function (BABYLON) {
  81070. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81071. __extends(StandardRenderingPipeline, _super);
  81072. /**
  81073. * @constructor
  81074. * @param {string} name - The rendering pipeline name
  81075. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81076. * @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)
  81077. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81078. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81079. */
  81080. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81081. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81082. var _this = _super.call(this, scene.getEngine(), name) || this;
  81083. /**
  81084. * Post-process used to down scale an image x4
  81085. */
  81086. _this.downSampleX4PostProcess = null;
  81087. /**
  81088. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81089. */
  81090. _this.brightPassPostProcess = null;
  81091. /**
  81092. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81093. */
  81094. _this.blurHPostProcesses = [];
  81095. /**
  81096. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81097. */
  81098. _this.blurVPostProcesses = [];
  81099. /**
  81100. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81101. */
  81102. _this.textureAdderPostProcess = null;
  81103. /**
  81104. * Post-process used to create volumetric lighting effect
  81105. */
  81106. _this.volumetricLightPostProcess = null;
  81107. /**
  81108. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81109. */
  81110. _this.volumetricLightSmoothXPostProcess = null;
  81111. /**
  81112. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81113. */
  81114. _this.volumetricLightSmoothYPostProcess = null;
  81115. /**
  81116. * Post-process used to merge the volumetric light effect and the real scene color
  81117. */
  81118. _this.volumetricLightMergePostProces = null;
  81119. /**
  81120. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81121. */
  81122. _this.volumetricLightFinalPostProcess = null;
  81123. /**
  81124. * Base post-process used to calculate the average luminance of the final image for HDR
  81125. */
  81126. _this.luminancePostProcess = null;
  81127. /**
  81128. * Post-processes used to create down sample post-processes in order to get
  81129. * the average luminance of the final image for HDR
  81130. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81131. */
  81132. _this.luminanceDownSamplePostProcesses = [];
  81133. /**
  81134. * Post-process used to create a HDR effect (light adaptation)
  81135. */
  81136. _this.hdrPostProcess = null;
  81137. /**
  81138. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81139. */
  81140. _this.textureAdderFinalPostProcess = null;
  81141. /**
  81142. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81143. */
  81144. _this.lensFlareFinalPostProcess = null;
  81145. /**
  81146. * Post-process used to merge the final HDR post-process and the real scene color
  81147. */
  81148. _this.hdrFinalPostProcess = null;
  81149. /**
  81150. * Post-process used to create a lens flare effect
  81151. */
  81152. _this.lensFlarePostProcess = null;
  81153. /**
  81154. * Post-process that merges the result of the lens flare post-process and the real scene color
  81155. */
  81156. _this.lensFlareComposePostProcess = null;
  81157. /**
  81158. * Post-process used to create a motion blur effect
  81159. */
  81160. _this.motionBlurPostProcess = null;
  81161. /**
  81162. * Post-process used to create a depth of field effect
  81163. */
  81164. _this.depthOfFieldPostProcess = null;
  81165. /**
  81166. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81167. */
  81168. _this.fxaaPostProcess = null;
  81169. // Values
  81170. /**
  81171. * Represents the brightness threshold in order to configure the illuminated surfaces
  81172. */
  81173. _this.brightThreshold = 1.0;
  81174. /**
  81175. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81176. */
  81177. _this.blurWidth = 512.0;
  81178. /**
  81179. * Sets if the blur for highlighted surfaces must be only horizontal
  81180. */
  81181. _this.horizontalBlur = false;
  81182. /**
  81183. * Sets the overall exposure used by the pipeline
  81184. */
  81185. _this.exposure = 1.0;
  81186. /**
  81187. * Texture used typically to simulate "dirty" on camera lens
  81188. */
  81189. _this.lensTexture = null;
  81190. /**
  81191. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81192. */
  81193. _this.volumetricLightCoefficient = 0.2;
  81194. /**
  81195. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81196. */
  81197. _this.volumetricLightPower = 4.0;
  81198. /**
  81199. * Used the set the blur intensity to smooth the volumetric lights
  81200. */
  81201. _this.volumetricLightBlurScale = 64.0;
  81202. /**
  81203. * Light (spot or directional) used to generate the volumetric lights rays
  81204. * The source light must have a shadow generate so the pipeline can get its
  81205. * depth map
  81206. */
  81207. _this.sourceLight = null;
  81208. /**
  81209. * For eye adaptation, represents the minimum luminance the eye can see
  81210. */
  81211. _this.hdrMinimumLuminance = 1.0;
  81212. /**
  81213. * For eye adaptation, represents the decrease luminance speed
  81214. */
  81215. _this.hdrDecreaseRate = 0.5;
  81216. /**
  81217. * For eye adaptation, represents the increase luminance speed
  81218. */
  81219. _this.hdrIncreaseRate = 0.5;
  81220. /**
  81221. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81222. */
  81223. _this.lensColorTexture = null;
  81224. /**
  81225. * The overall strengh for the lens flare effect
  81226. */
  81227. _this.lensFlareStrength = 20.0;
  81228. /**
  81229. * Dispersion coefficient for lens flare ghosts
  81230. */
  81231. _this.lensFlareGhostDispersal = 1.4;
  81232. /**
  81233. * Main lens flare halo width
  81234. */
  81235. _this.lensFlareHaloWidth = 0.7;
  81236. /**
  81237. * Based on the lens distortion effect, defines how much the lens flare result
  81238. * is distorted
  81239. */
  81240. _this.lensFlareDistortionStrength = 16.0;
  81241. /**
  81242. * Lens star texture must be used to simulate rays on the flares and is available
  81243. * in the documentation
  81244. */
  81245. _this.lensStarTexture = null;
  81246. /**
  81247. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81248. * flare effect by taking account of the dirt texture
  81249. */
  81250. _this.lensFlareDirtTexture = null;
  81251. /**
  81252. * Represents the focal length for the depth of field effect
  81253. */
  81254. _this.depthOfFieldDistance = 10.0;
  81255. /**
  81256. * Represents the blur intensity for the blurred part of the depth of field effect
  81257. */
  81258. _this.depthOfFieldBlurWidth = 64.0;
  81259. /**
  81260. * For motion blur, defines how much the image is blurred by the movement
  81261. */
  81262. _this.motionStrength = 1.0;
  81263. /**
  81264. * List of animations for the pipeline (IAnimatable implementation)
  81265. */
  81266. _this.animations = [];
  81267. _this._currentDepthOfFieldSource = null;
  81268. _this._hdrCurrentLuminance = 1.0;
  81269. // Getters and setters
  81270. _this._bloomEnabled = false;
  81271. _this._depthOfFieldEnabled = false;
  81272. _this._vlsEnabled = false;
  81273. _this._lensFlareEnabled = false;
  81274. _this._hdrEnabled = false;
  81275. _this._motionBlurEnabled = false;
  81276. _this._fxaaEnabled = false;
  81277. _this._motionBlurSamples = 64.0;
  81278. _this._volumetricLightStepsCount = 50.0;
  81279. _this._samples = 1;
  81280. _this._cameras = cameras || [];
  81281. // Initialize
  81282. _this._scene = scene;
  81283. _this._basePostProcess = originalPostProcess;
  81284. _this._ratio = ratio;
  81285. // Misc
  81286. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81287. // Finish
  81288. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81289. _this._buildPipeline();
  81290. return _this;
  81291. }
  81292. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  81293. /**
  81294. * Specifies if the bloom pipeline is enabled
  81295. */
  81296. get: function () {
  81297. return this._bloomEnabled;
  81298. },
  81299. set: function (enabled) {
  81300. if (this._bloomEnabled === enabled) {
  81301. return;
  81302. }
  81303. this._bloomEnabled = enabled;
  81304. this._buildPipeline();
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  81310. /**
  81311. * Specifies if the depth of field pipeline is enabed
  81312. */
  81313. get: function () {
  81314. return this._depthOfFieldEnabled;
  81315. },
  81316. set: function (enabled) {
  81317. if (this._depthOfFieldEnabled === enabled) {
  81318. return;
  81319. }
  81320. this._depthOfFieldEnabled = enabled;
  81321. this._buildPipeline();
  81322. },
  81323. enumerable: true,
  81324. configurable: true
  81325. });
  81326. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  81327. /**
  81328. * Specifies if the lens flare pipeline is enabed
  81329. */
  81330. get: function () {
  81331. return this._lensFlareEnabled;
  81332. },
  81333. set: function (enabled) {
  81334. if (this._lensFlareEnabled === enabled) {
  81335. return;
  81336. }
  81337. this._lensFlareEnabled = enabled;
  81338. this._buildPipeline();
  81339. },
  81340. enumerable: true,
  81341. configurable: true
  81342. });
  81343. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  81344. /**
  81345. * Specifies if the HDR pipeline is enabled
  81346. */
  81347. get: function () {
  81348. return this._hdrEnabled;
  81349. },
  81350. set: function (enabled) {
  81351. if (this._hdrEnabled === enabled) {
  81352. return;
  81353. }
  81354. this._hdrEnabled = enabled;
  81355. this._buildPipeline();
  81356. },
  81357. enumerable: true,
  81358. configurable: true
  81359. });
  81360. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  81361. /**
  81362. * Specifies if the volumetric lights scattering effect is enabled
  81363. */
  81364. get: function () {
  81365. return this._vlsEnabled;
  81366. },
  81367. set: function (enabled) {
  81368. if (this._vlsEnabled === enabled) {
  81369. return;
  81370. }
  81371. if (enabled) {
  81372. var geometry = this._scene.enableGeometryBufferRenderer();
  81373. if (!geometry) {
  81374. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  81375. return;
  81376. }
  81377. }
  81378. this._vlsEnabled = enabled;
  81379. this._buildPipeline();
  81380. },
  81381. enumerable: true,
  81382. configurable: true
  81383. });
  81384. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  81385. /**
  81386. * Specifies if the motion blur effect is enabled
  81387. */
  81388. get: function () {
  81389. return this._motionBlurEnabled;
  81390. },
  81391. set: function (enabled) {
  81392. if (this._motionBlurEnabled === enabled) {
  81393. return;
  81394. }
  81395. this._motionBlurEnabled = enabled;
  81396. this._buildPipeline();
  81397. },
  81398. enumerable: true,
  81399. configurable: true
  81400. });
  81401. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  81402. /**
  81403. * Specifies if anti-aliasing is enabled
  81404. */
  81405. get: function () {
  81406. return this._fxaaEnabled;
  81407. },
  81408. set: function (enabled) {
  81409. if (this._fxaaEnabled === enabled) {
  81410. return;
  81411. }
  81412. this._fxaaEnabled = enabled;
  81413. this._buildPipeline();
  81414. },
  81415. enumerable: true,
  81416. configurable: true
  81417. });
  81418. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  81419. /**
  81420. * Specifies the number of steps used to calculate the volumetric lights
  81421. * Typically in interval [50, 200]
  81422. */
  81423. get: function () {
  81424. return this._volumetricLightStepsCount;
  81425. },
  81426. set: function (count) {
  81427. if (this.volumetricLightPostProcess) {
  81428. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  81429. }
  81430. this._volumetricLightStepsCount = count;
  81431. },
  81432. enumerable: true,
  81433. configurable: true
  81434. });
  81435. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  81436. /**
  81437. * Specifies the number of samples used for the motion blur effect
  81438. * Typically in interval [16, 64]
  81439. */
  81440. get: function () {
  81441. return this._motionBlurSamples;
  81442. },
  81443. set: function (samples) {
  81444. if (this.motionBlurPostProcess) {
  81445. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  81446. }
  81447. this._motionBlurSamples = samples;
  81448. },
  81449. enumerable: true,
  81450. configurable: true
  81451. });
  81452. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  81453. /**
  81454. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81455. */
  81456. get: function () {
  81457. return this._samples;
  81458. },
  81459. set: function (sampleCount) {
  81460. if (this._samples === sampleCount) {
  81461. return;
  81462. }
  81463. this._samples = sampleCount;
  81464. this._buildPipeline();
  81465. },
  81466. enumerable: true,
  81467. configurable: true
  81468. });
  81469. StandardRenderingPipeline.prototype._buildPipeline = function () {
  81470. var _this = this;
  81471. var ratio = this._ratio;
  81472. var scene = this._scene;
  81473. this._disposePostProcesses();
  81474. this._reset();
  81475. // Create pass post-process
  81476. if (!this._basePostProcess) {
  81477. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  81478. this.originalPostProcess.onApply = function (effect) {
  81479. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  81480. };
  81481. }
  81482. else {
  81483. this.originalPostProcess = this._basePostProcess;
  81484. }
  81485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  81486. this._currentDepthOfFieldSource = this.originalPostProcess;
  81487. if (this._bloomEnabled) {
  81488. // Create down sample X4 post-process
  81489. this._createDownSampleX4PostProcess(scene, ratio / 2);
  81490. // Create bright pass post-process
  81491. this._createBrightPassPostProcess(scene, ratio / 2);
  81492. // Create gaussian blur post-processes (down sampling blurs)
  81493. this._createBlurPostProcesses(scene, ratio / 4, 1);
  81494. // Create texture adder post-process
  81495. this._createTextureAdderPostProcess(scene, ratio);
  81496. // Create depth-of-field source post-process
  81497. 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);
  81498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  81499. }
  81500. if (this._vlsEnabled) {
  81501. // Create volumetric light
  81502. this._createVolumetricLightPostProcess(scene, ratio);
  81503. // Create volumetric light final post-process
  81504. 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);
  81505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  81506. }
  81507. if (this._lensFlareEnabled) {
  81508. // Create lens flare post-process
  81509. this._createLensFlarePostProcess(scene, ratio);
  81510. // Create depth-of-field source post-process post lens-flare and disable it now
  81511. 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);
  81512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  81513. }
  81514. if (this._hdrEnabled) {
  81515. // Create luminance
  81516. this._createLuminancePostProcesses(scene, this._floatTextureType);
  81517. // Create HDR
  81518. this._createHdrPostProcess(scene, ratio);
  81519. // Create depth-of-field source post-process post hdr and disable it now
  81520. 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);
  81521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  81522. }
  81523. if (this._depthOfFieldEnabled) {
  81524. // Create gaussian blur used by depth-of-field
  81525. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  81526. // Create depth-of-field post-process
  81527. this._createDepthOfFieldPostProcess(scene, ratio);
  81528. }
  81529. if (this._motionBlurEnabled) {
  81530. // Create motion blur post-process
  81531. this._createMotionBlurPostProcess(scene, ratio);
  81532. }
  81533. if (this._fxaaEnabled) {
  81534. // Create fxaa post-process
  81535. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  81537. }
  81538. if (this._cameras !== null) {
  81539. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81540. }
  81541. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  81542. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81543. }
  81544. };
  81545. // Down Sample X4 Post-Processs
  81546. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  81547. var _this = this;
  81548. var downSampleX4Offsets = new Array(32);
  81549. 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);
  81550. this.downSampleX4PostProcess.onApply = function (effect) {
  81551. var id = 0;
  81552. var width = _this.downSampleX4PostProcess.width;
  81553. var height = _this.downSampleX4PostProcess.height;
  81554. for (var i = -2; i < 2; i++) {
  81555. for (var j = -2; j < 2; j++) {
  81556. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  81557. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  81558. id += 2;
  81559. }
  81560. }
  81561. effect.setArray2("dsOffsets", downSampleX4Offsets);
  81562. };
  81563. // Add to pipeline
  81564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  81565. };
  81566. // Brightpass Post-Process
  81567. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  81568. var _this = this;
  81569. var brightOffsets = new Array(8);
  81570. 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);
  81571. this.brightPassPostProcess.onApply = function (effect) {
  81572. var sU = (1.0 / _this.brightPassPostProcess.width);
  81573. var sV = (1.0 / _this.brightPassPostProcess.height);
  81574. brightOffsets[0] = -0.5 * sU;
  81575. brightOffsets[1] = 0.5 * sV;
  81576. brightOffsets[2] = 0.5 * sU;
  81577. brightOffsets[3] = 0.5 * sV;
  81578. brightOffsets[4] = -0.5 * sU;
  81579. brightOffsets[5] = -0.5 * sV;
  81580. brightOffsets[6] = 0.5 * sU;
  81581. brightOffsets[7] = -0.5 * sV;
  81582. effect.setArray2("dsOffsets", brightOffsets);
  81583. effect.setFloat("brightThreshold", _this.brightThreshold);
  81584. };
  81585. // Add to pipeline
  81586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  81587. };
  81588. // Create blur H&V post-processes
  81589. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  81590. var _this = this;
  81591. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  81592. var engine = scene.getEngine();
  81593. 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);
  81594. 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);
  81595. blurX.onActivateObservable.add(function () {
  81596. var dw = blurX.width / engine.getRenderWidth();
  81597. blurX.kernel = _this[blurWidthKey] * dw;
  81598. });
  81599. blurY.onActivateObservable.add(function () {
  81600. var dw = blurY.height / engine.getRenderHeight();
  81601. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  81602. });
  81603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  81604. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  81605. this.blurHPostProcesses.push(blurX);
  81606. this.blurVPostProcesses.push(blurY);
  81607. };
  81608. // Create texture adder post-process
  81609. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  81610. var _this = this;
  81611. 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);
  81612. this.textureAdderPostProcess.onApply = function (effect) {
  81613. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  81614. effect.setTexture("lensSampler", _this.lensTexture);
  81615. effect.setFloat("exposure", _this.exposure);
  81616. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  81617. };
  81618. // Add to pipeline
  81619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  81620. };
  81621. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  81622. var _this = this;
  81623. var geometryRenderer = scene.enableGeometryBufferRenderer();
  81624. geometryRenderer.enablePosition = true;
  81625. var geometry = geometryRenderer.getGBuffer();
  81626. // Base post-process
  81627. 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));
  81628. var depthValues = BABYLON.Vector2.Zero();
  81629. this.volumetricLightPostProcess.onApply = function (effect) {
  81630. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  81631. var generator = _this.sourceLight.getShadowGenerator();
  81632. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  81633. effect.setTexture("positionSampler", geometry.textures[2]);
  81634. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  81635. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  81636. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  81637. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  81638. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  81639. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  81640. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  81641. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  81642. effect.setVector2("depthValues", depthValues);
  81643. }
  81644. };
  81645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  81646. // Smooth
  81647. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  81648. // Merge
  81649. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  81650. this.volumetricLightMergePostProces.onApply = function (effect) {
  81651. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  81652. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  81653. };
  81654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  81655. };
  81656. // Create luminance
  81657. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  81658. var _this = this;
  81659. // Create luminance
  81660. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  81661. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  81662. var offsets = [];
  81663. this.luminancePostProcess.onApply = function (effect) {
  81664. var sU = (1.0 / _this.luminancePostProcess.width);
  81665. var sV = (1.0 / _this.luminancePostProcess.height);
  81666. offsets[0] = -0.5 * sU;
  81667. offsets[1] = 0.5 * sV;
  81668. offsets[2] = 0.5 * sU;
  81669. offsets[3] = 0.5 * sV;
  81670. offsets[4] = -0.5 * sU;
  81671. offsets[5] = -0.5 * sV;
  81672. offsets[6] = 0.5 * sU;
  81673. offsets[7] = -0.5 * sV;
  81674. effect.setArray2("lumOffsets", offsets);
  81675. };
  81676. // Add to pipeline
  81677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  81678. // Create down sample luminance
  81679. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  81680. var size = Math.pow(3, i);
  81681. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  81682. if (i === 0) {
  81683. defines += "#define FINAL_DOWN_SAMPLER";
  81684. }
  81685. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  81686. this.luminanceDownSamplePostProcesses.push(postProcess);
  81687. }
  81688. // Create callbacks and add effects
  81689. var lastLuminance = this.luminancePostProcess;
  81690. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  81691. var downSampleOffsets = new Array(18);
  81692. pp.onApply = function (effect) {
  81693. if (!lastLuminance) {
  81694. return;
  81695. }
  81696. var id = 0;
  81697. for (var x = -1; x < 2; x++) {
  81698. for (var y = -1; y < 2; y++) {
  81699. downSampleOffsets[id] = x / lastLuminance.width;
  81700. downSampleOffsets[id + 1] = y / lastLuminance.height;
  81701. id += 2;
  81702. }
  81703. }
  81704. effect.setArray2("dsOffsets", downSampleOffsets);
  81705. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  81706. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81707. lastLuminance = _this.luminancePostProcess;
  81708. }
  81709. else {
  81710. lastLuminance = pp;
  81711. }
  81712. };
  81713. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81714. pp.onAfterRender = function (effect) {
  81715. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  81716. 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);
  81717. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  81718. };
  81719. }
  81720. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  81721. });
  81722. };
  81723. // Create HDR post-process
  81724. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  81725. var _this = this;
  81726. 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);
  81727. var outputLiminance = 1;
  81728. var time = 0;
  81729. var lastTime = 0;
  81730. this.hdrPostProcess.onApply = function (effect) {
  81731. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  81732. time += scene.getEngine().getDeltaTime();
  81733. if (outputLiminance < 0) {
  81734. outputLiminance = _this._hdrCurrentLuminance;
  81735. }
  81736. else {
  81737. var dt = (lastTime - time) / 1000.0;
  81738. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  81739. outputLiminance += _this.hdrDecreaseRate * dt;
  81740. }
  81741. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  81742. outputLiminance -= _this.hdrIncreaseRate * dt;
  81743. }
  81744. else {
  81745. outputLiminance = _this._hdrCurrentLuminance;
  81746. }
  81747. }
  81748. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  81749. effect.setFloat("averageLuminance", outputLiminance);
  81750. lastTime = time;
  81751. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  81752. };
  81753. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  81754. };
  81755. // Create lens flare post-process
  81756. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  81757. var _this = this;
  81758. 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);
  81759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  81760. this._createBlurPostProcesses(scene, ratio / 4, 2);
  81761. 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);
  81762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  81763. var resolution = new BABYLON.Vector2(0, 0);
  81764. // Lens flare
  81765. this.lensFlarePostProcess.onApply = function (effect) {
  81766. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  81767. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  81768. effect.setFloat("strength", _this.lensFlareStrength);
  81769. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  81770. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  81771. // Shift
  81772. resolution.x = _this.lensFlarePostProcess.width;
  81773. resolution.y = _this.lensFlarePostProcess.height;
  81774. effect.setVector2("resolution", resolution);
  81775. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  81776. };
  81777. // Compose
  81778. 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);
  81779. 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);
  81780. this.lensFlareComposePostProcess.onApply = function (effect) {
  81781. if (!_this._scene.activeCamera) {
  81782. return;
  81783. }
  81784. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81785. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  81786. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  81787. // Lens start rotation matrix
  81788. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  81789. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  81790. 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));
  81791. camRot *= 4.0;
  81792. 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);
  81793. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  81794. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  81795. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  81796. };
  81797. };
  81798. // Create depth-of-field post-process
  81799. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  81800. var _this = this;
  81801. 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);
  81802. this.depthOfFieldPostProcess.onApply = function (effect) {
  81803. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81804. effect.setTexture("depthSampler", _this._getDepthTexture());
  81805. effect.setFloat("distance", _this.depthOfFieldDistance);
  81806. };
  81807. // Add to pipeline
  81808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  81809. };
  81810. // Create motion blur post-process
  81811. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  81812. var _this = this;
  81813. 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);
  81814. var motionScale = 0;
  81815. var prevViewProjection = BABYLON.Matrix.Identity();
  81816. var invViewProjection = BABYLON.Matrix.Identity();
  81817. var viewProjection = BABYLON.Matrix.Identity();
  81818. var screenSize = BABYLON.Vector2.Zero();
  81819. this.motionBlurPostProcess.onApply = function (effect) {
  81820. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  81821. viewProjection.invertToRef(invViewProjection);
  81822. effect.setMatrix("inverseViewProjection", invViewProjection);
  81823. effect.setMatrix("prevViewProjection", prevViewProjection);
  81824. prevViewProjection = viewProjection;
  81825. screenSize.x = _this.motionBlurPostProcess.width;
  81826. screenSize.y = _this.motionBlurPostProcess.height;
  81827. effect.setVector2("screenSize", screenSize);
  81828. motionScale = scene.getEngine().getFps() / 60.0;
  81829. effect.setFloat("motionScale", motionScale);
  81830. effect.setFloat("motionStrength", _this.motionStrength);
  81831. effect.setTexture("depthSampler", _this._getDepthTexture());
  81832. };
  81833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  81834. };
  81835. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  81836. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  81837. var renderer = this._scene.enableGeometryBufferRenderer();
  81838. return renderer.getGBuffer().textures[0];
  81839. }
  81840. return this._scene.enableDepthRenderer().getDepthMap();
  81841. };
  81842. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  81843. for (var i = 0; i < this._cameras.length; i++) {
  81844. var camera = this._cameras[i];
  81845. if (this.originalPostProcess) {
  81846. this.originalPostProcess.dispose(camera);
  81847. }
  81848. if (this.downSampleX4PostProcess) {
  81849. this.downSampleX4PostProcess.dispose(camera);
  81850. }
  81851. if (this.brightPassPostProcess) {
  81852. this.brightPassPostProcess.dispose(camera);
  81853. }
  81854. if (this.textureAdderPostProcess) {
  81855. this.textureAdderPostProcess.dispose(camera);
  81856. }
  81857. if (this.textureAdderFinalPostProcess) {
  81858. this.textureAdderFinalPostProcess.dispose(camera);
  81859. }
  81860. if (this.volumetricLightPostProcess) {
  81861. this.volumetricLightPostProcess.dispose(camera);
  81862. }
  81863. if (this.volumetricLightSmoothXPostProcess) {
  81864. this.volumetricLightSmoothXPostProcess.dispose(camera);
  81865. }
  81866. if (this.volumetricLightSmoothYPostProcess) {
  81867. this.volumetricLightSmoothYPostProcess.dispose(camera);
  81868. }
  81869. if (this.volumetricLightMergePostProces) {
  81870. this.volumetricLightMergePostProces.dispose(camera);
  81871. }
  81872. if (this.volumetricLightFinalPostProcess) {
  81873. this.volumetricLightFinalPostProcess.dispose(camera);
  81874. }
  81875. if (this.lensFlarePostProcess) {
  81876. this.lensFlarePostProcess.dispose(camera);
  81877. }
  81878. if (this.lensFlareComposePostProcess) {
  81879. this.lensFlareComposePostProcess.dispose(camera);
  81880. }
  81881. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  81882. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  81883. }
  81884. if (this.luminancePostProcess) {
  81885. this.luminancePostProcess.dispose(camera);
  81886. }
  81887. if (this.hdrPostProcess) {
  81888. this.hdrPostProcess.dispose(camera);
  81889. }
  81890. if (this.hdrFinalPostProcess) {
  81891. this.hdrFinalPostProcess.dispose(camera);
  81892. }
  81893. if (this.depthOfFieldPostProcess) {
  81894. this.depthOfFieldPostProcess.dispose(camera);
  81895. }
  81896. if (this.motionBlurPostProcess) {
  81897. this.motionBlurPostProcess.dispose(camera);
  81898. }
  81899. if (this.fxaaPostProcess) {
  81900. this.fxaaPostProcess.dispose(camera);
  81901. }
  81902. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  81903. this.blurHPostProcesses[j].dispose(camera);
  81904. }
  81905. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  81906. this.blurVPostProcesses[j].dispose(camera);
  81907. }
  81908. }
  81909. this.originalPostProcess = null;
  81910. this.downSampleX4PostProcess = null;
  81911. this.brightPassPostProcess = null;
  81912. this.textureAdderPostProcess = null;
  81913. this.textureAdderFinalPostProcess = null;
  81914. this.volumetricLightPostProcess = null;
  81915. this.volumetricLightSmoothXPostProcess = null;
  81916. this.volumetricLightSmoothYPostProcess = null;
  81917. this.volumetricLightMergePostProces = null;
  81918. this.volumetricLightFinalPostProcess = null;
  81919. this.lensFlarePostProcess = null;
  81920. this.lensFlareComposePostProcess = null;
  81921. this.luminancePostProcess = null;
  81922. this.hdrPostProcess = null;
  81923. this.hdrFinalPostProcess = null;
  81924. this.depthOfFieldPostProcess = null;
  81925. this.motionBlurPostProcess = null;
  81926. this.fxaaPostProcess = null;
  81927. this.luminanceDownSamplePostProcesses = [];
  81928. this.blurHPostProcesses = [];
  81929. this.blurVPostProcesses = [];
  81930. };
  81931. /**
  81932. * Dispose of the pipeline and stop all post processes
  81933. */
  81934. StandardRenderingPipeline.prototype.dispose = function () {
  81935. this._disposePostProcesses();
  81936. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81937. _super.prototype.dispose.call(this);
  81938. };
  81939. /**
  81940. * Serialize the rendering pipeline (Used when exporting)
  81941. * @returns the serialized object
  81942. */
  81943. StandardRenderingPipeline.prototype.serialize = function () {
  81944. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81945. if (this.sourceLight) {
  81946. serializationObject.sourceLightId = this.sourceLight.id;
  81947. }
  81948. serializationObject.customType = "StandardRenderingPipeline";
  81949. return serializationObject;
  81950. };
  81951. /**
  81952. * Parse the serialized pipeline
  81953. * @param source Source pipeline.
  81954. * @param scene The scene to load the pipeline to.
  81955. * @param rootUrl The URL of the serialized pipeline.
  81956. * @returns An instantiated pipeline from the serialized object.
  81957. */
  81958. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81959. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81960. if (source.sourceLightId) {
  81961. p.sourceLight = scene.getLightByID(source.sourceLightId);
  81962. }
  81963. return p;
  81964. };
  81965. // Luminance steps
  81966. StandardRenderingPipeline.LuminanceSteps = 6;
  81967. __decorate([
  81968. BABYLON.serialize()
  81969. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  81970. __decorate([
  81971. BABYLON.serialize()
  81972. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  81973. __decorate([
  81974. BABYLON.serialize()
  81975. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  81976. __decorate([
  81977. BABYLON.serialize()
  81978. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  81979. __decorate([
  81980. BABYLON.serializeAsTexture("lensTexture")
  81981. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  81982. __decorate([
  81983. BABYLON.serialize()
  81984. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  81985. __decorate([
  81986. BABYLON.serialize()
  81987. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  81988. __decorate([
  81989. BABYLON.serialize()
  81990. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  81991. __decorate([
  81992. BABYLON.serialize()
  81993. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  81994. __decorate([
  81995. BABYLON.serialize()
  81996. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  81997. __decorate([
  81998. BABYLON.serialize()
  81999. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82000. __decorate([
  82001. BABYLON.serializeAsTexture("lensColorTexture")
  82002. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82003. __decorate([
  82004. BABYLON.serialize()
  82005. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82006. __decorate([
  82007. BABYLON.serialize()
  82008. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82009. __decorate([
  82010. BABYLON.serialize()
  82011. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82012. __decorate([
  82013. BABYLON.serialize()
  82014. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82015. __decorate([
  82016. BABYLON.serializeAsTexture("lensStarTexture")
  82017. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82018. __decorate([
  82019. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82020. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82021. __decorate([
  82022. BABYLON.serialize()
  82023. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82024. __decorate([
  82025. BABYLON.serialize()
  82026. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82027. __decorate([
  82028. BABYLON.serialize()
  82029. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82030. __decorate([
  82031. BABYLON.serialize()
  82032. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82033. __decorate([
  82034. BABYLON.serialize()
  82035. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82036. __decorate([
  82037. BABYLON.serialize()
  82038. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82039. __decorate([
  82040. BABYLON.serialize()
  82041. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82042. __decorate([
  82043. BABYLON.serialize()
  82044. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82045. __decorate([
  82046. BABYLON.serialize()
  82047. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82048. __decorate([
  82049. BABYLON.serialize()
  82050. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82051. __decorate([
  82052. BABYLON.serialize()
  82053. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82054. __decorate([
  82055. BABYLON.serialize()
  82056. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82057. __decorate([
  82058. BABYLON.serialize()
  82059. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82060. __decorate([
  82061. BABYLON.serialize()
  82062. ], StandardRenderingPipeline.prototype, "samples", null);
  82063. return StandardRenderingPipeline;
  82064. }(BABYLON.PostProcessRenderPipeline));
  82065. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82066. })(BABYLON || (BABYLON = {}));
  82067. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82068. var BABYLON;
  82069. (function (BABYLON) {
  82070. var FxaaPostProcess = /** @class */ (function (_super) {
  82071. __extends(FxaaPostProcess, _super);
  82072. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82073. if (camera === void 0) { camera = null; }
  82074. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82075. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82076. var defines = _this._getDefines();
  82077. _this.updateEffect(defines);
  82078. _this.onApplyObservable.add(function (effect) {
  82079. var texelSize = _this.texelSize;
  82080. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82081. });
  82082. return _this;
  82083. }
  82084. FxaaPostProcess.prototype._getDefines = function () {
  82085. var engine = this.getEngine();
  82086. if (!engine) {
  82087. return null;
  82088. }
  82089. var glInfo = engine.getGlInfo();
  82090. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82091. return "#define MALI 1\n";
  82092. }
  82093. return null;
  82094. };
  82095. return FxaaPostProcess;
  82096. }(BABYLON.PostProcess));
  82097. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82098. })(BABYLON || (BABYLON = {}));
  82099. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82100. var BABYLON;
  82101. (function (BABYLON) {
  82102. /**
  82103. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82104. */
  82105. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82106. __extends(ChromaticAberrationPostProcess, _super);
  82107. /**
  82108. * Creates a new instance ChromaticAberrationPostProcess
  82109. * @param name The name of the effect.
  82110. * @param screenWidth The width of the screen to apply the effect on.
  82111. * @param screenHeight The height of the screen to apply the effect on.
  82112. * @param options The required width/height ratio to downsize to before computing the render pass.
  82113. * @param camera The camera to apply the render pass to.
  82114. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82115. * @param engine The engine which the post process will be applied. (default: current engine)
  82116. * @param reusable If the post process can be reused on the same frame. (default: false)
  82117. * @param textureType Type of textures used when performing the post process. (default: 0)
  82118. * @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)
  82119. */
  82120. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82122. if (blockCompilation === void 0) { blockCompilation = false; }
  82123. 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;
  82124. /**
  82125. * The amount of seperation of rgb channels (default: 30)
  82126. */
  82127. _this.aberrationAmount = 30;
  82128. /**
  82129. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82130. */
  82131. _this.radialIntensity = 0;
  82132. /**
  82133. * 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))
  82134. */
  82135. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82136. /**
  82137. * 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))
  82138. */
  82139. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82140. _this.onApplyObservable.add(function (effect) {
  82141. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82142. effect.setFloat('screen_width', screenWidth);
  82143. effect.setFloat('screen_height', screenHeight);
  82144. effect.setFloat('radialIntensity', _this.radialIntensity);
  82145. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82146. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82147. });
  82148. return _this;
  82149. }
  82150. return ChromaticAberrationPostProcess;
  82151. }(BABYLON.PostProcess));
  82152. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82153. })(BABYLON || (BABYLON = {}));
  82154. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82155. var BABYLON;
  82156. (function (BABYLON) {
  82157. /**
  82158. * The GrainPostProcess adds noise to the image at mid luminance levels
  82159. */
  82160. var GrainPostProcess = /** @class */ (function (_super) {
  82161. __extends(GrainPostProcess, _super);
  82162. /**
  82163. * Creates a new instance of @see GrainPostProcess
  82164. * @param name The name of the effect.
  82165. * @param options The required width/height ratio to downsize to before computing the render pass.
  82166. * @param camera The camera to apply the render pass to.
  82167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82168. * @param engine The engine which the post process will be applied. (default: current engine)
  82169. * @param reusable If the post process can be reused on the same frame. (default: false)
  82170. * @param textureType Type of textures used when performing the post process. (default: 0)
  82171. * @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)
  82172. */
  82173. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82174. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82175. if (blockCompilation === void 0) { blockCompilation = false; }
  82176. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82177. /**
  82178. * The intensity of the grain added (default: 30)
  82179. */
  82180. _this.intensity = 30;
  82181. /**
  82182. * If the grain should be randomized on every frame
  82183. */
  82184. _this.animated = false;
  82185. _this.onApplyObservable.add(function (effect) {
  82186. effect.setFloat('intensity', _this.intensity);
  82187. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82188. });
  82189. return _this;
  82190. }
  82191. return GrainPostProcess;
  82192. }(BABYLON.PostProcess));
  82193. BABYLON.GrainPostProcess = GrainPostProcess;
  82194. })(BABYLON || (BABYLON = {}));
  82195. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82196. var BABYLON;
  82197. (function (BABYLON) {
  82198. /**
  82199. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82200. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82201. */
  82202. var SharpenPostProcess = /** @class */ (function (_super) {
  82203. __extends(SharpenPostProcess, _super);
  82204. /**
  82205. * Creates a new instance ConvolutionPostProcess
  82206. * @param name The name of the effect.
  82207. * @param options The required width/height ratio to downsize to before computing the render pass.
  82208. * @param camera The camera to apply the render pass to.
  82209. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82210. * @param engine The engine which the post process will be applied. (default: current engine)
  82211. * @param reusable If the post process can be reused on the same frame. (default: false)
  82212. * @param textureType Type of textures used when performing the post process. (default: 0)
  82213. * @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)
  82214. */
  82215. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82216. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82217. if (blockCompilation === void 0) { blockCompilation = false; }
  82218. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82219. /**
  82220. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82221. */
  82222. _this.colorAmount = 1.0;
  82223. /**
  82224. * How much sharpness should be applied (default: 0.3)
  82225. */
  82226. _this.edgeAmount = 0.3;
  82227. _this.onApply = function (effect) {
  82228. effect.setFloat2("screenSize", _this.width, _this.height);
  82229. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82230. };
  82231. return _this;
  82232. }
  82233. return SharpenPostProcess;
  82234. }(BABYLON.PostProcess));
  82235. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82236. })(BABYLON || (BABYLON = {}));
  82237. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82238. var BABYLON;
  82239. (function (BABYLON) {
  82240. /**
  82241. * The Blur Post Process which blurs an image based on a kernel and direction.
  82242. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82243. */
  82244. var BlurPostProcess = /** @class */ (function (_super) {
  82245. __extends(BlurPostProcess, _super);
  82246. /**
  82247. * Creates a new instance BlurPostProcess
  82248. * @param name The name of the effect.
  82249. * @param direction The direction in which to blur the image.
  82250. * @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.
  82251. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82252. * @param camera The camera to apply the render pass to.
  82253. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82254. * @param engine The engine which the post process will be applied. (default: current engine)
  82255. * @param reusable If the post process can be reused on the same frame. (default: false)
  82256. * @param textureType Type of textures used when performing the post process. (default: 0)
  82257. * @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)
  82258. */
  82259. function BlurPostProcess(name,
  82260. /** The direction in which to blur the image. */
  82261. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82262. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82264. if (defines === void 0) { defines = ""; }
  82265. if (blockCompilation === void 0) { blockCompilation = false; }
  82266. 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;
  82267. _this.direction = direction;
  82268. _this.blockCompilation = blockCompilation;
  82269. _this._packedFloat = false;
  82270. _this._staticDefines = "";
  82271. _this._staticDefines = defines;
  82272. _this.onApplyObservable.add(function (effect) {
  82273. if (_this._outputTexture) {
  82274. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82275. }
  82276. else {
  82277. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82278. }
  82279. });
  82280. _this.kernel = kernel;
  82281. return _this;
  82282. }
  82283. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82284. /**
  82285. * Gets the length in pixels of the blur sample region
  82286. */
  82287. get: function () {
  82288. return this._idealKernel;
  82289. },
  82290. /**
  82291. * Sets the length in pixels of the blur sample region
  82292. */
  82293. set: function (v) {
  82294. if (this._idealKernel === v) {
  82295. return;
  82296. }
  82297. v = Math.max(v, 1);
  82298. this._idealKernel = v;
  82299. this._kernel = this._nearestBestKernel(v);
  82300. if (!this.blockCompilation) {
  82301. this._updateParameters();
  82302. }
  82303. },
  82304. enumerable: true,
  82305. configurable: true
  82306. });
  82307. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  82308. /**
  82309. * Gets wether or not the blur is unpacking/repacking floats
  82310. */
  82311. get: function () {
  82312. return this._packedFloat;
  82313. },
  82314. /**
  82315. * Sets wether or not the blur needs to unpack/repack floats
  82316. */
  82317. set: function (v) {
  82318. if (this._packedFloat === v) {
  82319. return;
  82320. }
  82321. this._packedFloat = v;
  82322. if (!this.blockCompilation) {
  82323. this._updateParameters();
  82324. }
  82325. },
  82326. enumerable: true,
  82327. configurable: true
  82328. });
  82329. /**
  82330. * Updates the effect with the current post process compile time values and recompiles the shader.
  82331. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82332. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82333. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82334. * @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
  82335. * @param onCompiled Called when the shader has been compiled.
  82336. * @param onError Called if there is an error when compiling a shader.
  82337. */
  82338. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82339. if (defines === void 0) { defines = null; }
  82340. if (uniforms === void 0) { uniforms = null; }
  82341. if (samplers === void 0) { samplers = null; }
  82342. this._updateParameters(onCompiled, onError);
  82343. };
  82344. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  82345. // Generate sampling offsets and weights
  82346. var N = this._kernel;
  82347. var centerIndex = (N - 1) / 2;
  82348. // Generate Gaussian sampling weights over kernel
  82349. var offsets = [];
  82350. var weights = [];
  82351. var totalWeight = 0;
  82352. for (var i = 0; i < N; i++) {
  82353. var u = i / (N - 1);
  82354. var w = this._gaussianWeight(u * 2.0 - 1);
  82355. offsets[i] = (i - centerIndex);
  82356. weights[i] = w;
  82357. totalWeight += w;
  82358. }
  82359. // Normalize weights
  82360. for (var i = 0; i < weights.length; i++) {
  82361. weights[i] /= totalWeight;
  82362. }
  82363. // Optimize: combine samples to take advantage of hardware linear sampling
  82364. // Walk from left to center, combining pairs (symmetrically)
  82365. var linearSamplingWeights = [];
  82366. var linearSamplingOffsets = [];
  82367. var linearSamplingMap = [];
  82368. for (var i = 0; i <= centerIndex; i += 2) {
  82369. var j = Math.min(i + 1, Math.floor(centerIndex));
  82370. var singleCenterSample = i === j;
  82371. if (singleCenterSample) {
  82372. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82373. }
  82374. else {
  82375. var sharedCell = j === centerIndex;
  82376. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  82377. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  82378. if (offsetLinear === 0) {
  82379. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82380. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  82381. }
  82382. else {
  82383. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  82384. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  82385. }
  82386. }
  82387. }
  82388. for (var i = 0; i < linearSamplingMap.length; i++) {
  82389. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  82390. linearSamplingWeights[i] = linearSamplingMap[i].w;
  82391. }
  82392. // Replace with optimized
  82393. offsets = linearSamplingOffsets;
  82394. weights = linearSamplingWeights;
  82395. // Generate shaders
  82396. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  82397. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  82398. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  82399. var defines = "";
  82400. defines += this._staticDefines;
  82401. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  82402. if (this._staticDefines.indexOf("DOF") != -1) {
  82403. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  82404. varyingCount--;
  82405. }
  82406. for (var i = 0; i < varyingCount; i++) {
  82407. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  82408. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  82409. }
  82410. var depCount = 0;
  82411. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  82412. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  82413. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  82414. depCount++;
  82415. }
  82416. if (this.packedFloat) {
  82417. defines += "#define PACKEDFLOAT 1";
  82418. }
  82419. this.blockCompilation = false;
  82420. _super.prototype.updateEffect.call(this, defines, null, null, {
  82421. varyingCount: varyingCount,
  82422. depCount: depCount
  82423. }, onCompiled, onError);
  82424. };
  82425. /**
  82426. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  82427. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  82428. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  82429. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  82430. * The gaps between physical kernels are compensated for in the weighting of the samples
  82431. * @param idealKernel Ideal blur kernel.
  82432. * @return Nearest best kernel.
  82433. */
  82434. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  82435. var v = Math.round(idealKernel);
  82436. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  82437. var k = _a[_i];
  82438. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  82439. return Math.max(k, 3);
  82440. }
  82441. }
  82442. return Math.max(v, 3);
  82443. };
  82444. /**
  82445. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  82446. * @param x The point on the Gaussian distribution to sample.
  82447. * @return the value of the Gaussian function at x.
  82448. */
  82449. BlurPostProcess.prototype._gaussianWeight = function (x) {
  82450. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  82451. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  82452. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  82453. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  82454. // truncated at around 1.3% of peak strength.
  82455. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  82456. var sigma = (1 / 3);
  82457. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  82458. var exponent = -((x * x) / (2.0 * sigma * sigma));
  82459. var weight = (1.0 / denominator) * Math.exp(exponent);
  82460. return weight;
  82461. };
  82462. /**
  82463. * Generates a string that can be used as a floating point number in GLSL.
  82464. * @param x Value to print.
  82465. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  82466. * @return GLSL float string.
  82467. */
  82468. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  82469. if (decimalFigures === void 0) { decimalFigures = 8; }
  82470. return x.toFixed(decimalFigures).replace(/0+$/, '');
  82471. };
  82472. return BlurPostProcess;
  82473. }(BABYLON.PostProcess));
  82474. BABYLON.BlurPostProcess = BlurPostProcess;
  82475. })(BABYLON || (BABYLON = {}));
  82476. //# sourceMappingURL=babylon.blurPostProcess.js.map
  82477. var BABYLON;
  82478. (function (BABYLON) {
  82479. /**
  82480. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  82481. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  82482. * based on samples that have a large difference in distance than the center pixel.
  82483. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82484. */
  82485. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  82486. __extends(DepthOfFieldBlurPostProcess, _super);
  82487. /**
  82488. * Creates a new instance CircleOfConfusionPostProcess
  82489. * @param name The name of the effect.
  82490. * @param scene The scene the effect belongs to.
  82491. * @param direction The direction the blur should be applied.
  82492. * @param kernel The size of the kernel used to blur.
  82493. * @param options The required width/height ratio to downsize to before computing the render pass.
  82494. * @param camera The camera to apply the render pass to.
  82495. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  82496. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  82497. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82498. * @param engine The engine which the post process will be applied. (default: current engine)
  82499. * @param reusable If the post process can be reused on the same frame. (default: false)
  82500. * @param textureType Type of textures used when performing the post process. (default: 0)
  82501. * @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)
  82502. */
  82503. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  82504. if (imageToBlur === void 0) { imageToBlur = null; }
  82505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82506. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82507. if (blockCompilation === void 0) { blockCompilation = false; }
  82508. 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;
  82509. _this.direction = direction;
  82510. _this.onApplyObservable.add(function (effect) {
  82511. if (imageToBlur != null) {
  82512. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  82513. }
  82514. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82515. if (scene.activeCamera) {
  82516. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82517. }
  82518. });
  82519. return _this;
  82520. }
  82521. return DepthOfFieldBlurPostProcess;
  82522. }(BABYLON.BlurPostProcess));
  82523. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  82524. })(BABYLON || (BABYLON = {}));
  82525. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  82526. var BABYLON;
  82527. (function (BABYLON) {
  82528. /**
  82529. * Options to be set when merging outputs from the default pipeline.
  82530. */
  82531. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  82532. function DepthOfFieldMergePostProcessOptions() {
  82533. }
  82534. return DepthOfFieldMergePostProcessOptions;
  82535. }());
  82536. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  82537. /**
  82538. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82539. */
  82540. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  82541. __extends(DepthOfFieldMergePostProcess, _super);
  82542. /**
  82543. * Creates a new instance of DepthOfFieldMergePostProcess
  82544. * @param name The name of the effect.
  82545. * @param originalFromInput Post process which's input will be used for the merge.
  82546. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  82547. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  82548. * @param options The required width/height ratio to downsize to before computing the render pass.
  82549. * @param camera The camera to apply the render pass to.
  82550. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82551. * @param engine The engine which the post process will be applied. (default: current engine)
  82552. * @param reusable If the post process can be reused on the same frame. (default: false)
  82553. * @param textureType Type of textures used when performing the post process. (default: 0)
  82554. * @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)
  82555. */
  82556. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82557. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82558. if (blockCompilation === void 0) { blockCompilation = false; }
  82559. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82560. _this.blurSteps = blurSteps;
  82561. _this.onApplyObservable.add(function (effect) {
  82562. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82563. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82564. blurSteps.forEach(function (step, index) {
  82565. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  82566. });
  82567. });
  82568. if (!blockCompilation) {
  82569. _this.updateEffect();
  82570. }
  82571. return _this;
  82572. }
  82573. /**
  82574. * Updates the effect with the current post process compile time values and recompiles the shader.
  82575. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82576. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82577. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82578. * @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
  82579. * @param onCompiled Called when the shader has been compiled.
  82580. * @param onError Called if there is an error when compiling a shader.
  82581. */
  82582. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82583. if (defines === void 0) { defines = null; }
  82584. if (uniforms === void 0) { uniforms = null; }
  82585. if (samplers === void 0) { samplers = null; }
  82586. if (!defines) {
  82587. defines = "";
  82588. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  82589. }
  82590. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  82591. };
  82592. return DepthOfFieldMergePostProcess;
  82593. }(BABYLON.PostProcess));
  82594. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  82595. })(BABYLON || (BABYLON = {}));
  82596. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  82597. var BABYLON;
  82598. (function (BABYLON) {
  82599. /**
  82600. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  82601. */
  82602. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  82603. __extends(CircleOfConfusionPostProcess, _super);
  82604. /**
  82605. * Creates a new instance CircleOfConfusionPostProcess
  82606. * @param name The name of the effect.
  82607. * @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.
  82608. * @param options The required width/height ratio to downsize to before computing the render pass.
  82609. * @param camera The camera to apply the render pass to.
  82610. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82611. * @param engine The engine which the post process will be applied. (default: current engine)
  82612. * @param reusable If the post process can be reused on the same frame. (default: false)
  82613. * @param textureType Type of textures used when performing the post process. (default: 0)
  82614. * @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)
  82615. */
  82616. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82617. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82618. if (blockCompilation === void 0) { blockCompilation = false; }
  82619. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82620. /**
  82621. * 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.
  82622. */
  82623. _this.lensSize = 50;
  82624. /**
  82625. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82626. */
  82627. _this.fStop = 1.4;
  82628. /**
  82629. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82630. */
  82631. _this.focusDistance = 2000;
  82632. /**
  82633. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  82634. */
  82635. _this.focalLength = 50;
  82636. _this._depthTexture = null;
  82637. _this._depthTexture = depthTexture;
  82638. _this.onApplyObservable.add(function (effect) {
  82639. if (!_this._depthTexture) {
  82640. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  82641. return;
  82642. }
  82643. effect.setTexture("depthSampler", _this._depthTexture);
  82644. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  82645. var aperture = _this.lensSize / _this.fStop;
  82646. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  82647. effect.setFloat('focusDistance', _this.focusDistance);
  82648. effect.setFloat('cocPrecalculation', cocPrecalculation);
  82649. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  82650. });
  82651. return _this;
  82652. }
  82653. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  82654. /**
  82655. * 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.
  82656. */
  82657. set: function (value) {
  82658. this._depthTexture = value;
  82659. },
  82660. enumerable: true,
  82661. configurable: true
  82662. });
  82663. return CircleOfConfusionPostProcess;
  82664. }(BABYLON.PostProcess));
  82665. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  82666. })(BABYLON || (BABYLON = {}));
  82667. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  82668. var BABYLON;
  82669. (function (BABYLON) {
  82670. /**
  82671. * Specifies the level of max blur that should be applied when using the depth of field effect
  82672. */
  82673. var DepthOfFieldEffectBlurLevel;
  82674. (function (DepthOfFieldEffectBlurLevel) {
  82675. /**
  82676. * Subtle blur
  82677. */
  82678. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  82679. /**
  82680. * Medium blur
  82681. */
  82682. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  82683. /**
  82684. * Large blur
  82685. */
  82686. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  82687. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  82688. ;
  82689. /**
  82690. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  82691. */
  82692. var DepthOfFieldEffect = /** @class */ (function (_super) {
  82693. __extends(DepthOfFieldEffect, _super);
  82694. /**
  82695. * Creates a new instance DepthOfFieldEffect
  82696. * @param scene The scene the effect belongs to.
  82697. * @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.
  82698. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82699. * @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)
  82700. */
  82701. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  82702. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  82703. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82704. if (blockCompilation === void 0) { blockCompilation = false; }
  82705. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  82706. return _this._effects;
  82707. }, true) || this;
  82708. /**
  82709. * @hidden Internal post processes in depth of field effect
  82710. */
  82711. _this._effects = [];
  82712. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  82713. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82714. // 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)
  82715. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  82716. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82717. _this._depthOfFieldBlurY = [];
  82718. _this._depthOfFieldBlurX = [];
  82719. var blurCount = 1;
  82720. var kernelSize = 15;
  82721. switch (blurLevel) {
  82722. case DepthOfFieldEffectBlurLevel.High: {
  82723. blurCount = 3;
  82724. kernelSize = 51;
  82725. break;
  82726. }
  82727. case DepthOfFieldEffectBlurLevel.Medium: {
  82728. blurCount = 2;
  82729. kernelSize = 31;
  82730. break;
  82731. }
  82732. default: {
  82733. kernelSize = 15;
  82734. blurCount = 1;
  82735. break;
  82736. }
  82737. }
  82738. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  82739. var ratio = 1.0;
  82740. for (var i = 0; i < blurCount; i++) {
  82741. 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);
  82742. blurY.autoClear = false;
  82743. ratio = 0.75 / Math.pow(2, i);
  82744. 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);
  82745. blurX.autoClear = false;
  82746. _this._depthOfFieldBlurY.push(blurY);
  82747. _this._depthOfFieldBlurX.push(blurX);
  82748. }
  82749. // Set all post processes on the effect.
  82750. _this._effects = [_this._circleOfConfusion];
  82751. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  82752. _this._effects.push(_this._depthOfFieldBlurY[i]);
  82753. _this._effects.push(_this._depthOfFieldBlurX[i]);
  82754. }
  82755. // Merge blurred images with original image based on circleOfConfusion
  82756. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82757. _this._dofMerge.autoClear = false;
  82758. _this._effects.push(_this._dofMerge);
  82759. return _this;
  82760. }
  82761. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  82762. get: function () {
  82763. return this._circleOfConfusion.focalLength;
  82764. },
  82765. /**
  82766. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  82767. */
  82768. set: function (value) {
  82769. this._circleOfConfusion.focalLength = value;
  82770. },
  82771. enumerable: true,
  82772. configurable: true
  82773. });
  82774. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  82775. get: function () {
  82776. return this._circleOfConfusion.fStop;
  82777. },
  82778. /**
  82779. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82780. */
  82781. set: function (value) {
  82782. this._circleOfConfusion.fStop = value;
  82783. },
  82784. enumerable: true,
  82785. configurable: true
  82786. });
  82787. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  82788. get: function () {
  82789. return this._circleOfConfusion.focusDistance;
  82790. },
  82791. /**
  82792. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82793. */
  82794. set: function (value) {
  82795. this._circleOfConfusion.focusDistance = value;
  82796. },
  82797. enumerable: true,
  82798. configurable: true
  82799. });
  82800. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  82801. get: function () {
  82802. return this._circleOfConfusion.lensSize;
  82803. },
  82804. /**
  82805. * 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.
  82806. */
  82807. set: function (value) {
  82808. this._circleOfConfusion.lensSize = value;
  82809. },
  82810. enumerable: true,
  82811. configurable: true
  82812. });
  82813. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  82814. /**
  82815. * 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.
  82816. */
  82817. set: function (value) {
  82818. this._circleOfConfusion.depthTexture = value;
  82819. },
  82820. enumerable: true,
  82821. configurable: true
  82822. });
  82823. /**
  82824. * Disposes each of the internal effects for a given camera.
  82825. * @param camera The camera to dispose the effect on.
  82826. */
  82827. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  82828. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82829. this._effects[effectIndex].dispose(camera);
  82830. }
  82831. };
  82832. /**
  82833. * @hidden Internal
  82834. */
  82835. DepthOfFieldEffect.prototype._updateEffects = function () {
  82836. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82837. this._effects[effectIndex].updateEffect();
  82838. }
  82839. };
  82840. /**
  82841. * Internal
  82842. * @returns if all the contained post processes are ready.
  82843. * @hidden
  82844. */
  82845. DepthOfFieldEffect.prototype._isReady = function () {
  82846. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82847. if (!this._effects[effectIndex].isReady()) {
  82848. return false;
  82849. }
  82850. }
  82851. return true;
  82852. };
  82853. return DepthOfFieldEffect;
  82854. }(BABYLON.PostProcessRenderEffect));
  82855. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  82856. })(BABYLON || (BABYLON = {}));
  82857. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  82858. var BABYLON;
  82859. (function (BABYLON) {
  82860. /**
  82861. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82862. */
  82863. var BloomMergePostProcess = /** @class */ (function (_super) {
  82864. __extends(BloomMergePostProcess, _super);
  82865. /**
  82866. * Creates a new instance of @see BloomMergePostProcess
  82867. * @param name The name of the effect.
  82868. * @param originalFromInput Post process which's input will be used for the merge.
  82869. * @param blurred Blurred highlights post process which's output will be used.
  82870. * @param weight Weight of the bloom to be added to the original input.
  82871. * @param options The required width/height ratio to downsize to before computing the render pass.
  82872. * @param camera The camera to apply the render pass to.
  82873. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82874. * @param engine The engine which the post process will be applied. (default: current engine)
  82875. * @param reusable If the post process can be reused on the same frame. (default: false)
  82876. * @param textureType Type of textures used when performing the post process. (default: 0)
  82877. * @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)
  82878. */
  82879. function BloomMergePostProcess(name, originalFromInput, blurred,
  82880. /** Weight of the bloom to be added to the original input. */
  82881. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82882. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82883. if (blockCompilation === void 0) { blockCompilation = false; }
  82884. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82885. _this.weight = weight;
  82886. _this.onApplyObservable.add(function (effect) {
  82887. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82888. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  82889. effect.setFloat("bloomWeight", _this.weight);
  82890. });
  82891. if (!blockCompilation) {
  82892. _this.updateEffect();
  82893. }
  82894. return _this;
  82895. }
  82896. return BloomMergePostProcess;
  82897. }(BABYLON.PostProcess));
  82898. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  82899. })(BABYLON || (BABYLON = {}));
  82900. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  82901. var BABYLON;
  82902. (function (BABYLON) {
  82903. /**
  82904. * 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.
  82905. */
  82906. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  82907. __extends(ExtractHighlightsPostProcess, _super);
  82908. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82909. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82910. if (blockCompilation === void 0) { blockCompilation = false; }
  82911. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82912. /**
  82913. * The luminance threshold, pixels below this value will be set to black.
  82914. */
  82915. _this.threshold = 0.9;
  82916. /** @hidden */
  82917. _this._exposure = 1;
  82918. /**
  82919. * Post process which has the input texture to be used when performing highlight extraction
  82920. * @hidden
  82921. */
  82922. _this._inputPostProcess = null;
  82923. _this.onApplyObservable.add(function (effect) {
  82924. if (_this._inputPostProcess) {
  82925. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  82926. }
  82927. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  82928. effect.setFloat('exposure', _this._exposure);
  82929. });
  82930. return _this;
  82931. }
  82932. return ExtractHighlightsPostProcess;
  82933. }(BABYLON.PostProcess));
  82934. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  82935. })(BABYLON || (BABYLON = {}));
  82936. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  82937. var BABYLON;
  82938. (function (BABYLON) {
  82939. /**
  82940. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  82941. */
  82942. var BloomEffect = /** @class */ (function (_super) {
  82943. __extends(BloomEffect, _super);
  82944. /**
  82945. * Creates a new instance of @see BloomEffect
  82946. * @param scene The scene the effect belongs to.
  82947. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  82948. * @param bloomKernel The size of the kernel to be used when applying the blur.
  82949. * @param bloomWeight The the strength of bloom.
  82950. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82951. * @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)
  82952. */
  82953. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  82954. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82955. if (blockCompilation === void 0) { blockCompilation = false; }
  82956. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  82957. return _this._effects;
  82958. }, true) || this;
  82959. _this.bloomScale = bloomScale;
  82960. /**
  82961. * @hidden Internal
  82962. */
  82963. _this._effects = [];
  82964. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82965. _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);
  82966. _this._blurX.alwaysForcePOT = true;
  82967. _this._blurX.autoClear = false;
  82968. _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);
  82969. _this._blurY.alwaysForcePOT = true;
  82970. _this._blurY.autoClear = false;
  82971. _this.kernel = bloomKernel;
  82972. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  82973. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82974. _this._merge.autoClear = false;
  82975. _this._effects.push(_this._merge);
  82976. return _this;
  82977. }
  82978. Object.defineProperty(BloomEffect.prototype, "threshold", {
  82979. /**
  82980. * The luminance threshold to find bright areas of the image to bloom.
  82981. */
  82982. get: function () {
  82983. return this._downscale.threshold;
  82984. },
  82985. set: function (value) {
  82986. this._downscale.threshold = value;
  82987. },
  82988. enumerable: true,
  82989. configurable: true
  82990. });
  82991. Object.defineProperty(BloomEffect.prototype, "weight", {
  82992. /**
  82993. * The strength of the bloom.
  82994. */
  82995. get: function () {
  82996. return this._merge.weight;
  82997. },
  82998. set: function (value) {
  82999. this._merge.weight = value;
  83000. },
  83001. enumerable: true,
  83002. configurable: true
  83003. });
  83004. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83005. /**
  83006. * Specifies the size of the bloom blur kernel, relative to the final output size
  83007. */
  83008. get: function () {
  83009. return this._blurX.kernel / this.bloomScale;
  83010. },
  83011. set: function (value) {
  83012. this._blurX.kernel = value * this.bloomScale;
  83013. this._blurY.kernel = value * this.bloomScale;
  83014. },
  83015. enumerable: true,
  83016. configurable: true
  83017. });
  83018. /**
  83019. * Disposes each of the internal effects for a given camera.
  83020. * @param camera The camera to dispose the effect on.
  83021. */
  83022. BloomEffect.prototype.disposeEffects = function (camera) {
  83023. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83024. this._effects[effectIndex].dispose(camera);
  83025. }
  83026. };
  83027. /**
  83028. * @hidden Internal
  83029. */
  83030. BloomEffect.prototype._updateEffects = function () {
  83031. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83032. this._effects[effectIndex].updateEffect();
  83033. }
  83034. };
  83035. /**
  83036. * Internal
  83037. * @returns if all the contained post processes are ready.
  83038. * @hidden
  83039. */
  83040. BloomEffect.prototype._isReady = function () {
  83041. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83042. if (!this._effects[effectIndex].isReady()) {
  83043. return false;
  83044. }
  83045. }
  83046. return true;
  83047. };
  83048. return BloomEffect;
  83049. }(BABYLON.PostProcessRenderEffect));
  83050. BABYLON.BloomEffect = BloomEffect;
  83051. })(BABYLON || (BABYLON = {}));
  83052. //# sourceMappingURL=babylon.bloomEffect.js.map
  83053. var BABYLON;
  83054. (function (BABYLON) {
  83055. /**
  83056. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83057. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83058. */
  83059. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83060. __extends(DefaultRenderingPipeline, _super);
  83061. /**
  83062. * @constructor
  83063. * @param {string} name - The rendering pipeline name (default: "")
  83064. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83065. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83066. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83067. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83068. */
  83069. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83070. if (name === void 0) { name = ""; }
  83071. if (hdr === void 0) { hdr = true; }
  83072. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83073. if (automaticBuild === void 0) { automaticBuild = true; }
  83074. var _this = _super.call(this, scene.getEngine(), name) || this;
  83075. _this._camerasToBeAttached = [];
  83076. /**
  83077. * ID of the sharpen post process,
  83078. */
  83079. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83080. /**
  83081. * ID of the image processing post process;
  83082. */
  83083. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83084. /**
  83085. * ID of the Fast Approximate Anti-Aliasing post process;
  83086. */
  83087. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83088. /**
  83089. * ID of the chromatic aberration post process,
  83090. */
  83091. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83092. /**
  83093. * ID of the grain post process
  83094. */
  83095. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83096. /**
  83097. * Glow post process which adds a glow to emmisive areas of the image
  83098. */
  83099. _this._glowLayer = null;
  83100. /**
  83101. * Animations which can be used to tweak settings over a period of time
  83102. */
  83103. _this.animations = [];
  83104. _this._imageProcessingConfigurationObserver = null;
  83105. // Values
  83106. _this._sharpenEnabled = false;
  83107. _this._bloomEnabled = false;
  83108. _this._depthOfFieldEnabled = false;
  83109. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83110. _this._fxaaEnabled = false;
  83111. _this._imageProcessingEnabled = true;
  83112. _this._bloomScale = 0.5;
  83113. _this._chromaticAberrationEnabled = false;
  83114. _this._grainEnabled = false;
  83115. _this._buildAllowed = true;
  83116. _this._resizeObserver = null;
  83117. _this._hardwareScaleLevel = 1.0;
  83118. _this._bloomKernel = 64;
  83119. /**
  83120. * Specifies the weight of the bloom in the final rendering
  83121. */
  83122. _this._bloomWeight = 0.15;
  83123. /**
  83124. * Specifies the luma threshold for the area that will be blurred by the bloom
  83125. */
  83126. _this._bloomThreshold = 0.9;
  83127. _this._samples = 1;
  83128. _this._hasCleared = false;
  83129. _this._prevPostProcess = null;
  83130. _this._prevPrevPostProcess = null;
  83131. _this._depthOfFieldSceneObserver = null;
  83132. _this._cameras = cameras || scene.cameras;
  83133. _this._cameras = _this._cameras.slice();
  83134. _this._camerasToBeAttached = _this._cameras.slice();
  83135. _this._buildAllowed = automaticBuild;
  83136. // Initialize
  83137. _this._scene = scene;
  83138. var caps = _this._scene.getEngine().getCaps();
  83139. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83140. // Misc
  83141. if (_this._hdr) {
  83142. if (caps.textureHalfFloatRender) {
  83143. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83144. }
  83145. else if (caps.textureFloatRender) {
  83146. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83147. }
  83148. }
  83149. else {
  83150. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83151. }
  83152. // Attach
  83153. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83154. var engine = _this._scene.getEngine();
  83155. // Create post processes before hand so they can be modified before enabled.
  83156. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83157. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83158. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83159. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83160. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83161. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83162. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83163. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83164. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83165. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83166. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83167. _this.bloomKernel = _this.bloomKernel;
  83168. });
  83169. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83170. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83171. });
  83172. _this._buildPipeline();
  83173. return _this;
  83174. }
  83175. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83176. get: function () {
  83177. return this._sharpenEnabled;
  83178. },
  83179. /**
  83180. * Enable or disable the sharpen process from the pipeline
  83181. */
  83182. set: function (enabled) {
  83183. if (this._sharpenEnabled === enabled) {
  83184. return;
  83185. }
  83186. this._sharpenEnabled = enabled;
  83187. this._buildPipeline();
  83188. },
  83189. enumerable: true,
  83190. configurable: true
  83191. });
  83192. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83193. /**
  83194. * Specifies the size of the bloom blur kernel, relative to the final output size
  83195. */
  83196. get: function () {
  83197. return this._bloomKernel;
  83198. },
  83199. set: function (value) {
  83200. this._bloomKernel = value;
  83201. this.bloom.kernel = value / this._hardwareScaleLevel;
  83202. },
  83203. enumerable: true,
  83204. configurable: true
  83205. });
  83206. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83207. get: function () {
  83208. return this._bloomWeight;
  83209. },
  83210. /**
  83211. * The strength of the bloom.
  83212. */
  83213. set: function (value) {
  83214. if (this._bloomWeight === value) {
  83215. return;
  83216. }
  83217. this.bloom.weight = value;
  83218. this._bloomWeight = value;
  83219. },
  83220. enumerable: true,
  83221. configurable: true
  83222. });
  83223. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83224. get: function () {
  83225. return this._bloomThreshold;
  83226. },
  83227. /**
  83228. * The strength of the bloom.
  83229. */
  83230. set: function (value) {
  83231. if (this._bloomThreshold === value) {
  83232. return;
  83233. }
  83234. this.bloom.threshold = value;
  83235. this._bloomThreshold = value;
  83236. },
  83237. enumerable: true,
  83238. configurable: true
  83239. });
  83240. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83241. get: function () {
  83242. return this._bloomScale;
  83243. },
  83244. /**
  83245. * The scale of the bloom, lower value will provide better performance.
  83246. */
  83247. set: function (value) {
  83248. if (this._bloomScale === value) {
  83249. return;
  83250. }
  83251. this._bloomScale = value;
  83252. // recreate bloom and dispose old as this setting is not dynamic
  83253. this._rebuildBloom();
  83254. this._buildPipeline();
  83255. },
  83256. enumerable: true,
  83257. configurable: true
  83258. });
  83259. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83260. get: function () {
  83261. return this._bloomEnabled;
  83262. },
  83263. /**
  83264. * Enable or disable the bloom from the pipeline
  83265. */
  83266. set: function (enabled) {
  83267. if (this._bloomEnabled === enabled) {
  83268. return;
  83269. }
  83270. this._bloomEnabled = enabled;
  83271. this._buildPipeline();
  83272. },
  83273. enumerable: true,
  83274. configurable: true
  83275. });
  83276. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83277. // recreate bloom and dispose old as this setting is not dynamic
  83278. var oldBloom = this.bloom;
  83279. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83280. this.bloom.threshold = oldBloom.threshold;
  83281. for (var i = 0; i < this._cameras.length; i++) {
  83282. oldBloom.disposeEffects(this._cameras[i]);
  83283. }
  83284. };
  83285. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83286. /**
  83287. * If the depth of field is enabled.
  83288. */
  83289. get: function () {
  83290. return this._depthOfFieldEnabled;
  83291. },
  83292. set: function (enabled) {
  83293. if (this._depthOfFieldEnabled === enabled) {
  83294. return;
  83295. }
  83296. this._depthOfFieldEnabled = enabled;
  83297. this._buildPipeline();
  83298. },
  83299. enumerable: true,
  83300. configurable: true
  83301. });
  83302. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  83303. /**
  83304. * Blur level of the depth of field effect. (Higher blur will effect performance)
  83305. */
  83306. get: function () {
  83307. return this._depthOfFieldBlurLevel;
  83308. },
  83309. set: function (value) {
  83310. if (this._depthOfFieldBlurLevel === value) {
  83311. return;
  83312. }
  83313. this._depthOfFieldBlurLevel = value;
  83314. // recreate dof and dispose old as this setting is not dynamic
  83315. var oldDof = this.depthOfField;
  83316. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  83317. this.depthOfField.focalLength = oldDof.focalLength;
  83318. this.depthOfField.focusDistance = oldDof.focusDistance;
  83319. this.depthOfField.fStop = oldDof.fStop;
  83320. this.depthOfField.lensSize = oldDof.lensSize;
  83321. for (var i = 0; i < this._cameras.length; i++) {
  83322. oldDof.disposeEffects(this._cameras[i]);
  83323. }
  83324. this._buildPipeline();
  83325. },
  83326. enumerable: true,
  83327. configurable: true
  83328. });
  83329. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  83330. get: function () {
  83331. return this._fxaaEnabled;
  83332. },
  83333. /**
  83334. * If the anti aliasing is enabled.
  83335. */
  83336. set: function (enabled) {
  83337. if (this._fxaaEnabled === enabled) {
  83338. return;
  83339. }
  83340. this._fxaaEnabled = enabled;
  83341. this._buildPipeline();
  83342. },
  83343. enumerable: true,
  83344. configurable: true
  83345. });
  83346. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  83347. get: function () {
  83348. return this._samples;
  83349. },
  83350. /**
  83351. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83352. */
  83353. set: function (sampleCount) {
  83354. if (this._samples === sampleCount) {
  83355. return;
  83356. }
  83357. this._samples = sampleCount;
  83358. this._buildPipeline();
  83359. },
  83360. enumerable: true,
  83361. configurable: true
  83362. });
  83363. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  83364. get: function () {
  83365. return this._imageProcessingEnabled;
  83366. },
  83367. /**
  83368. * If image processing is enabled.
  83369. */
  83370. set: function (enabled) {
  83371. if (this._imageProcessingEnabled === enabled) {
  83372. return;
  83373. }
  83374. this._imageProcessingEnabled = enabled;
  83375. this._buildPipeline();
  83376. },
  83377. enumerable: true,
  83378. configurable: true
  83379. });
  83380. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  83381. get: function () {
  83382. return this._glowLayer == null;
  83383. },
  83384. /**
  83385. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  83386. */
  83387. set: function (enabled) {
  83388. if (enabled && !this._glowLayer) {
  83389. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  83390. }
  83391. else if (!enabled && this._glowLayer) {
  83392. this._glowLayer.dispose();
  83393. this._glowLayer = null;
  83394. }
  83395. },
  83396. enumerable: true,
  83397. configurable: true
  83398. });
  83399. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  83400. get: function () {
  83401. return this._chromaticAberrationEnabled;
  83402. },
  83403. /**
  83404. * Enable or disable the chromaticAberration process from the pipeline
  83405. */
  83406. set: function (enabled) {
  83407. if (this._chromaticAberrationEnabled === enabled) {
  83408. return;
  83409. }
  83410. this._chromaticAberrationEnabled = enabled;
  83411. this._buildPipeline();
  83412. },
  83413. enumerable: true,
  83414. configurable: true
  83415. });
  83416. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  83417. get: function () {
  83418. return this._grainEnabled;
  83419. },
  83420. /**
  83421. * Enable or disable the grain process from the pipeline
  83422. */
  83423. set: function (enabled) {
  83424. if (this._grainEnabled === enabled) {
  83425. return;
  83426. }
  83427. this._grainEnabled = enabled;
  83428. this._buildPipeline();
  83429. },
  83430. enumerable: true,
  83431. configurable: true
  83432. });
  83433. /**
  83434. * Force the compilation of the entire pipeline.
  83435. */
  83436. DefaultRenderingPipeline.prototype.prepare = function () {
  83437. var previousState = this._buildAllowed;
  83438. this._buildAllowed = true;
  83439. this._buildPipeline();
  83440. this._buildAllowed = previousState;
  83441. };
  83442. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  83443. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  83444. if (this._hasCleared) {
  83445. postProcess.autoClear = false;
  83446. }
  83447. else {
  83448. postProcess.autoClear = true;
  83449. this._scene.autoClear = false;
  83450. this._hasCleared = true;
  83451. }
  83452. if (!skipTextureSharing) {
  83453. if (this._prevPrevPostProcess) {
  83454. postProcess.shareOutputWith(this._prevPrevPostProcess);
  83455. }
  83456. else {
  83457. postProcess.useOwnOutput();
  83458. }
  83459. if (this._prevPostProcess) {
  83460. this._prevPrevPostProcess = this._prevPostProcess;
  83461. }
  83462. this._prevPostProcess = postProcess;
  83463. }
  83464. };
  83465. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  83466. var _this = this;
  83467. if (!this._buildAllowed) {
  83468. return;
  83469. }
  83470. this._scene.autoClear = true;
  83471. var engine = this._scene.getEngine();
  83472. this._disposePostProcesses();
  83473. if (this._cameras !== null) {
  83474. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83475. // get back cameras to be used to reattach pipeline
  83476. this._cameras = this._camerasToBeAttached.slice();
  83477. }
  83478. this._reset();
  83479. this._prevPostProcess = null;
  83480. this._prevPrevPostProcess = null;
  83481. this._hasCleared = false;
  83482. if (this.depthOfFieldEnabled) {
  83483. // Multi camera suport
  83484. if (this._cameras.length > 1) {
  83485. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  83486. var camera = _a[_i];
  83487. var depthRenderer = this._scene.enableDepthRenderer(camera);
  83488. depthRenderer.useOnlyInActiveCamera = true;
  83489. }
  83490. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  83491. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  83492. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  83493. }
  83494. });
  83495. }
  83496. else {
  83497. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83498. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  83499. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  83500. }
  83501. if (!this.depthOfField._isReady()) {
  83502. this.depthOfField._updateEffects();
  83503. }
  83504. this.addEffect(this.depthOfField);
  83505. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  83506. }
  83507. else {
  83508. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83509. }
  83510. if (this.bloomEnabled) {
  83511. if (!this.bloom._isReady()) {
  83512. this.bloom._updateEffects();
  83513. }
  83514. this.addEffect(this.bloom);
  83515. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  83516. }
  83517. if (this._imageProcessingEnabled) {
  83518. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83519. if (this._hdr) {
  83520. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  83521. this._setAutoClearAndTextureSharing(this.imageProcessing);
  83522. }
  83523. else {
  83524. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  83525. }
  83526. }
  83527. if (this.sharpenEnabled) {
  83528. if (!this.sharpen.isReady()) {
  83529. this.sharpen.updateEffect();
  83530. }
  83531. this.addEffect(this._sharpenEffect);
  83532. this._setAutoClearAndTextureSharing(this.sharpen);
  83533. }
  83534. if (this.grainEnabled) {
  83535. if (!this.grain.isReady()) {
  83536. this.grain.updateEffect();
  83537. }
  83538. this.addEffect(this._grainEffect);
  83539. this._setAutoClearAndTextureSharing(this.grain);
  83540. }
  83541. if (this.chromaticAberrationEnabled) {
  83542. if (!this.chromaticAberration.isReady()) {
  83543. this.chromaticAberration.updateEffect();
  83544. }
  83545. this.addEffect(this._chromaticAberrationEffect);
  83546. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  83547. }
  83548. if (this.fxaaEnabled) {
  83549. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83550. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  83551. this._setAutoClearAndTextureSharing(this.fxaa, true);
  83552. }
  83553. if (this._cameras !== null) {
  83554. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83555. }
  83556. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  83557. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83558. }
  83559. };
  83560. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  83561. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  83562. for (var i = 0; i < this._cameras.length; i++) {
  83563. var camera = this._cameras[i];
  83564. if (this.imageProcessing) {
  83565. this.imageProcessing.dispose(camera);
  83566. }
  83567. if (this.fxaa) {
  83568. this.fxaa.dispose(camera);
  83569. }
  83570. // These are created in the constructor and should not be disposed on every pipeline change
  83571. if (disposeNonRecreated) {
  83572. if (this.sharpen) {
  83573. this.sharpen.dispose(camera);
  83574. }
  83575. if (this.depthOfField) {
  83576. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83577. this.depthOfField.disposeEffects(camera);
  83578. }
  83579. if (this.bloom) {
  83580. this.bloom.disposeEffects(camera);
  83581. }
  83582. if (this.chromaticAberration) {
  83583. this.chromaticAberration.dispose(camera);
  83584. }
  83585. if (this.grain) {
  83586. this.grain.dispose(camera);
  83587. }
  83588. if (this._glowLayer) {
  83589. this._glowLayer.dispose();
  83590. }
  83591. }
  83592. }
  83593. this.imageProcessing = null;
  83594. this.fxaa = null;
  83595. if (disposeNonRecreated) {
  83596. this.sharpen = null;
  83597. this._sharpenEffect = null;
  83598. this.depthOfField = null;
  83599. this.bloom = null;
  83600. this.chromaticAberration = null;
  83601. this._chromaticAberrationEffect = null;
  83602. this.grain = null;
  83603. this._grainEffect = null;
  83604. this._glowLayer = null;
  83605. }
  83606. };
  83607. /**
  83608. * Adds a camera to the pipeline
  83609. * @param camera the camera to be added
  83610. */
  83611. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  83612. this._camerasToBeAttached.push(camera);
  83613. this._buildPipeline();
  83614. };
  83615. /**
  83616. * Removes a camera from the pipeline
  83617. * @param camera the camera to remove
  83618. */
  83619. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  83620. var index = this._camerasToBeAttached.indexOf(camera);
  83621. this._camerasToBeAttached.splice(index, 1);
  83622. this._buildPipeline();
  83623. };
  83624. /**
  83625. * Dispose of the pipeline and stop all post processes
  83626. */
  83627. DefaultRenderingPipeline.prototype.dispose = function () {
  83628. this._disposePostProcesses(true);
  83629. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83630. this._scene.autoClear = true;
  83631. if (this._resizeObserver) {
  83632. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  83633. this._resizeObserver = null;
  83634. }
  83635. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  83636. _super.prototype.dispose.call(this);
  83637. };
  83638. /**
  83639. * Serialize the rendering pipeline (Used when exporting)
  83640. * @returns the serialized object
  83641. */
  83642. DefaultRenderingPipeline.prototype.serialize = function () {
  83643. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83644. serializationObject.customType = "DefaultRenderingPipeline";
  83645. return serializationObject;
  83646. };
  83647. /**
  83648. * Parse the serialized pipeline
  83649. * @param source Source pipeline.
  83650. * @param scene The scene to load the pipeline to.
  83651. * @param rootUrl The URL of the serialized pipeline.
  83652. * @returns An instantiated pipeline from the serialized object.
  83653. */
  83654. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83655. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  83656. };
  83657. __decorate([
  83658. BABYLON.serialize()
  83659. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  83660. __decorate([
  83661. BABYLON.serialize()
  83662. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  83663. __decorate([
  83664. BABYLON.serialize()
  83665. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  83666. __decorate([
  83667. BABYLON.serialize()
  83668. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  83669. __decorate([
  83670. BABYLON.serialize()
  83671. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  83672. __decorate([
  83673. BABYLON.serialize()
  83674. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  83675. __decorate([
  83676. BABYLON.serialize()
  83677. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  83678. __decorate([
  83679. BABYLON.serialize()
  83680. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  83681. __decorate([
  83682. BABYLON.serialize()
  83683. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  83684. __decorate([
  83685. BABYLON.serialize()
  83686. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  83687. __decorate([
  83688. BABYLON.serialize()
  83689. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  83690. __decorate([
  83691. BABYLON.serialize()
  83692. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  83693. __decorate([
  83694. BABYLON.serialize()
  83695. ], DefaultRenderingPipeline.prototype, "samples", null);
  83696. __decorate([
  83697. BABYLON.serialize()
  83698. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  83699. __decorate([
  83700. BABYLON.serialize()
  83701. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  83702. __decorate([
  83703. BABYLON.serialize()
  83704. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  83705. __decorate([
  83706. BABYLON.serialize()
  83707. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  83708. return DefaultRenderingPipeline;
  83709. }(BABYLON.PostProcessRenderPipeline));
  83710. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  83711. })(BABYLON || (BABYLON = {}));
  83712. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  83713. var BABYLON;
  83714. (function (BABYLON) {
  83715. /**
  83716. * @hidden
  83717. */
  83718. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  83719. __extends(ImageProcessingConfigurationDefines, _super);
  83720. function ImageProcessingConfigurationDefines() {
  83721. var _this = _super.call(this) || this;
  83722. _this.IMAGEPROCESSING = false;
  83723. _this.VIGNETTE = false;
  83724. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83725. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83726. _this.TONEMAPPING = false;
  83727. _this.TONEMAPPING_ACES = false;
  83728. _this.CONTRAST = false;
  83729. _this.COLORCURVES = false;
  83730. _this.COLORGRADING = false;
  83731. _this.COLORGRADING3D = false;
  83732. _this.SAMPLER3DGREENDEPTH = false;
  83733. _this.SAMPLER3DBGRMAP = false;
  83734. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83735. _this.EXPOSURE = false;
  83736. _this.rebuild();
  83737. return _this;
  83738. }
  83739. return ImageProcessingConfigurationDefines;
  83740. }(BABYLON.MaterialDefines));
  83741. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  83742. /**
  83743. * This groups together the common properties used for image processing either in direct forward pass
  83744. * or through post processing effect depending on the use of the image processing pipeline in your scene
  83745. * or not.
  83746. */
  83747. var ImageProcessingConfiguration = /** @class */ (function () {
  83748. function ImageProcessingConfiguration() {
  83749. /**
  83750. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  83751. */
  83752. this.colorCurves = new BABYLON.ColorCurves();
  83753. this._colorCurvesEnabled = false;
  83754. this._colorGradingEnabled = false;
  83755. this._colorGradingWithGreenDepth = true;
  83756. this._colorGradingBGR = true;
  83757. /** @hidden */
  83758. this._exposure = 1.0;
  83759. this._toneMappingEnabled = false;
  83760. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  83761. this._contrast = 1.0;
  83762. /**
  83763. * Vignette stretch size.
  83764. */
  83765. this.vignetteStretch = 0;
  83766. /**
  83767. * Vignette centre X Offset.
  83768. */
  83769. this.vignetteCentreX = 0;
  83770. /**
  83771. * Vignette centre Y Offset.
  83772. */
  83773. this.vignetteCentreY = 0;
  83774. /**
  83775. * Vignette weight or intensity of the vignette effect.
  83776. */
  83777. this.vignetteWeight = 1.5;
  83778. /**
  83779. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83780. * if vignetteEnabled is set to true.
  83781. */
  83782. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83783. /**
  83784. * Camera field of view used by the Vignette effect.
  83785. */
  83786. this.vignetteCameraFov = 0.5;
  83787. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  83788. this._vignetteEnabled = false;
  83789. this._applyByPostProcess = false;
  83790. this._isEnabled = true;
  83791. /**
  83792. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  83793. */
  83794. this.onUpdateParameters = new BABYLON.Observable();
  83795. }
  83796. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  83797. /**
  83798. * Gets wether the color curves effect is enabled.
  83799. */
  83800. get: function () {
  83801. return this._colorCurvesEnabled;
  83802. },
  83803. /**
  83804. * Sets wether the color curves effect is enabled.
  83805. */
  83806. set: function (value) {
  83807. if (this._colorCurvesEnabled === value) {
  83808. return;
  83809. }
  83810. this._colorCurvesEnabled = value;
  83811. this._updateParameters();
  83812. },
  83813. enumerable: true,
  83814. configurable: true
  83815. });
  83816. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  83817. /**
  83818. * Gets wether the color grading effect is enabled.
  83819. */
  83820. get: function () {
  83821. return this._colorGradingEnabled;
  83822. },
  83823. /**
  83824. * Sets wether the color grading effect is enabled.
  83825. */
  83826. set: function (value) {
  83827. if (this._colorGradingEnabled === value) {
  83828. return;
  83829. }
  83830. this._colorGradingEnabled = value;
  83831. this._updateParameters();
  83832. },
  83833. enumerable: true,
  83834. configurable: true
  83835. });
  83836. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  83837. /**
  83838. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  83839. */
  83840. get: function () {
  83841. return this._colorGradingWithGreenDepth;
  83842. },
  83843. /**
  83844. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  83845. */
  83846. set: function (value) {
  83847. if (this._colorGradingWithGreenDepth === value) {
  83848. return;
  83849. }
  83850. this._colorGradingWithGreenDepth = value;
  83851. this._updateParameters();
  83852. },
  83853. enumerable: true,
  83854. configurable: true
  83855. });
  83856. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  83857. /**
  83858. * Gets wether the color grading texture contains BGR values.
  83859. */
  83860. get: function () {
  83861. return this._colorGradingBGR;
  83862. },
  83863. /**
  83864. * Sets wether the color grading texture contains BGR values.
  83865. */
  83866. set: function (value) {
  83867. if (this._colorGradingBGR === value) {
  83868. return;
  83869. }
  83870. this._colorGradingBGR = value;
  83871. this._updateParameters();
  83872. },
  83873. enumerable: true,
  83874. configurable: true
  83875. });
  83876. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  83877. /**
  83878. * Gets the Exposure used in the effect.
  83879. */
  83880. get: function () {
  83881. return this._exposure;
  83882. },
  83883. /**
  83884. * Sets the Exposure used in the effect.
  83885. */
  83886. set: function (value) {
  83887. if (this._exposure === value) {
  83888. return;
  83889. }
  83890. this._exposure = value;
  83891. this._updateParameters();
  83892. },
  83893. enumerable: true,
  83894. configurable: true
  83895. });
  83896. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  83897. /**
  83898. * Gets wether the tone mapping effect is enabled.
  83899. */
  83900. get: function () {
  83901. return this._toneMappingEnabled;
  83902. },
  83903. /**
  83904. * Sets wether the tone mapping effect is enabled.
  83905. */
  83906. set: function (value) {
  83907. if (this._toneMappingEnabled === value) {
  83908. return;
  83909. }
  83910. this._toneMappingEnabled = value;
  83911. this._updateParameters();
  83912. },
  83913. enumerable: true,
  83914. configurable: true
  83915. });
  83916. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  83917. /**
  83918. * Gets the type of tone mapping effect.
  83919. */
  83920. get: function () {
  83921. return this._toneMappingType;
  83922. },
  83923. /**
  83924. * Sets the type of tone mapping effect used in BabylonJS.
  83925. */
  83926. set: function (value) {
  83927. if (this._toneMappingType === value) {
  83928. return;
  83929. }
  83930. this._toneMappingType = value;
  83931. this._updateParameters();
  83932. },
  83933. enumerable: true,
  83934. configurable: true
  83935. });
  83936. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  83937. /**
  83938. * Gets the contrast used in the effect.
  83939. */
  83940. get: function () {
  83941. return this._contrast;
  83942. },
  83943. /**
  83944. * Sets the contrast used in the effect.
  83945. */
  83946. set: function (value) {
  83947. if (this._contrast === value) {
  83948. return;
  83949. }
  83950. this._contrast = value;
  83951. this._updateParameters();
  83952. },
  83953. enumerable: true,
  83954. configurable: true
  83955. });
  83956. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  83957. /**
  83958. * Gets the vignette blend mode allowing different kind of effect.
  83959. */
  83960. get: function () {
  83961. return this._vignetteBlendMode;
  83962. },
  83963. /**
  83964. * Sets the vignette blend mode allowing different kind of effect.
  83965. */
  83966. set: function (value) {
  83967. if (this._vignetteBlendMode === value) {
  83968. return;
  83969. }
  83970. this._vignetteBlendMode = value;
  83971. this._updateParameters();
  83972. },
  83973. enumerable: true,
  83974. configurable: true
  83975. });
  83976. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  83977. /**
  83978. * Gets wether the vignette effect is enabled.
  83979. */
  83980. get: function () {
  83981. return this._vignetteEnabled;
  83982. },
  83983. /**
  83984. * Sets wether the vignette effect is enabled.
  83985. */
  83986. set: function (value) {
  83987. if (this._vignetteEnabled === value) {
  83988. return;
  83989. }
  83990. this._vignetteEnabled = value;
  83991. this._updateParameters();
  83992. },
  83993. enumerable: true,
  83994. configurable: true
  83995. });
  83996. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  83997. /**
  83998. * Gets wether the image processing is applied through a post process or not.
  83999. */
  84000. get: function () {
  84001. return this._applyByPostProcess;
  84002. },
  84003. /**
  84004. * Sets wether the image processing is applied through a post process or not.
  84005. */
  84006. set: function (value) {
  84007. if (this._applyByPostProcess === value) {
  84008. return;
  84009. }
  84010. this._applyByPostProcess = value;
  84011. this._updateParameters();
  84012. },
  84013. enumerable: true,
  84014. configurable: true
  84015. });
  84016. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84017. /**
  84018. * Gets wether the image processing is enabled or not.
  84019. */
  84020. get: function () {
  84021. return this._isEnabled;
  84022. },
  84023. /**
  84024. * Sets wether the image processing is enabled or not.
  84025. */
  84026. set: function (value) {
  84027. if (this._isEnabled === value) {
  84028. return;
  84029. }
  84030. this._isEnabled = value;
  84031. this._updateParameters();
  84032. },
  84033. enumerable: true,
  84034. configurable: true
  84035. });
  84036. /**
  84037. * Method called each time the image processing information changes requires to recompile the effect.
  84038. */
  84039. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84040. this.onUpdateParameters.notifyObservers(this);
  84041. };
  84042. ImageProcessingConfiguration.prototype.getClassName = function () {
  84043. return "ImageProcessingConfiguration";
  84044. };
  84045. /**
  84046. * Prepare the list of uniforms associated with the Image Processing effects.
  84047. * @param uniformsList The list of uniforms used in the effect
  84048. * @param defines the list of defines currently in use
  84049. */
  84050. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84051. if (defines.EXPOSURE) {
  84052. uniforms.push("exposureLinear");
  84053. }
  84054. if (defines.CONTRAST) {
  84055. uniforms.push("contrast");
  84056. }
  84057. if (defines.COLORGRADING) {
  84058. uniforms.push("colorTransformSettings");
  84059. }
  84060. if (defines.VIGNETTE) {
  84061. uniforms.push("vInverseScreenSize");
  84062. uniforms.push("vignetteSettings1");
  84063. uniforms.push("vignetteSettings2");
  84064. }
  84065. if (defines.COLORCURVES) {
  84066. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84067. }
  84068. };
  84069. /**
  84070. * Prepare the list of samplers associated with the Image Processing effects.
  84071. * @param uniformsList The list of uniforms used in the effect
  84072. * @param defines the list of defines currently in use
  84073. */
  84074. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84075. if (defines.COLORGRADING) {
  84076. samplersList.push("txColorTransform");
  84077. }
  84078. };
  84079. /**
  84080. * Prepare the list of defines associated to the shader.
  84081. * @param defines the list of defines to complete
  84082. */
  84083. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84084. if (forPostProcess === void 0) { forPostProcess = false; }
  84085. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84086. defines.VIGNETTE = false;
  84087. defines.TONEMAPPING = false;
  84088. defines.TONEMAPPING_ACES = false;
  84089. defines.CONTRAST = false;
  84090. defines.EXPOSURE = false;
  84091. defines.COLORCURVES = false;
  84092. defines.COLORGRADING = false;
  84093. defines.COLORGRADING3D = false;
  84094. defines.IMAGEPROCESSING = false;
  84095. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84096. return;
  84097. }
  84098. defines.VIGNETTE = this.vignetteEnabled;
  84099. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84100. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84101. defines.TONEMAPPING = this.toneMappingEnabled;
  84102. switch (this._toneMappingType) {
  84103. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84104. defines.TONEMAPPING_ACES = true;
  84105. break;
  84106. }
  84107. defines.CONTRAST = (this.contrast !== 1.0);
  84108. defines.EXPOSURE = (this.exposure !== 1.0);
  84109. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84110. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84111. if (defines.COLORGRADING) {
  84112. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84113. }
  84114. else {
  84115. defines.COLORGRADING3D = false;
  84116. }
  84117. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84118. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84119. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84120. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84121. };
  84122. /**
  84123. * Returns true if all the image processing information are ready.
  84124. */
  84125. ImageProcessingConfiguration.prototype.isReady = function () {
  84126. // Color Grading texure can not be none blocking.
  84127. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84128. };
  84129. /**
  84130. * Binds the image processing to the shader.
  84131. * @param effect The effect to bind to
  84132. */
  84133. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84134. if (aspectRatio === void 0) { aspectRatio = 1; }
  84135. // Color Curves
  84136. if (this._colorCurvesEnabled && this.colorCurves) {
  84137. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84138. }
  84139. // Vignette
  84140. if (this._vignetteEnabled) {
  84141. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84142. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84143. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84144. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84145. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84146. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84147. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84148. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84149. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84150. var vignettePower = -2.0 * this.vignetteWeight;
  84151. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84152. }
  84153. // Exposure
  84154. effect.setFloat("exposureLinear", this.exposure);
  84155. // Contrast
  84156. effect.setFloat("contrast", this.contrast);
  84157. // Color transform settings
  84158. if (this.colorGradingTexture) {
  84159. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84160. var textureSize = this.colorGradingTexture.getSize().height;
  84161. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84162. 0.5 / textureSize, // textureOffset
  84163. textureSize, // textureSize
  84164. this.colorGradingTexture.level // weight
  84165. );
  84166. }
  84167. };
  84168. /**
  84169. * Clones the current image processing instance.
  84170. * @return The cloned image processing
  84171. */
  84172. ImageProcessingConfiguration.prototype.clone = function () {
  84173. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84174. };
  84175. /**
  84176. * Serializes the current image processing instance to a json representation.
  84177. * @return a JSON representation
  84178. */
  84179. ImageProcessingConfiguration.prototype.serialize = function () {
  84180. return BABYLON.SerializationHelper.Serialize(this);
  84181. };
  84182. /**
  84183. * Parses the image processing from a json representation.
  84184. * @param source the JSON source to parse
  84185. * @return The parsed image processing
  84186. */
  84187. ImageProcessingConfiguration.Parse = function (source) {
  84188. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84189. };
  84190. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84191. /**
  84192. * Used to apply the vignette as a mix with the pixel color.
  84193. */
  84194. get: function () {
  84195. return this._VIGNETTEMODE_MULTIPLY;
  84196. },
  84197. enumerable: true,
  84198. configurable: true
  84199. });
  84200. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84201. /**
  84202. * Used to apply the vignette as a replacement of the pixel color.
  84203. */
  84204. get: function () {
  84205. return this._VIGNETTEMODE_OPAQUE;
  84206. },
  84207. enumerable: true,
  84208. configurable: true
  84209. });
  84210. /**
  84211. * Default tone mapping applied in BabylonJS.
  84212. */
  84213. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84214. /**
  84215. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84216. * to other engines rendering to increase portability.
  84217. */
  84218. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84219. // Static constants associated to the image processing.
  84220. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84221. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84222. __decorate([
  84223. BABYLON.serializeAsColorCurves()
  84224. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84225. __decorate([
  84226. BABYLON.serialize()
  84227. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84228. __decorate([
  84229. BABYLON.serializeAsTexture()
  84230. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84231. __decorate([
  84232. BABYLON.serialize()
  84233. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84234. __decorate([
  84235. BABYLON.serialize()
  84236. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84237. __decorate([
  84238. BABYLON.serialize()
  84239. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84240. __decorate([
  84241. BABYLON.serialize()
  84242. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84243. __decorate([
  84244. BABYLON.serialize()
  84245. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84246. __decorate([
  84247. BABYLON.serialize()
  84248. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84249. __decorate([
  84250. BABYLON.serialize()
  84251. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84252. __decorate([
  84253. BABYLON.serialize()
  84254. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84255. __decorate([
  84256. BABYLON.serialize()
  84257. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84258. __decorate([
  84259. BABYLON.serialize()
  84260. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84261. __decorate([
  84262. BABYLON.serialize()
  84263. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84264. __decorate([
  84265. BABYLON.serializeAsColor4()
  84266. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84267. __decorate([
  84268. BABYLON.serialize()
  84269. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84270. __decorate([
  84271. BABYLON.serialize()
  84272. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84273. __decorate([
  84274. BABYLON.serialize()
  84275. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84276. __decorate([
  84277. BABYLON.serialize()
  84278. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84279. __decorate([
  84280. BABYLON.serialize()
  84281. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84282. return ImageProcessingConfiguration;
  84283. }());
  84284. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84285. })(BABYLON || (BABYLON = {}));
  84286. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  84287. var BABYLON;
  84288. (function (BABYLON) {
  84289. /**
  84290. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  84291. * It can help converting any input color in a desired output one. This can then be used to create effects
  84292. * from sepia, black and white to sixties or futuristic rendering...
  84293. *
  84294. * The only supported format is currently 3dl.
  84295. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  84296. */
  84297. var ColorGradingTexture = /** @class */ (function (_super) {
  84298. __extends(ColorGradingTexture, _super);
  84299. /**
  84300. * Instantiates a ColorGradingTexture from the following parameters.
  84301. *
  84302. * @param url The location of the color gradind data (currently only supporting 3dl)
  84303. * @param scene The scene the texture will be used in
  84304. */
  84305. function ColorGradingTexture(url, scene) {
  84306. var _this = _super.call(this, scene) || this;
  84307. if (!url) {
  84308. return _this;
  84309. }
  84310. _this._engine = scene.getEngine();
  84311. _this._textureMatrix = BABYLON.Matrix.Identity();
  84312. _this.name = url;
  84313. _this.url = url;
  84314. _this.hasAlpha = false;
  84315. _this.isCube = false;
  84316. _this.is3D = _this._engine.webGLVersion > 1;
  84317. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84318. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84319. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84320. _this.anisotropicFilteringLevel = 1;
  84321. _this._texture = _this._getFromCache(url, true);
  84322. if (!_this._texture) {
  84323. if (!scene.useDelayedTextureLoading) {
  84324. _this.loadTexture();
  84325. }
  84326. else {
  84327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84328. }
  84329. }
  84330. return _this;
  84331. }
  84332. /**
  84333. * Returns the texture matrix used in most of the material.
  84334. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  84335. */
  84336. ColorGradingTexture.prototype.getTextureMatrix = function () {
  84337. return this._textureMatrix;
  84338. };
  84339. /**
  84340. * Occurs when the file being loaded is a .3dl LUT file.
  84341. */
  84342. ColorGradingTexture.prototype.load3dlTexture = function () {
  84343. var engine = this._engine;
  84344. var texture;
  84345. if (engine.webGLVersion === 1) {
  84346. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84347. }
  84348. else {
  84349. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84350. }
  84351. this._texture = texture;
  84352. var callback = function (text) {
  84353. if (typeof text !== "string") {
  84354. return;
  84355. }
  84356. var data = null;
  84357. var tempData = null;
  84358. var line;
  84359. var lines = text.split('\n');
  84360. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  84361. var maxColor = 0;
  84362. for (var i = 0; i < lines.length; i++) {
  84363. line = lines[i];
  84364. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  84365. continue;
  84366. if (line.indexOf('#') === 0)
  84367. continue;
  84368. var words = line.split(" ");
  84369. if (size === 0) {
  84370. // Number of space + one
  84371. size = words.length;
  84372. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  84373. tempData = new Float32Array(size * size * size * 4);
  84374. continue;
  84375. }
  84376. if (size != 0) {
  84377. var r = Math.max(parseInt(words[0]), 0);
  84378. var g = Math.max(parseInt(words[1]), 0);
  84379. var b = Math.max(parseInt(words[2]), 0);
  84380. maxColor = Math.max(r, maxColor);
  84381. maxColor = Math.max(g, maxColor);
  84382. maxColor = Math.max(b, maxColor);
  84383. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  84384. if (tempData) {
  84385. tempData[pixelStorageIndex + 0] = r;
  84386. tempData[pixelStorageIndex + 1] = g;
  84387. tempData[pixelStorageIndex + 2] = b;
  84388. }
  84389. pixelIndexSlice++;
  84390. if (pixelIndexSlice % size == 0) {
  84391. pixelIndexH++;
  84392. pixelIndexSlice = 0;
  84393. if (pixelIndexH % size == 0) {
  84394. pixelIndexW++;
  84395. pixelIndexH = 0;
  84396. }
  84397. }
  84398. }
  84399. }
  84400. if (tempData && data) {
  84401. for (var i = 0; i < tempData.length; i++) {
  84402. if (i > 0 && (i + 1) % 4 === 0) {
  84403. data[i] = 255;
  84404. }
  84405. else {
  84406. var value = tempData[i];
  84407. data[i] = (value / maxColor * 255);
  84408. }
  84409. }
  84410. }
  84411. if (texture.is3D) {
  84412. texture.updateSize(size, size, size);
  84413. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84414. }
  84415. else {
  84416. texture.updateSize(size * size, size);
  84417. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84418. }
  84419. };
  84420. var scene = this.getScene();
  84421. if (scene) {
  84422. scene._loadFile(this.url, callback);
  84423. }
  84424. else {
  84425. this._engine._loadFile(this.url, callback);
  84426. }
  84427. return this._texture;
  84428. };
  84429. /**
  84430. * Starts the loading process of the texture.
  84431. */
  84432. ColorGradingTexture.prototype.loadTexture = function () {
  84433. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  84434. this.load3dlTexture();
  84435. }
  84436. };
  84437. /**
  84438. * Clones the color gradind texture.
  84439. */
  84440. ColorGradingTexture.prototype.clone = function () {
  84441. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  84442. // Base texture
  84443. newTexture.level = this.level;
  84444. return newTexture;
  84445. };
  84446. /**
  84447. * Called during delayed load for textures.
  84448. */
  84449. ColorGradingTexture.prototype.delayLoad = function () {
  84450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84451. return;
  84452. }
  84453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84454. this._texture = this._getFromCache(this.url, true);
  84455. if (!this._texture) {
  84456. this.loadTexture();
  84457. }
  84458. };
  84459. /**
  84460. * Parses a color grading texture serialized by Babylon.
  84461. * @param parsedTexture The texture information being parsedTexture
  84462. * @param scene The scene to load the texture in
  84463. * @param rootUrl The root url of the data assets to load
  84464. * @return A color gradind texture
  84465. */
  84466. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84467. var texture = null;
  84468. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84469. texture = new ColorGradingTexture(parsedTexture.name, scene);
  84470. texture.name = parsedTexture.name;
  84471. texture.level = parsedTexture.level;
  84472. }
  84473. return texture;
  84474. };
  84475. /**
  84476. * Serializes the LUT texture to json format.
  84477. */
  84478. ColorGradingTexture.prototype.serialize = function () {
  84479. if (!this.name) {
  84480. return null;
  84481. }
  84482. var serializationObject = {};
  84483. serializationObject.name = this.name;
  84484. serializationObject.level = this.level;
  84485. serializationObject.customType = "BABYLON.ColorGradingTexture";
  84486. return serializationObject;
  84487. };
  84488. /**
  84489. * Empty line regex stored for GC.
  84490. */
  84491. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  84492. return ColorGradingTexture;
  84493. }(BABYLON.BaseTexture));
  84494. BABYLON.ColorGradingTexture = ColorGradingTexture;
  84495. })(BABYLON || (BABYLON = {}));
  84496. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  84497. var BABYLON;
  84498. (function (BABYLON) {
  84499. /**
  84500. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84501. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84502. * 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;
  84503. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84504. */
  84505. var ColorCurves = /** @class */ (function () {
  84506. function ColorCurves() {
  84507. this._dirty = true;
  84508. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  84509. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  84510. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84511. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  84512. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84513. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  84514. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  84515. this._globalHue = 30;
  84516. this._globalDensity = 0;
  84517. this._globalSaturation = 0;
  84518. this._globalExposure = 0;
  84519. this._highlightsHue = 30;
  84520. this._highlightsDensity = 0;
  84521. this._highlightsSaturation = 0;
  84522. this._highlightsExposure = 0;
  84523. this._midtonesHue = 30;
  84524. this._midtonesDensity = 0;
  84525. this._midtonesSaturation = 0;
  84526. this._midtonesExposure = 0;
  84527. this._shadowsHue = 30;
  84528. this._shadowsDensity = 0;
  84529. this._shadowsSaturation = 0;
  84530. this._shadowsExposure = 0;
  84531. }
  84532. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  84533. /**
  84534. * Gets the global Hue value.
  84535. * 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).
  84536. */
  84537. get: function () {
  84538. return this._globalHue;
  84539. },
  84540. /**
  84541. * Sets the global Hue value.
  84542. * 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).
  84543. */
  84544. set: function (value) {
  84545. this._globalHue = value;
  84546. this._dirty = true;
  84547. },
  84548. enumerable: true,
  84549. configurable: true
  84550. });
  84551. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  84552. /**
  84553. * Gets the global Density value.
  84554. * 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.
  84555. * Values less than zero provide a filter of opposite hue.
  84556. */
  84557. get: function () {
  84558. return this._globalDensity;
  84559. },
  84560. /**
  84561. * Sets the global Density value.
  84562. * 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.
  84563. * Values less than zero provide a filter of opposite hue.
  84564. */
  84565. set: function (value) {
  84566. this._globalDensity = value;
  84567. this._dirty = true;
  84568. },
  84569. enumerable: true,
  84570. configurable: true
  84571. });
  84572. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  84573. /**
  84574. * Gets the global Saturation value.
  84575. * 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.
  84576. */
  84577. get: function () {
  84578. return this._globalSaturation;
  84579. },
  84580. /**
  84581. * Sets the global Saturation value.
  84582. * 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.
  84583. */
  84584. set: function (value) {
  84585. this._globalSaturation = value;
  84586. this._dirty = true;
  84587. },
  84588. enumerable: true,
  84589. configurable: true
  84590. });
  84591. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  84592. /**
  84593. * Gets the global Exposure value.
  84594. * 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.
  84595. */
  84596. get: function () {
  84597. return this._globalExposure;
  84598. },
  84599. /**
  84600. * Sets the global Exposure value.
  84601. * 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.
  84602. */
  84603. set: function (value) {
  84604. this._globalExposure = value;
  84605. this._dirty = true;
  84606. },
  84607. enumerable: true,
  84608. configurable: true
  84609. });
  84610. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  84611. /**
  84612. * Gets the highlights Hue value.
  84613. * 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).
  84614. */
  84615. get: function () {
  84616. return this._highlightsHue;
  84617. },
  84618. /**
  84619. * Sets the highlights Hue value.
  84620. * 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).
  84621. */
  84622. set: function (value) {
  84623. this._highlightsHue = value;
  84624. this._dirty = true;
  84625. },
  84626. enumerable: true,
  84627. configurable: true
  84628. });
  84629. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  84630. /**
  84631. * Gets the highlights Density value.
  84632. * 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.
  84633. * Values less than zero provide a filter of opposite hue.
  84634. */
  84635. get: function () {
  84636. return this._highlightsDensity;
  84637. },
  84638. /**
  84639. * Sets the highlights Density value.
  84640. * 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.
  84641. * Values less than zero provide a filter of opposite hue.
  84642. */
  84643. set: function (value) {
  84644. this._highlightsDensity = value;
  84645. this._dirty = true;
  84646. },
  84647. enumerable: true,
  84648. configurable: true
  84649. });
  84650. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  84651. /**
  84652. * Gets the highlights Saturation value.
  84653. * 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.
  84654. */
  84655. get: function () {
  84656. return this._highlightsSaturation;
  84657. },
  84658. /**
  84659. * Sets the highlights Saturation value.
  84660. * 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.
  84661. */
  84662. set: function (value) {
  84663. this._highlightsSaturation = value;
  84664. this._dirty = true;
  84665. },
  84666. enumerable: true,
  84667. configurable: true
  84668. });
  84669. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  84670. /**
  84671. * Gets the highlights Exposure value.
  84672. * 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.
  84673. */
  84674. get: function () {
  84675. return this._highlightsExposure;
  84676. },
  84677. /**
  84678. * Sets the highlights Exposure value.
  84679. * 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.
  84680. */
  84681. set: function (value) {
  84682. this._highlightsExposure = value;
  84683. this._dirty = true;
  84684. },
  84685. enumerable: true,
  84686. configurable: true
  84687. });
  84688. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  84689. /**
  84690. * Gets the midtones Hue value.
  84691. * 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).
  84692. */
  84693. get: function () {
  84694. return this._midtonesHue;
  84695. },
  84696. /**
  84697. * Sets the midtones Hue value.
  84698. * 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).
  84699. */
  84700. set: function (value) {
  84701. this._midtonesHue = value;
  84702. this._dirty = true;
  84703. },
  84704. enumerable: true,
  84705. configurable: true
  84706. });
  84707. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  84708. /**
  84709. * Gets the midtones Density value.
  84710. * 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.
  84711. * Values less than zero provide a filter of opposite hue.
  84712. */
  84713. get: function () {
  84714. return this._midtonesDensity;
  84715. },
  84716. /**
  84717. * Sets the midtones Density value.
  84718. * 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.
  84719. * Values less than zero provide a filter of opposite hue.
  84720. */
  84721. set: function (value) {
  84722. this._midtonesDensity = value;
  84723. this._dirty = true;
  84724. },
  84725. enumerable: true,
  84726. configurable: true
  84727. });
  84728. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  84729. /**
  84730. * Gets the midtones Saturation value.
  84731. * 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.
  84732. */
  84733. get: function () {
  84734. return this._midtonesSaturation;
  84735. },
  84736. /**
  84737. * Sets the midtones Saturation value.
  84738. * 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.
  84739. */
  84740. set: function (value) {
  84741. this._midtonesSaturation = value;
  84742. this._dirty = true;
  84743. },
  84744. enumerable: true,
  84745. configurable: true
  84746. });
  84747. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  84748. /**
  84749. * Gets the midtones Exposure value.
  84750. * 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.
  84751. */
  84752. get: function () {
  84753. return this._midtonesExposure;
  84754. },
  84755. /**
  84756. * Sets the midtones Exposure value.
  84757. * 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.
  84758. */
  84759. set: function (value) {
  84760. this._midtonesExposure = value;
  84761. this._dirty = true;
  84762. },
  84763. enumerable: true,
  84764. configurable: true
  84765. });
  84766. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  84767. /**
  84768. * Gets the shadows Hue value.
  84769. * 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).
  84770. */
  84771. get: function () {
  84772. return this._shadowsHue;
  84773. },
  84774. /**
  84775. * Sets the shadows Hue value.
  84776. * 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).
  84777. */
  84778. set: function (value) {
  84779. this._shadowsHue = value;
  84780. this._dirty = true;
  84781. },
  84782. enumerable: true,
  84783. configurable: true
  84784. });
  84785. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  84786. /**
  84787. * Gets the shadows Density value.
  84788. * 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.
  84789. * Values less than zero provide a filter of opposite hue.
  84790. */
  84791. get: function () {
  84792. return this._shadowsDensity;
  84793. },
  84794. /**
  84795. * Sets the shadows Density value.
  84796. * 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.
  84797. * Values less than zero provide a filter of opposite hue.
  84798. */
  84799. set: function (value) {
  84800. this._shadowsDensity = value;
  84801. this._dirty = true;
  84802. },
  84803. enumerable: true,
  84804. configurable: true
  84805. });
  84806. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  84807. /**
  84808. * Gets the shadows Saturation value.
  84809. * 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.
  84810. */
  84811. get: function () {
  84812. return this._shadowsSaturation;
  84813. },
  84814. /**
  84815. * Sets the shadows Saturation value.
  84816. * 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.
  84817. */
  84818. set: function (value) {
  84819. this._shadowsSaturation = value;
  84820. this._dirty = true;
  84821. },
  84822. enumerable: true,
  84823. configurable: true
  84824. });
  84825. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  84826. /**
  84827. * Gets the shadows Exposure value.
  84828. * 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.
  84829. */
  84830. get: function () {
  84831. return this._shadowsExposure;
  84832. },
  84833. /**
  84834. * Sets the shadows Exposure value.
  84835. * 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.
  84836. */
  84837. set: function (value) {
  84838. this._shadowsExposure = value;
  84839. this._dirty = true;
  84840. },
  84841. enumerable: true,
  84842. configurable: true
  84843. });
  84844. ColorCurves.prototype.getClassName = function () {
  84845. return "ColorCurves";
  84846. };
  84847. /**
  84848. * Binds the color curves to the shader.
  84849. * @param colorCurves The color curve to bind
  84850. * @param effect The effect to bind to
  84851. */
  84852. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  84853. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  84854. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  84855. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  84856. if (colorCurves._dirty) {
  84857. colorCurves._dirty = false;
  84858. // Fill in global info.
  84859. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  84860. // Compute highlights info.
  84861. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  84862. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  84863. // Compute midtones info.
  84864. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  84865. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  84866. // Compute shadows info.
  84867. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  84868. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  84869. // Compute deltas (neutral is midtones).
  84870. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  84871. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  84872. }
  84873. if (effect) {
  84874. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  84875. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  84876. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  84877. }
  84878. };
  84879. /**
  84880. * Prepare the list of uniforms associated with the ColorCurves effects.
  84881. * @param uniformsList The list of uniforms used in the effect
  84882. */
  84883. ColorCurves.PrepareUniforms = function (uniformsList) {
  84884. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  84885. };
  84886. /**
  84887. * Returns color grading data based on a hue, density, saturation and exposure value.
  84888. * @param filterHue The hue of the color filter.
  84889. * @param filterDensity The density of the color filter.
  84890. * @param saturation The saturation.
  84891. * @param exposure The exposure.
  84892. * @param result The result data container.
  84893. */
  84894. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  84895. if (hue == null) {
  84896. return;
  84897. }
  84898. hue = ColorCurves.clamp(hue, 0, 360);
  84899. density = ColorCurves.clamp(density, -100, 100);
  84900. saturation = ColorCurves.clamp(saturation, -100, 100);
  84901. exposure = ColorCurves.clamp(exposure, -100, 100);
  84902. // Remap the slider/config filter density with non-linear mapping and also scale by half
  84903. // so that the maximum filter density is only 50% control. This provides fine control
  84904. // for small values and reasonable range.
  84905. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  84906. density *= 0.5;
  84907. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  84908. if (density < 0) {
  84909. density *= -1;
  84910. hue = (hue + 180) % 360;
  84911. }
  84912. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  84913. result.scaleToRef(2, result);
  84914. result.a = 1 + 0.01 * saturation;
  84915. };
  84916. /**
  84917. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  84918. * @param value The input slider value in range [-100,100].
  84919. * @returns Adjusted value.
  84920. */
  84921. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  84922. value /= 100;
  84923. var x = Math.abs(value);
  84924. x = Math.pow(x, 2);
  84925. if (value < 0) {
  84926. x *= -1;
  84927. }
  84928. x *= 100;
  84929. return x;
  84930. };
  84931. /**
  84932. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  84933. * @param hue The hue (H) input.
  84934. * @param saturation The saturation (S) input.
  84935. * @param brightness The brightness (B) input.
  84936. * @result An RGBA color represented as Vector4.
  84937. */
  84938. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  84939. var h = ColorCurves.clamp(hue, 0, 360);
  84940. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  84941. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  84942. if (s === 0) {
  84943. result.r = v;
  84944. result.g = v;
  84945. result.b = v;
  84946. }
  84947. else {
  84948. // sector 0 to 5
  84949. h /= 60;
  84950. var i = Math.floor(h);
  84951. // fractional part of h
  84952. var f = h - i;
  84953. var p = v * (1 - s);
  84954. var q = v * (1 - s * f);
  84955. var t = v * (1 - s * (1 - f));
  84956. switch (i) {
  84957. case 0:
  84958. result.r = v;
  84959. result.g = t;
  84960. result.b = p;
  84961. break;
  84962. case 1:
  84963. result.r = q;
  84964. result.g = v;
  84965. result.b = p;
  84966. break;
  84967. case 2:
  84968. result.r = p;
  84969. result.g = v;
  84970. result.b = t;
  84971. break;
  84972. case 3:
  84973. result.r = p;
  84974. result.g = q;
  84975. result.b = v;
  84976. break;
  84977. case 4:
  84978. result.r = t;
  84979. result.g = p;
  84980. result.b = v;
  84981. break;
  84982. default: // case 5:
  84983. result.r = v;
  84984. result.g = p;
  84985. result.b = q;
  84986. break;
  84987. }
  84988. }
  84989. result.a = 1;
  84990. };
  84991. /**
  84992. * Returns a value clamped between min and max
  84993. * @param value The value to clamp
  84994. * @param min The minimum of value
  84995. * @param max The maximum of value
  84996. * @returns The clamped value.
  84997. */
  84998. ColorCurves.clamp = function (value, min, max) {
  84999. return Math.min(Math.max(value, min), max);
  85000. };
  85001. /**
  85002. * Clones the current color curve instance.
  85003. * @return The cloned curves
  85004. */
  85005. ColorCurves.prototype.clone = function () {
  85006. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85007. };
  85008. /**
  85009. * Serializes the current color curve instance to a json representation.
  85010. * @return a JSON representation
  85011. */
  85012. ColorCurves.prototype.serialize = function () {
  85013. return BABYLON.SerializationHelper.Serialize(this);
  85014. };
  85015. /**
  85016. * Parses the color curve from a json representation.
  85017. * @param source the JSON source to parse
  85018. * @return The parsed curves
  85019. */
  85020. ColorCurves.Parse = function (source) {
  85021. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85022. };
  85023. __decorate([
  85024. BABYLON.serialize()
  85025. ], ColorCurves.prototype, "_globalHue", void 0);
  85026. __decorate([
  85027. BABYLON.serialize()
  85028. ], ColorCurves.prototype, "_globalDensity", void 0);
  85029. __decorate([
  85030. BABYLON.serialize()
  85031. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85032. __decorate([
  85033. BABYLON.serialize()
  85034. ], ColorCurves.prototype, "_globalExposure", void 0);
  85035. __decorate([
  85036. BABYLON.serialize()
  85037. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85038. __decorate([
  85039. BABYLON.serialize()
  85040. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85041. __decorate([
  85042. BABYLON.serialize()
  85043. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85044. __decorate([
  85045. BABYLON.serialize()
  85046. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85047. __decorate([
  85048. BABYLON.serialize()
  85049. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85050. __decorate([
  85051. BABYLON.serialize()
  85052. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85053. __decorate([
  85054. BABYLON.serialize()
  85055. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85056. __decorate([
  85057. BABYLON.serialize()
  85058. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85059. return ColorCurves;
  85060. }());
  85061. BABYLON.ColorCurves = ColorCurves;
  85062. })(BABYLON || (BABYLON = {}));
  85063. //# sourceMappingURL=babylon.colorCurves.js.map
  85064. var BABYLON;
  85065. (function (BABYLON) {
  85066. var RefractionPostProcess = /** @class */ (function (_super) {
  85067. __extends(RefractionPostProcess, _super);
  85068. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85069. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85070. _this.color = color;
  85071. _this.depth = depth;
  85072. _this.colorLevel = colorLevel;
  85073. _this._ownRefractionTexture = true;
  85074. _this.onActivateObservable.add(function (cam) {
  85075. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85076. });
  85077. _this.onApplyObservable.add(function (effect) {
  85078. effect.setColor3("baseColor", _this.color);
  85079. effect.setFloat("depth", _this.depth);
  85080. effect.setFloat("colorLevel", _this.colorLevel);
  85081. effect.setTexture("refractionSampler", _this._refTexture);
  85082. });
  85083. return _this;
  85084. }
  85085. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85086. /**
  85087. * Gets or sets the refraction texture
  85088. * Please note that you are responsible for disposing the texture if you set it manually
  85089. */
  85090. get: function () {
  85091. return this._refTexture;
  85092. },
  85093. set: function (value) {
  85094. if (this._refTexture && this._ownRefractionTexture) {
  85095. this._refTexture.dispose();
  85096. }
  85097. this._refTexture = value;
  85098. this._ownRefractionTexture = false;
  85099. },
  85100. enumerable: true,
  85101. configurable: true
  85102. });
  85103. // Methods
  85104. RefractionPostProcess.prototype.dispose = function (camera) {
  85105. if (this._refTexture && this._ownRefractionTexture) {
  85106. this._refTexture.dispose();
  85107. this._refTexture = null;
  85108. }
  85109. _super.prototype.dispose.call(this, camera);
  85110. };
  85111. return RefractionPostProcess;
  85112. }(BABYLON.PostProcess));
  85113. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85114. })(BABYLON || (BABYLON = {}));
  85115. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85116. var BABYLON;
  85117. (function (BABYLON) {
  85118. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85119. __extends(BlackAndWhitePostProcess, _super);
  85120. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85121. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85122. _this.degree = 1;
  85123. _this.onApplyObservable.add(function (effect) {
  85124. effect.setFloat("degree", _this.degree);
  85125. });
  85126. return _this;
  85127. }
  85128. return BlackAndWhitePostProcess;
  85129. }(BABYLON.PostProcess));
  85130. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85131. })(BABYLON || (BABYLON = {}));
  85132. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85133. var BABYLON;
  85134. (function (BABYLON) {
  85135. /**
  85136. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85137. * input texture to perform effects such as edge detection or sharpening
  85138. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85139. */
  85140. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85141. __extends(ConvolutionPostProcess, _super);
  85142. /**
  85143. * Creates a new instance ConvolutionPostProcess
  85144. * @param name The name of the effect.
  85145. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85146. * @param options The required width/height ratio to downsize to before computing the render pass.
  85147. * @param camera The camera to apply the render pass to.
  85148. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85149. * @param engine The engine which the post process will be applied. (default: current engine)
  85150. * @param reusable If the post process can be reused on the same frame. (default: false)
  85151. * @param textureType Type of textures used when performing the post process. (default: 0)
  85152. */
  85153. function ConvolutionPostProcess(name,
  85154. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85155. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85156. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85157. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85158. _this.kernel = kernel;
  85159. _this.onApply = function (effect) {
  85160. effect.setFloat2("screenSize", _this.width, _this.height);
  85161. effect.setArray("kernel", _this.kernel);
  85162. };
  85163. return _this;
  85164. }
  85165. // Statics
  85166. /**
  85167. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85168. */
  85169. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85170. /**
  85171. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85172. */
  85173. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85174. /**
  85175. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85176. */
  85177. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85178. /**
  85179. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85180. */
  85181. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85182. /**
  85183. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85184. */
  85185. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85186. /**
  85187. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85188. */
  85189. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85190. return ConvolutionPostProcess;
  85191. }(BABYLON.PostProcess));
  85192. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85193. })(BABYLON || (BABYLON = {}));
  85194. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85195. var BABYLON;
  85196. (function (BABYLON) {
  85197. var FilterPostProcess = /** @class */ (function (_super) {
  85198. __extends(FilterPostProcess, _super);
  85199. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85200. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85201. _this.kernelMatrix = kernelMatrix;
  85202. _this.onApply = function (effect) {
  85203. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85204. };
  85205. return _this;
  85206. }
  85207. return FilterPostProcess;
  85208. }(BABYLON.PostProcess));
  85209. BABYLON.FilterPostProcess = FilterPostProcess;
  85210. })(BABYLON || (BABYLON = {}));
  85211. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85212. var BABYLON;
  85213. (function (BABYLON) {
  85214. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85215. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85216. __extends(VolumetricLightScatteringPostProcess, _super);
  85217. /**
  85218. * @constructor
  85219. * @param {string} name - The post-process name
  85220. * @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)
  85221. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85222. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85223. * @param {number} samples - The post-process quality, default 100
  85224. * @param {number} samplingMode - The post-process filtering mode
  85225. * @param {BABYLON.Engine} engine - The babylon engine
  85226. * @param {boolean} reusable - If the post-process is reusable
  85227. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85228. */
  85229. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85230. if (samples === void 0) { samples = 100; }
  85231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85232. 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;
  85233. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85234. /**
  85235. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85236. */
  85237. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85238. /**
  85239. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85240. */
  85241. _this.useCustomMeshPosition = false;
  85242. /**
  85243. * If the post-process should inverse the light scattering direction
  85244. */
  85245. _this.invert = true;
  85246. /**
  85247. * Array containing the excluded meshes not rendered in the internal pass
  85248. */
  85249. _this.excludedMeshes = new Array();
  85250. /**
  85251. * Controls the overall intensity of the post-process
  85252. */
  85253. _this.exposure = 0.3;
  85254. /**
  85255. * Dissipates each sample's contribution in range [0, 1]
  85256. */
  85257. _this.decay = 0.96815;
  85258. /**
  85259. * Controls the overall intensity of each sample
  85260. */
  85261. _this.weight = 0.58767;
  85262. /**
  85263. * Controls the density of each sample
  85264. */
  85265. _this.density = 0.926;
  85266. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85267. engine = scene.getEngine();
  85268. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85269. // Configure mesh
  85270. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85271. // Configure
  85272. _this._createPass(scene, ratio.passRatio || ratio);
  85273. _this.onActivate = function (camera) {
  85274. if (!_this.isSupported) {
  85275. _this.dispose(camera);
  85276. }
  85277. _this.onActivate = null;
  85278. };
  85279. _this.onApplyObservable.add(function (effect) {
  85280. _this._updateMeshScreenCoordinates(scene);
  85281. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85282. effect.setFloat("exposure", _this.exposure);
  85283. effect.setFloat("decay", _this.decay);
  85284. effect.setFloat("weight", _this.weight);
  85285. effect.setFloat("density", _this.density);
  85286. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  85287. });
  85288. return _this;
  85289. }
  85290. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  85291. get: function () {
  85292. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85293. return false;
  85294. },
  85295. set: function (useDiffuseColor) {
  85296. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85297. },
  85298. enumerable: true,
  85299. configurable: true
  85300. });
  85301. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  85302. return "VolumetricLightScatteringPostProcess";
  85303. };
  85304. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  85305. var mesh = subMesh.getMesh();
  85306. // Render this.mesh as default
  85307. if (mesh === this.mesh && mesh.material) {
  85308. return mesh.material.isReady(mesh);
  85309. }
  85310. var defines = [];
  85311. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85312. var material = subMesh.getMaterial();
  85313. // Alpha test
  85314. if (material) {
  85315. if (material.needAlphaTesting()) {
  85316. defines.push("#define ALPHATEST");
  85317. }
  85318. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85319. attribs.push(BABYLON.VertexBuffer.UVKind);
  85320. defines.push("#define UV1");
  85321. }
  85322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85323. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85324. defines.push("#define UV2");
  85325. }
  85326. }
  85327. // Bones
  85328. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85329. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85330. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85331. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85332. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85333. }
  85334. else {
  85335. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85336. }
  85337. // Instances
  85338. if (useInstances) {
  85339. defines.push("#define INSTANCES");
  85340. attribs.push("world0");
  85341. attribs.push("world1");
  85342. attribs.push("world2");
  85343. attribs.push("world3");
  85344. }
  85345. // Get correct effect
  85346. var join = defines.join("\n");
  85347. if (this._cachedDefines !== join) {
  85348. this._cachedDefines = join;
  85349. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  85350. }
  85351. return this._volumetricLightScatteringPass.isReady();
  85352. };
  85353. /**
  85354. * Sets the new light position for light scattering effect
  85355. * @param {BABYLON.Vector3} The new custom light position
  85356. */
  85357. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  85358. this.customMeshPosition = position;
  85359. };
  85360. /**
  85361. * Returns the light position for light scattering effect
  85362. * @return {BABYLON.Vector3} The custom light position
  85363. */
  85364. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  85365. return this.customMeshPosition;
  85366. };
  85367. /**
  85368. * Disposes the internal assets and detaches the post-process from the camera
  85369. */
  85370. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  85371. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  85372. if (rttIndex !== -1) {
  85373. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  85374. }
  85375. this._volumetricLightScatteringRTT.dispose();
  85376. _super.prototype.dispose.call(this, camera);
  85377. };
  85378. /**
  85379. * Returns the render target texture used by the post-process
  85380. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  85381. */
  85382. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  85383. return this._volumetricLightScatteringRTT;
  85384. };
  85385. // Private methods
  85386. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  85387. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  85388. return true;
  85389. }
  85390. return false;
  85391. };
  85392. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  85393. var _this = this;
  85394. var engine = scene.getEngine();
  85395. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85396. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85397. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85398. this._volumetricLightScatteringRTT.renderList = null;
  85399. this._volumetricLightScatteringRTT.renderParticles = false;
  85400. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  85401. var camera = this.getCamera();
  85402. if (camera) {
  85403. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85404. }
  85405. else {
  85406. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85407. }
  85408. // Custom render function for submeshes
  85409. var renderSubMesh = function (subMesh) {
  85410. var mesh = subMesh.getRenderingMesh();
  85411. if (_this._meshExcluded(mesh)) {
  85412. return;
  85413. }
  85414. var material = subMesh.getMaterial();
  85415. if (!material) {
  85416. return;
  85417. }
  85418. var scene = mesh.getScene();
  85419. var engine = scene.getEngine();
  85420. // Culling
  85421. engine.setState(material.backFaceCulling);
  85422. // Managing instances
  85423. var batch = mesh._getInstancesRenderList(subMesh._id);
  85424. if (batch.mustReturn) {
  85425. return;
  85426. }
  85427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85428. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  85429. var effect = _this._volumetricLightScatteringPass;
  85430. if (mesh === _this.mesh) {
  85431. if (subMesh.effect) {
  85432. effect = subMesh.effect;
  85433. }
  85434. else {
  85435. effect = material.getEffect();
  85436. }
  85437. }
  85438. engine.enableEffect(effect);
  85439. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  85440. if (mesh === _this.mesh) {
  85441. material.bind(mesh.getWorldMatrix(), mesh);
  85442. }
  85443. else {
  85444. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  85445. // Alpha test
  85446. if (material && material.needAlphaTesting()) {
  85447. var alphaTexture = material.getAlphaTestTexture();
  85448. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  85449. if (alphaTexture) {
  85450. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85451. }
  85452. }
  85453. // Bones
  85454. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85455. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85456. }
  85457. }
  85458. // Draw
  85459. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  85460. }
  85461. };
  85462. // Render target texture callbacks
  85463. var savedSceneClearColor;
  85464. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  85465. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  85466. savedSceneClearColor = scene.clearColor;
  85467. scene.clearColor = sceneClearColor;
  85468. });
  85469. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  85470. scene.clearColor = savedSceneClearColor;
  85471. });
  85472. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85473. var engine = scene.getEngine();
  85474. var index;
  85475. if (depthOnlySubMeshes.length) {
  85476. engine.setColorWrite(false);
  85477. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85478. renderSubMesh(depthOnlySubMeshes.data[index]);
  85479. }
  85480. engine.setColorWrite(true);
  85481. }
  85482. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85483. renderSubMesh(opaqueSubMeshes.data[index]);
  85484. }
  85485. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85486. renderSubMesh(alphaTestSubMeshes.data[index]);
  85487. }
  85488. if (transparentSubMeshes.length) {
  85489. // Sort sub meshes
  85490. for (index = 0; index < transparentSubMeshes.length; index++) {
  85491. var submesh = transparentSubMeshes.data[index];
  85492. var boundingInfo = submesh.getBoundingInfo();
  85493. if (boundingInfo && scene.activeCamera) {
  85494. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  85495. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  85496. }
  85497. }
  85498. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  85499. sortedArray.sort(function (a, b) {
  85500. // Alpha index first
  85501. if (a._alphaIndex > b._alphaIndex) {
  85502. return 1;
  85503. }
  85504. if (a._alphaIndex < b._alphaIndex) {
  85505. return -1;
  85506. }
  85507. // Then distance to camera
  85508. if (a._distanceToCamera < b._distanceToCamera) {
  85509. return 1;
  85510. }
  85511. if (a._distanceToCamera > b._distanceToCamera) {
  85512. return -1;
  85513. }
  85514. return 0;
  85515. });
  85516. // Render sub meshes
  85517. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  85518. for (index = 0; index < sortedArray.length; index++) {
  85519. renderSubMesh(sortedArray[index]);
  85520. }
  85521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85522. }
  85523. };
  85524. };
  85525. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  85526. var transform = scene.getTransformMatrix();
  85527. var meshPosition;
  85528. if (this.useCustomMeshPosition) {
  85529. meshPosition = this.customMeshPosition;
  85530. }
  85531. else if (this.attachedNode) {
  85532. meshPosition = this.attachedNode.position;
  85533. }
  85534. else {
  85535. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  85536. }
  85537. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  85538. this._screenCoordinates.x = pos.x / this._viewPort.width;
  85539. this._screenCoordinates.y = pos.y / this._viewPort.height;
  85540. if (this.invert)
  85541. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  85542. };
  85543. // Static methods
  85544. /**
  85545. * Creates a default mesh for the Volumeric Light Scattering post-process
  85546. * @param {string} The mesh name
  85547. * @param {BABYLON.Scene} The scene where to create the mesh
  85548. * @return {BABYLON.Mesh} the default mesh
  85549. */
  85550. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  85551. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  85552. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  85553. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  85554. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  85555. mesh.material = material;
  85556. return mesh;
  85557. };
  85558. __decorate([
  85559. BABYLON.serializeAsVector3()
  85560. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  85561. __decorate([
  85562. BABYLON.serialize()
  85563. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  85564. __decorate([
  85565. BABYLON.serialize()
  85566. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  85567. __decorate([
  85568. BABYLON.serializeAsMeshReference()
  85569. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  85570. __decorate([
  85571. BABYLON.serialize()
  85572. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  85573. __decorate([
  85574. BABYLON.serialize()
  85575. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  85576. __decorate([
  85577. BABYLON.serialize()
  85578. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  85579. __decorate([
  85580. BABYLON.serialize()
  85581. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  85582. __decorate([
  85583. BABYLON.serialize()
  85584. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  85585. return VolumetricLightScatteringPostProcess;
  85586. }(BABYLON.PostProcess));
  85587. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  85588. })(BABYLON || (BABYLON = {}));
  85589. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  85590. //
  85591. // This post-process allows the modification of rendered colors by using
  85592. // a 'look-up table' (LUT). This effect is also called Color Grading.
  85593. //
  85594. // The object needs to be provided an url to a texture containing the color
  85595. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  85596. // Use an image editing software to tweak the LUT to match your needs.
  85597. //
  85598. // For an example of a color LUT, see here:
  85599. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  85600. // For explanations on color grading, see here:
  85601. // http://udn.epicgames.com/Three/ColorGrading.html
  85602. //
  85603. var BABYLON;
  85604. (function (BABYLON) {
  85605. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  85606. __extends(ColorCorrectionPostProcess, _super);
  85607. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  85608. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  85609. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85610. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  85611. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85612. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85613. _this.onApply = function (effect) {
  85614. effect.setTexture("colorTable", _this._colorTableTexture);
  85615. };
  85616. return _this;
  85617. }
  85618. return ColorCorrectionPostProcess;
  85619. }(BABYLON.PostProcess));
  85620. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  85621. })(BABYLON || (BABYLON = {}));
  85622. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  85623. var BABYLON;
  85624. (function (BABYLON) {
  85625. /** Defines operator used for tonemapping */
  85626. var TonemappingOperator;
  85627. (function (TonemappingOperator) {
  85628. /** Hable */
  85629. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  85630. /** Reinhard */
  85631. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  85632. /** HejiDawson */
  85633. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  85634. /** Photographic */
  85635. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  85636. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  85637. ;
  85638. /**
  85639. * Defines a post process to apply tone mapping
  85640. */
  85641. var TonemapPostProcess = /** @class */ (function (_super) {
  85642. __extends(TonemapPostProcess, _super);
  85643. /**
  85644. * Creates a new TonemapPostProcess
  85645. * @param name defines the name of the postprocess
  85646. * @param _operator defines the operator to use
  85647. * @param exposureAdjustment defines the required exposure adjustement
  85648. * @param camera defines the camera to use (can be null)
  85649. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  85650. * @param engine defines the hosting engine (can be ignore if camera is set)
  85651. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  85652. */
  85653. function TonemapPostProcess(name, _operator,
  85654. /** Defines the required exposure adjustement */
  85655. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  85656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85657. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85658. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  85659. _this._operator = _operator;
  85660. _this.exposureAdjustment = exposureAdjustment;
  85661. var defines = "#define ";
  85662. if (_this._operator === TonemappingOperator.Hable)
  85663. defines += "HABLE_TONEMAPPING";
  85664. else if (_this._operator === TonemappingOperator.Reinhard)
  85665. defines += "REINHARD_TONEMAPPING";
  85666. else if (_this._operator === TonemappingOperator.HejiDawson)
  85667. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  85668. else if (_this._operator === TonemappingOperator.Photographic)
  85669. defines += "PHOTOGRAPHIC_TONEMAPPING";
  85670. //sadly a second call to create the effect.
  85671. _this.updateEffect(defines);
  85672. _this.onApply = function (effect) {
  85673. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  85674. };
  85675. return _this;
  85676. }
  85677. return TonemapPostProcess;
  85678. }(BABYLON.PostProcess));
  85679. BABYLON.TonemapPostProcess = TonemapPostProcess;
  85680. })(BABYLON || (BABYLON = {}));
  85681. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  85682. var BABYLON;
  85683. (function (BABYLON) {
  85684. var DisplayPassPostProcess = /** @class */ (function (_super) {
  85685. __extends(DisplayPassPostProcess, _super);
  85686. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  85687. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  85688. }
  85689. return DisplayPassPostProcess;
  85690. }(BABYLON.PostProcess));
  85691. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  85692. })(BABYLON || (BABYLON = {}));
  85693. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  85694. var BABYLON;
  85695. (function (BABYLON) {
  85696. var HighlightsPostProcess = /** @class */ (function (_super) {
  85697. __extends(HighlightsPostProcess, _super);
  85698. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85700. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85701. }
  85702. return HighlightsPostProcess;
  85703. }(BABYLON.PostProcess));
  85704. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  85705. })(BABYLON || (BABYLON = {}));
  85706. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  85707. var BABYLON;
  85708. (function (BABYLON) {
  85709. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  85710. __extends(ImageProcessingPostProcess, _super);
  85711. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  85712. if (camera === void 0) { camera = null; }
  85713. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85714. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  85715. _this._fromLinearSpace = true;
  85716. /**
  85717. * Defines cache preventing GC.
  85718. */
  85719. _this._defines = {
  85720. IMAGEPROCESSING: false,
  85721. VIGNETTE: false,
  85722. VIGNETTEBLENDMODEMULTIPLY: false,
  85723. VIGNETTEBLENDMODEOPAQUE: false,
  85724. TONEMAPPING: false,
  85725. TONEMAPPING_ACES: false,
  85726. CONTRAST: false,
  85727. COLORCURVES: false,
  85728. COLORGRADING: false,
  85729. COLORGRADING3D: false,
  85730. FROMLINEARSPACE: false,
  85731. SAMPLER3DGREENDEPTH: false,
  85732. SAMPLER3DBGRMAP: false,
  85733. IMAGEPROCESSINGPOSTPROCESS: false,
  85734. EXPOSURE: false,
  85735. };
  85736. // Setup the configuration as forced by the constructor. This would then not force the
  85737. // scene materials output in linear space and let untouched the default forward pass.
  85738. if (imageProcessingConfiguration) {
  85739. imageProcessingConfiguration.applyByPostProcess = true;
  85740. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  85741. // This will cause the shader to be compiled
  85742. _this.fromLinearSpace = false;
  85743. }
  85744. // Setup the default processing configuration to the scene.
  85745. else {
  85746. _this._attachImageProcessingConfiguration(null, true);
  85747. _this.imageProcessingConfiguration.applyByPostProcess = true;
  85748. }
  85749. _this.onApply = function (effect) {
  85750. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  85751. };
  85752. return _this;
  85753. }
  85754. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  85755. /**
  85756. * Gets the image processing configuration used either in this material.
  85757. */
  85758. get: function () {
  85759. return this._imageProcessingConfiguration;
  85760. },
  85761. /**
  85762. * Sets the Default image processing configuration used either in the this material.
  85763. *
  85764. * If sets to null, the scene one is in use.
  85765. */
  85766. set: function (value) {
  85767. this._attachImageProcessingConfiguration(value);
  85768. },
  85769. enumerable: true,
  85770. configurable: true
  85771. });
  85772. /**
  85773. * Attaches a new image processing configuration to the PBR Material.
  85774. * @param configuration
  85775. */
  85776. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  85777. var _this = this;
  85778. if (doNotBuild === void 0) { doNotBuild = false; }
  85779. if (configuration === this._imageProcessingConfiguration) {
  85780. return;
  85781. }
  85782. // Detaches observer.
  85783. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85784. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85785. }
  85786. // Pick the scene configuration if needed.
  85787. if (!configuration) {
  85788. var scene = null;
  85789. var engine = this.getEngine();
  85790. var camera = this.getCamera();
  85791. if (camera) {
  85792. scene = camera.getScene();
  85793. }
  85794. else if (engine && engine.scenes) {
  85795. var scenes = engine.scenes;
  85796. scene = scenes[scenes.length - 1];
  85797. }
  85798. else {
  85799. scene = BABYLON.Engine.LastCreatedScene;
  85800. }
  85801. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  85802. }
  85803. else {
  85804. this._imageProcessingConfiguration = configuration;
  85805. }
  85806. // Attaches observer.
  85807. if (this._imageProcessingConfiguration) {
  85808. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  85809. _this._updateParameters();
  85810. });
  85811. }
  85812. // Ensure the effect will be rebuilt.
  85813. if (!doNotBuild) {
  85814. this._updateParameters();
  85815. }
  85816. };
  85817. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  85818. /**
  85819. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85820. */
  85821. get: function () {
  85822. return this.imageProcessingConfiguration.colorCurves;
  85823. },
  85824. /**
  85825. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85826. */
  85827. set: function (value) {
  85828. this.imageProcessingConfiguration.colorCurves = value;
  85829. },
  85830. enumerable: true,
  85831. configurable: true
  85832. });
  85833. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  85834. /**
  85835. * Gets wether the color curves effect is enabled.
  85836. */
  85837. get: function () {
  85838. return this.imageProcessingConfiguration.colorCurvesEnabled;
  85839. },
  85840. /**
  85841. * Sets wether the color curves effect is enabled.
  85842. */
  85843. set: function (value) {
  85844. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  85845. },
  85846. enumerable: true,
  85847. configurable: true
  85848. });
  85849. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  85850. /**
  85851. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85852. */
  85853. get: function () {
  85854. return this.imageProcessingConfiguration.colorGradingTexture;
  85855. },
  85856. /**
  85857. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85858. */
  85859. set: function (value) {
  85860. this.imageProcessingConfiguration.colorGradingTexture = value;
  85861. },
  85862. enumerable: true,
  85863. configurable: true
  85864. });
  85865. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  85866. /**
  85867. * Gets wether the color grading effect is enabled.
  85868. */
  85869. get: function () {
  85870. return this.imageProcessingConfiguration.colorGradingEnabled;
  85871. },
  85872. /**
  85873. * Gets wether the color grading effect is enabled.
  85874. */
  85875. set: function (value) {
  85876. this.imageProcessingConfiguration.colorGradingEnabled = value;
  85877. },
  85878. enumerable: true,
  85879. configurable: true
  85880. });
  85881. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  85882. /**
  85883. * Gets exposure used in the effect.
  85884. */
  85885. get: function () {
  85886. return this.imageProcessingConfiguration.exposure;
  85887. },
  85888. /**
  85889. * Sets exposure used in the effect.
  85890. */
  85891. set: function (value) {
  85892. this.imageProcessingConfiguration.exposure = value;
  85893. },
  85894. enumerable: true,
  85895. configurable: true
  85896. });
  85897. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  85898. /**
  85899. * Gets wether tonemapping is enabled or not.
  85900. */
  85901. get: function () {
  85902. return this._imageProcessingConfiguration.toneMappingEnabled;
  85903. },
  85904. /**
  85905. * Sets wether tonemapping is enabled or not
  85906. */
  85907. set: function (value) {
  85908. this._imageProcessingConfiguration.toneMappingEnabled = value;
  85909. },
  85910. enumerable: true,
  85911. configurable: true
  85912. });
  85913. ;
  85914. ;
  85915. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  85916. /**
  85917. * Gets contrast used in the effect.
  85918. */
  85919. get: function () {
  85920. return this.imageProcessingConfiguration.contrast;
  85921. },
  85922. /**
  85923. * Sets contrast used in the effect.
  85924. */
  85925. set: function (value) {
  85926. this.imageProcessingConfiguration.contrast = value;
  85927. },
  85928. enumerable: true,
  85929. configurable: true
  85930. });
  85931. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  85932. /**
  85933. * Gets Vignette stretch size.
  85934. */
  85935. get: function () {
  85936. return this.imageProcessingConfiguration.vignetteStretch;
  85937. },
  85938. /**
  85939. * Sets Vignette stretch size.
  85940. */
  85941. set: function (value) {
  85942. this.imageProcessingConfiguration.vignetteStretch = value;
  85943. },
  85944. enumerable: true,
  85945. configurable: true
  85946. });
  85947. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  85948. /**
  85949. * Gets Vignette centre X Offset.
  85950. */
  85951. get: function () {
  85952. return this.imageProcessingConfiguration.vignetteCentreX;
  85953. },
  85954. /**
  85955. * Sets Vignette centre X Offset.
  85956. */
  85957. set: function (value) {
  85958. this.imageProcessingConfiguration.vignetteCentreX = value;
  85959. },
  85960. enumerable: true,
  85961. configurable: true
  85962. });
  85963. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  85964. /**
  85965. * Gets Vignette centre Y Offset.
  85966. */
  85967. get: function () {
  85968. return this.imageProcessingConfiguration.vignetteCentreY;
  85969. },
  85970. /**
  85971. * Sets Vignette centre Y Offset.
  85972. */
  85973. set: function (value) {
  85974. this.imageProcessingConfiguration.vignetteCentreY = value;
  85975. },
  85976. enumerable: true,
  85977. configurable: true
  85978. });
  85979. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  85980. /**
  85981. * Gets Vignette weight or intensity of the vignette effect.
  85982. */
  85983. get: function () {
  85984. return this.imageProcessingConfiguration.vignetteWeight;
  85985. },
  85986. /**
  85987. * Sets Vignette weight or intensity of the vignette effect.
  85988. */
  85989. set: function (value) {
  85990. this.imageProcessingConfiguration.vignetteWeight = value;
  85991. },
  85992. enumerable: true,
  85993. configurable: true
  85994. });
  85995. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  85996. /**
  85997. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85998. * if vignetteEnabled is set to true.
  85999. */
  86000. get: function () {
  86001. return this.imageProcessingConfiguration.vignetteColor;
  86002. },
  86003. /**
  86004. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86005. * if vignetteEnabled is set to true.
  86006. */
  86007. set: function (value) {
  86008. this.imageProcessingConfiguration.vignetteColor = value;
  86009. },
  86010. enumerable: true,
  86011. configurable: true
  86012. });
  86013. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86014. /**
  86015. * Gets Camera field of view used by the Vignette effect.
  86016. */
  86017. get: function () {
  86018. return this.imageProcessingConfiguration.vignetteCameraFov;
  86019. },
  86020. /**
  86021. * Sets Camera field of view used by the Vignette effect.
  86022. */
  86023. set: function (value) {
  86024. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86025. },
  86026. enumerable: true,
  86027. configurable: true
  86028. });
  86029. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86030. /**
  86031. * Gets the vignette blend mode allowing different kind of effect.
  86032. */
  86033. get: function () {
  86034. return this.imageProcessingConfiguration.vignetteBlendMode;
  86035. },
  86036. /**
  86037. * Sets the vignette blend mode allowing different kind of effect.
  86038. */
  86039. set: function (value) {
  86040. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86041. },
  86042. enumerable: true,
  86043. configurable: true
  86044. });
  86045. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86046. /**
  86047. * Gets wether the vignette effect is enabled.
  86048. */
  86049. get: function () {
  86050. return this.imageProcessingConfiguration.vignetteEnabled;
  86051. },
  86052. /**
  86053. * Sets wether the vignette effect is enabled.
  86054. */
  86055. set: function (value) {
  86056. this.imageProcessingConfiguration.vignetteEnabled = value;
  86057. },
  86058. enumerable: true,
  86059. configurable: true
  86060. });
  86061. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86062. /**
  86063. * Gets wether the input of the processing is in Gamma or Linear Space.
  86064. */
  86065. get: function () {
  86066. return this._fromLinearSpace;
  86067. },
  86068. /**
  86069. * Sets wether the input of the processing is in Gamma or Linear Space.
  86070. */
  86071. set: function (value) {
  86072. if (this._fromLinearSpace === value) {
  86073. return;
  86074. }
  86075. this._fromLinearSpace = value;
  86076. this._updateParameters();
  86077. },
  86078. enumerable: true,
  86079. configurable: true
  86080. });
  86081. ImageProcessingPostProcess.prototype.getClassName = function () {
  86082. return "ImageProcessingPostProcess";
  86083. };
  86084. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86085. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86086. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86087. var defines = "";
  86088. for (var define in this._defines) {
  86089. if (this._defines[define]) {
  86090. defines += "#define " + define + ";\r\n";
  86091. }
  86092. }
  86093. var samplers = ["textureSampler"];
  86094. var uniforms = ["scale"];
  86095. if (BABYLON.ImageProcessingConfiguration) {
  86096. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86097. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86098. }
  86099. this.updateEffect(defines, uniforms, samplers);
  86100. };
  86101. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86102. _super.prototype.dispose.call(this, camera);
  86103. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86104. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86105. }
  86106. if (this._imageProcessingConfiguration) {
  86107. this.imageProcessingConfiguration.applyByPostProcess = false;
  86108. }
  86109. };
  86110. __decorate([
  86111. BABYLON.serialize()
  86112. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86113. return ImageProcessingPostProcess;
  86114. }(BABYLON.PostProcess));
  86115. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86116. })(BABYLON || (BABYLON = {}));
  86117. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86118. var BABYLON;
  86119. (function (BABYLON) {
  86120. /**
  86121. * Class used to store bone information
  86122. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86123. */
  86124. var Bone = /** @class */ (function (_super) {
  86125. __extends(Bone, _super);
  86126. /**
  86127. * Create a new bone
  86128. * @param name defines the bone name
  86129. * @param skeleton defines the parent skeleton
  86130. * @param parentBone defines the parent (can be null if the bone is the root)
  86131. * @param localMatrix defines the local matrix
  86132. * @param restPose defines the rest pose matrix
  86133. * @param baseMatrix defines the base matrix
  86134. * @param index defines index of the bone in the hiearchy
  86135. */
  86136. function Bone(
  86137. /**
  86138. * defines the bone name
  86139. */
  86140. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86141. if (parentBone === void 0) { parentBone = null; }
  86142. if (localMatrix === void 0) { localMatrix = null; }
  86143. if (restPose === void 0) { restPose = null; }
  86144. if (baseMatrix === void 0) { baseMatrix = null; }
  86145. if (index === void 0) { index = null; }
  86146. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86147. _this.name = name;
  86148. /**
  86149. * Gets the list of child bones
  86150. */
  86151. _this.children = new Array();
  86152. /** Gets the animations associated with this bone */
  86153. _this.animations = new Array();
  86154. /**
  86155. * @hidden Internal only
  86156. * Set this value to map this bone to a different index in the transform matrices
  86157. * Set this value to -1 to exclude the bone from the transform matrices
  86158. */
  86159. _this._index = null;
  86160. _this._absoluteTransform = new BABYLON.Matrix();
  86161. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86162. _this._scalingDeterminant = 1;
  86163. _this._worldTransform = new BABYLON.Matrix();
  86164. _this._needToDecompose = true;
  86165. _this._needToCompose = false;
  86166. _this._skeleton = skeleton;
  86167. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86168. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86169. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86170. _this._index = index;
  86171. skeleton.bones.push(_this);
  86172. _this.setParent(parentBone, false);
  86173. if (baseMatrix || localMatrix) {
  86174. _this._updateDifferenceMatrix();
  86175. }
  86176. return _this;
  86177. }
  86178. Object.defineProperty(Bone.prototype, "_matrix", {
  86179. /** @hidden */
  86180. get: function () {
  86181. this._compose();
  86182. return this._localMatrix;
  86183. },
  86184. /** @hidden */
  86185. set: function (value) {
  86186. this._localMatrix.copyFrom(value);
  86187. this._needToDecompose = true;
  86188. },
  86189. enumerable: true,
  86190. configurable: true
  86191. });
  86192. // Members
  86193. /**
  86194. * Gets the parent skeleton
  86195. * @returns a skeleton
  86196. */
  86197. Bone.prototype.getSkeleton = function () {
  86198. return this._skeleton;
  86199. };
  86200. /**
  86201. * Gets parent bone
  86202. * @returns a bone or null if the bone is the root of the bone hierarchy
  86203. */
  86204. Bone.prototype.getParent = function () {
  86205. return this._parent;
  86206. };
  86207. /**
  86208. * Sets the parent bone
  86209. * @param parent defines the parent (can be null if the bone is the root)
  86210. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86211. */
  86212. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86213. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86214. if (this._parent === parent) {
  86215. return;
  86216. }
  86217. if (this._parent) {
  86218. var index = this._parent.children.indexOf(this);
  86219. if (index !== -1) {
  86220. this._parent.children.splice(index, 1);
  86221. }
  86222. }
  86223. this._parent = parent;
  86224. if (this._parent) {
  86225. this._parent.children.push(this);
  86226. }
  86227. if (updateDifferenceMatrix) {
  86228. this._updateDifferenceMatrix();
  86229. }
  86230. this.markAsDirty();
  86231. };
  86232. /**
  86233. * Gets the local matrix
  86234. * @returns a matrix
  86235. */
  86236. Bone.prototype.getLocalMatrix = function () {
  86237. this._compose();
  86238. return this._localMatrix;
  86239. };
  86240. /**
  86241. * Gets the base matrix (initial matrix which remains unchanged)
  86242. * @returns a matrix
  86243. */
  86244. Bone.prototype.getBaseMatrix = function () {
  86245. return this._baseMatrix;
  86246. };
  86247. /**
  86248. * Gets the rest pose matrix
  86249. * @returns a matrix
  86250. */
  86251. Bone.prototype.getRestPose = function () {
  86252. return this._restPose;
  86253. };
  86254. /**
  86255. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86256. */
  86257. Bone.prototype.getWorldMatrix = function () {
  86258. return this._worldTransform;
  86259. };
  86260. /**
  86261. * Sets the local matrix to rest pose matrix
  86262. */
  86263. Bone.prototype.returnToRest = function () {
  86264. this.updateMatrix(this._restPose.clone());
  86265. };
  86266. /**
  86267. * Gets the inverse of the absolute transform matrix.
  86268. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86269. * @returns a matrix
  86270. */
  86271. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86272. return this._invertedAbsoluteTransform;
  86273. };
  86274. /**
  86275. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86276. * @returns a matrix
  86277. */
  86278. Bone.prototype.getAbsoluteTransform = function () {
  86279. return this._absoluteTransform;
  86280. };
  86281. Object.defineProperty(Bone.prototype, "position", {
  86282. // Properties (matches AbstractMesh properties)
  86283. /** Gets or sets current position (in local space) */
  86284. get: function () {
  86285. this._decompose();
  86286. return this._localPosition;
  86287. },
  86288. set: function (newPosition) {
  86289. this._decompose();
  86290. this._localPosition.copyFrom(newPosition);
  86291. this._markAsDirtyAndCompose();
  86292. },
  86293. enumerable: true,
  86294. configurable: true
  86295. });
  86296. Object.defineProperty(Bone.prototype, "rotation", {
  86297. /** Gets or sets current rotation (in local space) */
  86298. get: function () {
  86299. return this.getRotation();
  86300. },
  86301. set: function (newRotation) {
  86302. this.setRotation(newRotation);
  86303. },
  86304. enumerable: true,
  86305. configurable: true
  86306. });
  86307. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  86308. /** Gets or sets current rotation quaternion (in local space) */
  86309. get: function () {
  86310. this._decompose();
  86311. return this._localRotation;
  86312. },
  86313. set: function (newRotation) {
  86314. this.setRotationQuaternion(newRotation);
  86315. },
  86316. enumerable: true,
  86317. configurable: true
  86318. });
  86319. Object.defineProperty(Bone.prototype, "scaling", {
  86320. /** Gets or sets current scaling (in local space) */
  86321. get: function () {
  86322. return this.getScale();
  86323. },
  86324. set: function (newScaling) {
  86325. this.setScale(newScaling);
  86326. },
  86327. enumerable: true,
  86328. configurable: true
  86329. });
  86330. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  86331. /**
  86332. * Gets the animation properties override
  86333. */
  86334. get: function () {
  86335. return this._skeleton.animationPropertiesOverride;
  86336. },
  86337. enumerable: true,
  86338. configurable: true
  86339. });
  86340. // Methods
  86341. Bone.prototype._decompose = function () {
  86342. if (!this._needToDecompose) {
  86343. return;
  86344. }
  86345. this._needToDecompose = false;
  86346. if (!this._localScaling) {
  86347. this._localScaling = BABYLON.Vector3.Zero();
  86348. this._localRotation = BABYLON.Quaternion.Zero();
  86349. this._localPosition = BABYLON.Vector3.Zero();
  86350. }
  86351. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  86352. };
  86353. Bone.prototype._compose = function () {
  86354. if (!this._needToCompose) {
  86355. return;
  86356. }
  86357. this._needToCompose = false;
  86358. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  86359. };
  86360. /**
  86361. * Update the base and local matrices
  86362. * @param matrix defines the new base or local matrix
  86363. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86364. * @param updateLocalMatrix defines if the local matrix should be updated
  86365. */
  86366. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  86367. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86368. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  86369. this._baseMatrix.copyFrom(matrix);
  86370. if (updateDifferenceMatrix) {
  86371. this._updateDifferenceMatrix();
  86372. }
  86373. if (updateLocalMatrix) {
  86374. this._localMatrix.copyFrom(matrix);
  86375. this._markAsDirtyAndDecompose();
  86376. }
  86377. else {
  86378. this.markAsDirty();
  86379. }
  86380. };
  86381. /** @hidden */
  86382. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  86383. if (updateChildren === void 0) { updateChildren = true; }
  86384. if (!rootMatrix) {
  86385. rootMatrix = this._baseMatrix;
  86386. }
  86387. if (this._parent) {
  86388. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86389. }
  86390. else {
  86391. this._absoluteTransform.copyFrom(rootMatrix);
  86392. }
  86393. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  86394. if (updateChildren) {
  86395. for (var index = 0; index < this.children.length; index++) {
  86396. this.children[index]._updateDifferenceMatrix();
  86397. }
  86398. }
  86399. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  86400. };
  86401. /**
  86402. * Flag the bone as dirty (Forcing it to update everything)
  86403. */
  86404. Bone.prototype.markAsDirty = function () {
  86405. this._currentRenderId++;
  86406. this._childRenderId++;
  86407. this._skeleton._markAsDirty();
  86408. };
  86409. Bone.prototype._markAsDirtyAndCompose = function () {
  86410. this.markAsDirty();
  86411. this._needToCompose = true;
  86412. };
  86413. Bone.prototype._markAsDirtyAndDecompose = function () {
  86414. this.markAsDirty();
  86415. this._needToDecompose = true;
  86416. };
  86417. /**
  86418. * Copy an animation range from another bone
  86419. * @param source defines the source bone
  86420. * @param rangeName defines the range name to copy
  86421. * @param frameOffset defines the frame offset
  86422. * @param rescaleAsRequired defines if rescaling must be applied if required
  86423. * @param skelDimensionsRatio defines the scaling ratio
  86424. * @returns true if operation was successful
  86425. */
  86426. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  86427. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86428. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  86429. // all animation may be coming from a library skeleton, so may need to create animation
  86430. if (this.animations.length === 0) {
  86431. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  86432. this.animations[0].setKeys([]);
  86433. }
  86434. // get animation info / verify there is such a range from the source bone
  86435. var sourceRange = source.animations[0].getRange(rangeName);
  86436. if (!sourceRange) {
  86437. return false;
  86438. }
  86439. var from = sourceRange.from;
  86440. var to = sourceRange.to;
  86441. var sourceKeys = source.animations[0].getKeys();
  86442. // rescaling prep
  86443. var sourceBoneLength = source.length;
  86444. var sourceParent = source.getParent();
  86445. var parent = this.getParent();
  86446. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  86447. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  86448. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  86449. var destKeys = this.animations[0].getKeys();
  86450. // loop vars declaration
  86451. var orig;
  86452. var origTranslation;
  86453. var mat;
  86454. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  86455. orig = sourceKeys[key];
  86456. if (orig.frame >= from && orig.frame <= to) {
  86457. if (rescaleAsRequired) {
  86458. mat = orig.value.clone();
  86459. // scale based on parent ratio, when bone has parent
  86460. if (parentScalingReqd) {
  86461. origTranslation = mat.getTranslation();
  86462. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  86463. // scale based on skeleton dimension ratio when root bone, and value is passed
  86464. }
  86465. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  86466. origTranslation = mat.getTranslation();
  86467. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  86468. // use original when root bone, and no data for skelDimensionsRatio
  86469. }
  86470. else {
  86471. mat = orig.value;
  86472. }
  86473. }
  86474. else {
  86475. mat = orig.value;
  86476. }
  86477. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  86478. }
  86479. }
  86480. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  86481. return true;
  86482. };
  86483. /**
  86484. * Translate the bone in local or world space
  86485. * @param vec The amount to translate the bone
  86486. * @param space The space that the translation is in
  86487. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86488. */
  86489. Bone.prototype.translate = function (vec, space, mesh) {
  86490. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86491. var lm = this.getLocalMatrix();
  86492. if (space == BABYLON.Space.LOCAL) {
  86493. lm.m[12] += vec.x;
  86494. lm.m[13] += vec.y;
  86495. lm.m[14] += vec.z;
  86496. }
  86497. else {
  86498. var wm = null;
  86499. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86500. if (mesh) {
  86501. wm = mesh.getWorldMatrix();
  86502. }
  86503. this._skeleton.computeAbsoluteTransforms();
  86504. var tmat = Bone._tmpMats[0];
  86505. var tvec = Bone._tmpVecs[0];
  86506. if (this._parent) {
  86507. if (mesh && wm) {
  86508. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86509. tmat.multiplyToRef(wm, tmat);
  86510. }
  86511. else {
  86512. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86513. }
  86514. }
  86515. tmat.m[12] = 0;
  86516. tmat.m[13] = 0;
  86517. tmat.m[14] = 0;
  86518. tmat.invert();
  86519. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  86520. lm.m[12] += tvec.x;
  86521. lm.m[13] += tvec.y;
  86522. lm.m[14] += tvec.z;
  86523. }
  86524. this._markAsDirtyAndDecompose();
  86525. };
  86526. /**
  86527. * Set the postion of the bone in local or world space
  86528. * @param position The position to set the bone
  86529. * @param space The space that the position is in
  86530. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86531. */
  86532. Bone.prototype.setPosition = function (position, space, mesh) {
  86533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86534. var lm = this.getLocalMatrix();
  86535. if (space == BABYLON.Space.LOCAL) {
  86536. lm.m[12] = position.x;
  86537. lm.m[13] = position.y;
  86538. lm.m[14] = position.z;
  86539. }
  86540. else {
  86541. var wm = null;
  86542. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86543. if (mesh) {
  86544. wm = mesh.getWorldMatrix();
  86545. }
  86546. this._skeleton.computeAbsoluteTransforms();
  86547. var tmat = Bone._tmpMats[0];
  86548. var vec = Bone._tmpVecs[0];
  86549. if (this._parent) {
  86550. if (mesh && wm) {
  86551. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86552. tmat.multiplyToRef(wm, tmat);
  86553. }
  86554. else {
  86555. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86556. }
  86557. }
  86558. tmat.invert();
  86559. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  86560. lm.m[12] = vec.x;
  86561. lm.m[13] = vec.y;
  86562. lm.m[14] = vec.z;
  86563. }
  86564. this._markAsDirtyAndDecompose();
  86565. };
  86566. /**
  86567. * Set the absolute position of the bone (world space)
  86568. * @param position The position to set the bone
  86569. * @param mesh The mesh that this bone is attached to
  86570. */
  86571. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  86572. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  86573. };
  86574. /**
  86575. * Scale the bone on the x, y and z axes (in local space)
  86576. * @param x The amount to scale the bone on the x axis
  86577. * @param y The amount to scale the bone on the y axis
  86578. * @param z The amount to scale the bone on the z axis
  86579. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  86580. */
  86581. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  86582. if (scaleChildren === void 0) { scaleChildren = false; }
  86583. var locMat = this.getLocalMatrix();
  86584. // Apply new scaling on top of current local matrix
  86585. var scaleMat = Bone._tmpMats[0];
  86586. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  86587. scaleMat.multiplyToRef(locMat, locMat);
  86588. // Invert scaling matrix and apply the inverse to all children
  86589. scaleMat.invert();
  86590. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  86591. var child = _a[_i];
  86592. var cm = child.getLocalMatrix();
  86593. cm.multiplyToRef(scaleMat, cm);
  86594. cm.m[12] *= x;
  86595. cm.m[13] *= y;
  86596. cm.m[14] *= z;
  86597. child._markAsDirtyAndDecompose();
  86598. }
  86599. this._markAsDirtyAndDecompose();
  86600. if (scaleChildren) {
  86601. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  86602. var child = _c[_b];
  86603. child.scale(x, y, z, scaleChildren);
  86604. }
  86605. }
  86606. };
  86607. /**
  86608. * Set the bone scaling in local space
  86609. * @param scale defines the scaling vector
  86610. */
  86611. Bone.prototype.setScale = function (scale) {
  86612. this._decompose();
  86613. this._localScaling.copyFrom(scale);
  86614. this._markAsDirtyAndCompose();
  86615. };
  86616. /**
  86617. * Gets the current scaling in local space
  86618. * @returns the current scaling vector
  86619. */
  86620. Bone.prototype.getScale = function () {
  86621. this._decompose();
  86622. return this._localScaling;
  86623. };
  86624. /**
  86625. * Gets the current scaling in local space and stores it in a target vector
  86626. * @param result defines the target vector
  86627. */
  86628. Bone.prototype.getScaleToRef = function (result) {
  86629. this._decompose();
  86630. result.copyFrom(this._localScaling);
  86631. };
  86632. /**
  86633. * Set the yaw, pitch, and roll of the bone in local or world space
  86634. * @param yaw The rotation of the bone on the y axis
  86635. * @param pitch The rotation of the bone on the x axis
  86636. * @param roll The rotation of the bone on the z axis
  86637. * @param space The space that the axes of rotation are in
  86638. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86639. */
  86640. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  86641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86642. if (space === BABYLON.Space.LOCAL) {
  86643. var quat = Bone._tmpQuat;
  86644. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  86645. this.setRotationQuaternion(quat, space, mesh);
  86646. return;
  86647. }
  86648. var rotMatInv = Bone._tmpMats[0];
  86649. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86650. return;
  86651. }
  86652. var rotMat = Bone._tmpMats[1];
  86653. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  86654. rotMatInv.multiplyToRef(rotMat, rotMat);
  86655. this._rotateWithMatrix(rotMat, space, mesh);
  86656. };
  86657. /**
  86658. * Add a rotation to the bone on an axis in local or world space
  86659. * @param axis The axis to rotate the bone on
  86660. * @param amount The amount to rotate the bone
  86661. * @param space The space that the axis is in
  86662. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86663. */
  86664. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  86665. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86666. var rmat = Bone._tmpMats[0];
  86667. rmat.m[12] = 0;
  86668. rmat.m[13] = 0;
  86669. rmat.m[14] = 0;
  86670. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  86671. this._rotateWithMatrix(rmat, space, mesh);
  86672. };
  86673. /**
  86674. * Set the rotation of the bone to a particular axis angle in local or world space
  86675. * @param axis The axis to rotate the bone on
  86676. * @param angle The angle that the bone should be rotated to
  86677. * @param space The space that the axis is in
  86678. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86679. */
  86680. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  86681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86682. if (space === BABYLON.Space.LOCAL) {
  86683. var quat = Bone._tmpQuat;
  86684. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  86685. this.setRotationQuaternion(quat, space, mesh);
  86686. return;
  86687. }
  86688. var rotMatInv = Bone._tmpMats[0];
  86689. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86690. return;
  86691. }
  86692. var rotMat = Bone._tmpMats[1];
  86693. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  86694. rotMatInv.multiplyToRef(rotMat, rotMat);
  86695. this._rotateWithMatrix(rotMat, space, mesh);
  86696. };
  86697. /**
  86698. * Set the euler rotation of the bone in local of world space
  86699. * @param rotation The euler rotation that the bone should be set to
  86700. * @param space The space that the rotation is in
  86701. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86702. */
  86703. Bone.prototype.setRotation = function (rotation, space, mesh) {
  86704. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86705. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  86706. };
  86707. /**
  86708. * Set the quaternion rotation of the bone in local of world space
  86709. * @param quat The quaternion rotation that the bone should be set to
  86710. * @param space The space that the rotation is in
  86711. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86712. */
  86713. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  86714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86715. if (space === BABYLON.Space.LOCAL) {
  86716. this._decompose();
  86717. this._localRotation.copyFrom(quat);
  86718. this._markAsDirtyAndCompose();
  86719. return;
  86720. }
  86721. var rotMatInv = Bone._tmpMats[0];
  86722. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86723. return;
  86724. }
  86725. var rotMat = Bone._tmpMats[1];
  86726. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  86727. rotMatInv.multiplyToRef(rotMat, rotMat);
  86728. this._rotateWithMatrix(rotMat, space, mesh);
  86729. };
  86730. /**
  86731. * Set the rotation matrix of the bone in local of world space
  86732. * @param rotMat The rotation matrix that the bone should be set to
  86733. * @param space The space that the rotation is in
  86734. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86735. */
  86736. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  86737. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86738. if (space === BABYLON.Space.LOCAL) {
  86739. var quat = Bone._tmpQuat;
  86740. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  86741. this.setRotationQuaternion(quat, space, mesh);
  86742. return;
  86743. }
  86744. var rotMatInv = Bone._tmpMats[0];
  86745. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86746. return;
  86747. }
  86748. var rotMat2 = Bone._tmpMats[1];
  86749. rotMat2.copyFrom(rotMat);
  86750. rotMatInv.multiplyToRef(rotMat, rotMat2);
  86751. this._rotateWithMatrix(rotMat2, space, mesh);
  86752. };
  86753. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  86754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86755. var lmat = this.getLocalMatrix();
  86756. var lx = lmat.m[12];
  86757. var ly = lmat.m[13];
  86758. var lz = lmat.m[14];
  86759. var parent = this.getParent();
  86760. var parentScale = Bone._tmpMats[3];
  86761. var parentScaleInv = Bone._tmpMats[4];
  86762. if (parent && space == BABYLON.Space.WORLD) {
  86763. if (mesh) {
  86764. parentScale.copyFrom(mesh.getWorldMatrix());
  86765. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  86766. }
  86767. else {
  86768. parentScale.copyFrom(parent.getAbsoluteTransform());
  86769. }
  86770. parentScaleInv.copyFrom(parentScale);
  86771. parentScaleInv.invert();
  86772. lmat.multiplyToRef(parentScale, lmat);
  86773. lmat.multiplyToRef(rmat, lmat);
  86774. lmat.multiplyToRef(parentScaleInv, lmat);
  86775. }
  86776. else {
  86777. if (space == BABYLON.Space.WORLD && mesh) {
  86778. parentScale.copyFrom(mesh.getWorldMatrix());
  86779. parentScaleInv.copyFrom(parentScale);
  86780. parentScaleInv.invert();
  86781. lmat.multiplyToRef(parentScale, lmat);
  86782. lmat.multiplyToRef(rmat, lmat);
  86783. lmat.multiplyToRef(parentScaleInv, lmat);
  86784. }
  86785. else {
  86786. lmat.multiplyToRef(rmat, lmat);
  86787. }
  86788. }
  86789. lmat.m[12] = lx;
  86790. lmat.m[13] = ly;
  86791. lmat.m[14] = lz;
  86792. this.computeAbsoluteTransforms();
  86793. this._markAsDirtyAndDecompose();
  86794. };
  86795. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  86796. var scaleMatrix = Bone._tmpMats[2];
  86797. rotMatInv.copyFrom(this.getAbsoluteTransform());
  86798. if (mesh) {
  86799. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  86800. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  86801. }
  86802. rotMatInv.invert();
  86803. if (isNaN(rotMatInv.m[0])) {
  86804. // Matrix failed to invert.
  86805. // This can happen if scale is zero for example.
  86806. return false;
  86807. }
  86808. scaleMatrix.m[0] *= this._scalingDeterminant;
  86809. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  86810. return true;
  86811. };
  86812. /**
  86813. * Get the position of the bone in local or world space
  86814. * @param space The space that the returned position is in
  86815. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86816. * @returns The position of the bone
  86817. */
  86818. Bone.prototype.getPosition = function (space, mesh) {
  86819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86820. if (mesh === void 0) { mesh = null; }
  86821. var pos = BABYLON.Vector3.Zero();
  86822. this.getPositionToRef(space, mesh, pos);
  86823. return pos;
  86824. };
  86825. /**
  86826. * Copy the position of the bone to a vector3 in local or world space
  86827. * @param space The space that the returned position is in
  86828. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86829. * @param result The vector3 to copy the position to
  86830. */
  86831. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  86832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86833. if (space == BABYLON.Space.LOCAL) {
  86834. var lm = this.getLocalMatrix();
  86835. result.x = lm.m[12];
  86836. result.y = lm.m[13];
  86837. result.z = lm.m[14];
  86838. }
  86839. else {
  86840. var wm = null;
  86841. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86842. if (mesh) {
  86843. wm = mesh.getWorldMatrix();
  86844. }
  86845. this._skeleton.computeAbsoluteTransforms();
  86846. var tmat = Bone._tmpMats[0];
  86847. if (mesh && wm) {
  86848. tmat.copyFrom(this.getAbsoluteTransform());
  86849. tmat.multiplyToRef(wm, tmat);
  86850. }
  86851. else {
  86852. tmat = this.getAbsoluteTransform();
  86853. }
  86854. result.x = tmat.m[12];
  86855. result.y = tmat.m[13];
  86856. result.z = tmat.m[14];
  86857. }
  86858. };
  86859. /**
  86860. * Get the absolute position of the bone (world space)
  86861. * @param mesh The mesh that this bone is attached to
  86862. * @returns The absolute position of the bone
  86863. */
  86864. Bone.prototype.getAbsolutePosition = function (mesh) {
  86865. if (mesh === void 0) { mesh = null; }
  86866. var pos = BABYLON.Vector3.Zero();
  86867. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  86868. return pos;
  86869. };
  86870. /**
  86871. * Copy the absolute position of the bone (world space) to the result param
  86872. * @param mesh The mesh that this bone is attached to
  86873. * @param result The vector3 to copy the absolute position to
  86874. */
  86875. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  86876. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  86877. };
  86878. /**
  86879. * Compute the absolute transforms of this bone and its children
  86880. */
  86881. Bone.prototype.computeAbsoluteTransforms = function () {
  86882. this._compose();
  86883. if (this._parent) {
  86884. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86885. }
  86886. else {
  86887. this._absoluteTransform.copyFrom(this._localMatrix);
  86888. var poseMatrix = this._skeleton.getPoseMatrix();
  86889. if (poseMatrix) {
  86890. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  86891. }
  86892. }
  86893. var children = this.children;
  86894. var len = children.length;
  86895. for (var i = 0; i < len; i++) {
  86896. children[i].computeAbsoluteTransforms();
  86897. }
  86898. };
  86899. /**
  86900. * Get the world direction from an axis that is in the local space of the bone
  86901. * @param localAxis The local direction that is used to compute the world direction
  86902. * @param mesh The mesh that this bone is attached to
  86903. * @returns The world direction
  86904. */
  86905. Bone.prototype.getDirection = function (localAxis, mesh) {
  86906. if (mesh === void 0) { mesh = null; }
  86907. var result = BABYLON.Vector3.Zero();
  86908. this.getDirectionToRef(localAxis, mesh, result);
  86909. return result;
  86910. };
  86911. /**
  86912. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  86913. * @param localAxis The local direction that is used to compute the world direction
  86914. * @param mesh The mesh that this bone is attached to
  86915. * @param result The vector3 that the world direction will be copied to
  86916. */
  86917. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  86918. if (mesh === void 0) { mesh = null; }
  86919. var wm = null;
  86920. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86921. if (mesh) {
  86922. wm = mesh.getWorldMatrix();
  86923. }
  86924. this._skeleton.computeAbsoluteTransforms();
  86925. var mat = Bone._tmpMats[0];
  86926. mat.copyFrom(this.getAbsoluteTransform());
  86927. if (mesh && wm) {
  86928. mat.multiplyToRef(wm, mat);
  86929. }
  86930. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  86931. result.normalize();
  86932. };
  86933. /**
  86934. * Get the euler rotation of the bone in local or world space
  86935. * @param space The space that the rotation should be in
  86936. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86937. * @returns The euler rotation
  86938. */
  86939. Bone.prototype.getRotation = function (space, mesh) {
  86940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86941. if (mesh === void 0) { mesh = null; }
  86942. var result = BABYLON.Vector3.Zero();
  86943. this.getRotationToRef(space, mesh, result);
  86944. return result;
  86945. };
  86946. /**
  86947. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  86948. * @param space The space that the rotation should be in
  86949. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86950. * @param result The vector3 that the rotation should be copied to
  86951. */
  86952. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  86953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86954. if (mesh === void 0) { mesh = null; }
  86955. var quat = Bone._tmpQuat;
  86956. this.getRotationQuaternionToRef(space, mesh, quat);
  86957. quat.toEulerAnglesToRef(result);
  86958. };
  86959. /**
  86960. * Get the quaternion rotation of the bone in either local or world space
  86961. * @param space The space that the rotation should be in
  86962. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86963. * @returns The quaternion rotation
  86964. */
  86965. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  86966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86967. if (mesh === void 0) { mesh = null; }
  86968. var result = BABYLON.Quaternion.Identity();
  86969. this.getRotationQuaternionToRef(space, mesh, result);
  86970. return result;
  86971. };
  86972. /**
  86973. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  86974. * @param space The space that the rotation should be in
  86975. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86976. * @param result The quaternion that the rotation should be copied to
  86977. */
  86978. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  86979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86980. if (mesh === void 0) { mesh = null; }
  86981. if (space == BABYLON.Space.LOCAL) {
  86982. this._decompose();
  86983. result.copyFrom(this._localRotation);
  86984. }
  86985. else {
  86986. var mat = Bone._tmpMats[0];
  86987. var amat = this.getAbsoluteTransform();
  86988. if (mesh) {
  86989. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  86990. }
  86991. else {
  86992. mat.copyFrom(amat);
  86993. }
  86994. mat.m[0] *= this._scalingDeterminant;
  86995. mat.m[1] *= this._scalingDeterminant;
  86996. mat.m[2] *= this._scalingDeterminant;
  86997. mat.decompose(undefined, result, undefined);
  86998. }
  86999. };
  87000. /**
  87001. * Get the rotation matrix of the bone in local or world space
  87002. * @param space The space that the rotation should be in
  87003. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87004. * @returns The rotation matrix
  87005. */
  87006. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87008. var result = BABYLON.Matrix.Identity();
  87009. this.getRotationMatrixToRef(space, mesh, result);
  87010. return result;
  87011. };
  87012. /**
  87013. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87014. * @param space The space that the rotation should be in
  87015. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87016. * @param result The quaternion that the rotation should be copied to
  87017. */
  87018. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87019. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87020. if (space == BABYLON.Space.LOCAL) {
  87021. this.getLocalMatrix().getRotationMatrixToRef(result);
  87022. }
  87023. else {
  87024. var mat = Bone._tmpMats[0];
  87025. var amat = this.getAbsoluteTransform();
  87026. if (mesh) {
  87027. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87028. }
  87029. else {
  87030. mat.copyFrom(amat);
  87031. }
  87032. mat.m[0] *= this._scalingDeterminant;
  87033. mat.m[1] *= this._scalingDeterminant;
  87034. mat.m[2] *= this._scalingDeterminant;
  87035. mat.getRotationMatrixToRef(result);
  87036. }
  87037. };
  87038. /**
  87039. * Get the world position of a point that is in the local space of the bone
  87040. * @param position The local position
  87041. * @param mesh The mesh that this bone is attached to
  87042. * @returns The world position
  87043. */
  87044. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87045. if (mesh === void 0) { mesh = null; }
  87046. var result = BABYLON.Vector3.Zero();
  87047. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87048. return result;
  87049. };
  87050. /**
  87051. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87052. * @param position The local position
  87053. * @param mesh The mesh that this bone is attached to
  87054. * @param result The vector3 that the world position should be copied to
  87055. */
  87056. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87057. if (mesh === void 0) { mesh = null; }
  87058. var wm = null;
  87059. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87060. if (mesh) {
  87061. wm = mesh.getWorldMatrix();
  87062. }
  87063. this._skeleton.computeAbsoluteTransforms();
  87064. var tmat = Bone._tmpMats[0];
  87065. if (mesh && wm) {
  87066. tmat.copyFrom(this.getAbsoluteTransform());
  87067. tmat.multiplyToRef(wm, tmat);
  87068. }
  87069. else {
  87070. tmat = this.getAbsoluteTransform();
  87071. }
  87072. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87073. };
  87074. /**
  87075. * Get the local position of a point that is in world space
  87076. * @param position The world position
  87077. * @param mesh The mesh that this bone is attached to
  87078. * @returns The local position
  87079. */
  87080. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87081. if (mesh === void 0) { mesh = null; }
  87082. var result = BABYLON.Vector3.Zero();
  87083. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87084. return result;
  87085. };
  87086. /**
  87087. * Get the local position of a point that is in world space and copy it to the result param
  87088. * @param position The world position
  87089. * @param mesh The mesh that this bone is attached to
  87090. * @param result The vector3 that the local position should be copied to
  87091. */
  87092. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87093. if (mesh === void 0) { mesh = null; }
  87094. var wm = null;
  87095. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87096. if (mesh) {
  87097. wm = mesh.getWorldMatrix();
  87098. }
  87099. this._skeleton.computeAbsoluteTransforms();
  87100. var tmat = Bone._tmpMats[0];
  87101. tmat.copyFrom(this.getAbsoluteTransform());
  87102. if (mesh && wm) {
  87103. tmat.multiplyToRef(wm, tmat);
  87104. }
  87105. tmat.invert();
  87106. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87107. };
  87108. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87109. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87110. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87111. return Bone;
  87112. }(BABYLON.Node));
  87113. BABYLON.Bone = Bone;
  87114. })(BABYLON || (BABYLON = {}));
  87115. //# sourceMappingURL=babylon.bone.js.map
  87116. var BABYLON;
  87117. (function (BABYLON) {
  87118. /**
  87119. * Class used to apply inverse kinematics to bones
  87120. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87121. */
  87122. var BoneIKController = /** @class */ (function () {
  87123. /**
  87124. * Creates a new BoneIKController
  87125. * @param mesh defines the mesh to control
  87126. * @param bone defines the bone to control
  87127. * @param options defines options to set up the controller
  87128. */
  87129. function BoneIKController(mesh, bone, options) {
  87130. /**
  87131. * Gets or sets the target position
  87132. */
  87133. this.targetPosition = BABYLON.Vector3.Zero();
  87134. /**
  87135. * Gets or sets the pole target position
  87136. */
  87137. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87138. /**
  87139. * Gets or sets the pole target local offset
  87140. */
  87141. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87142. /**
  87143. * Gets or sets the pole angle
  87144. */
  87145. this.poleAngle = 0;
  87146. /**
  87147. * 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)
  87148. */
  87149. this.slerpAmount = 1;
  87150. this._bone1Quat = BABYLON.Quaternion.Identity();
  87151. this._bone1Mat = BABYLON.Matrix.Identity();
  87152. this._bone2Ang = Math.PI;
  87153. this._maxAngle = Math.PI;
  87154. this._rightHandedSystem = false;
  87155. this._bendAxis = BABYLON.Vector3.Right();
  87156. this._slerping = false;
  87157. this._adjustRoll = 0;
  87158. this._bone2 = bone;
  87159. this._bone1 = bone.getParent();
  87160. if (!this._bone1) {
  87161. return;
  87162. }
  87163. this.mesh = mesh;
  87164. var bonePos = bone.getPosition();
  87165. if (bone.getAbsoluteTransform().determinant() > 0) {
  87166. this._rightHandedSystem = true;
  87167. this._bendAxis.x = 0;
  87168. this._bendAxis.y = 0;
  87169. this._bendAxis.z = -1;
  87170. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87171. this._adjustRoll = Math.PI * .5;
  87172. this._bendAxis.z = 1;
  87173. }
  87174. }
  87175. if (this._bone1.length) {
  87176. var boneScale1 = this._bone1.getScale();
  87177. var boneScale2 = this._bone2.getScale();
  87178. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87179. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87180. }
  87181. else if (this._bone1.children[0]) {
  87182. mesh.computeWorldMatrix(true);
  87183. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87184. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87185. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87186. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87187. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87188. }
  87189. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87190. this.maxAngle = Math.PI;
  87191. if (options) {
  87192. if (options.targetMesh) {
  87193. this.targetMesh = options.targetMesh;
  87194. this.targetMesh.computeWorldMatrix(true);
  87195. }
  87196. if (options.poleTargetMesh) {
  87197. this.poleTargetMesh = options.poleTargetMesh;
  87198. this.poleTargetMesh.computeWorldMatrix(true);
  87199. }
  87200. else if (options.poleTargetBone) {
  87201. this.poleTargetBone = options.poleTargetBone;
  87202. }
  87203. else if (this._bone1.getParent()) {
  87204. this.poleTargetBone = this._bone1.getParent();
  87205. }
  87206. if (options.poleTargetLocalOffset) {
  87207. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87208. }
  87209. if (options.poleAngle) {
  87210. this.poleAngle = options.poleAngle;
  87211. }
  87212. if (options.bendAxis) {
  87213. this._bendAxis.copyFrom(options.bendAxis);
  87214. }
  87215. if (options.maxAngle) {
  87216. this.maxAngle = options.maxAngle;
  87217. }
  87218. if (options.slerpAmount) {
  87219. this.slerpAmount = options.slerpAmount;
  87220. }
  87221. }
  87222. }
  87223. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87224. /**
  87225. * Gets or sets maximum allowed angle
  87226. */
  87227. get: function () {
  87228. return this._maxAngle;
  87229. },
  87230. set: function (value) {
  87231. this._setMaxAngle(value);
  87232. },
  87233. enumerable: true,
  87234. configurable: true
  87235. });
  87236. BoneIKController.prototype._setMaxAngle = function (ang) {
  87237. if (ang < 0) {
  87238. ang = 0;
  87239. }
  87240. if (ang > Math.PI || ang == undefined) {
  87241. ang = Math.PI;
  87242. }
  87243. this._maxAngle = ang;
  87244. var a = this._bone1Length;
  87245. var b = this._bone2Length;
  87246. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87247. };
  87248. /**
  87249. * Force the controller to update the bones
  87250. */
  87251. BoneIKController.prototype.update = function () {
  87252. var bone1 = this._bone1;
  87253. if (!bone1) {
  87254. return;
  87255. }
  87256. var target = this.targetPosition;
  87257. var poleTarget = this.poleTargetPosition;
  87258. var mat1 = BoneIKController._tmpMats[0];
  87259. var mat2 = BoneIKController._tmpMats[1];
  87260. if (this.targetMesh) {
  87261. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87262. }
  87263. if (this.poleTargetBone) {
  87264. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87265. }
  87266. else if (this.poleTargetMesh) {
  87267. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87268. }
  87269. var bonePos = BoneIKController._tmpVecs[0];
  87270. var zaxis = BoneIKController._tmpVecs[1];
  87271. var xaxis = BoneIKController._tmpVecs[2];
  87272. var yaxis = BoneIKController._tmpVecs[3];
  87273. var upAxis = BoneIKController._tmpVecs[4];
  87274. var _tmpQuat = BoneIKController._tmpQuat;
  87275. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87276. poleTarget.subtractToRef(bonePos, upAxis);
  87277. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87278. upAxis.y = 1;
  87279. }
  87280. else {
  87281. upAxis.normalize();
  87282. }
  87283. target.subtractToRef(bonePos, yaxis);
  87284. yaxis.normalize();
  87285. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87286. zaxis.normalize();
  87287. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  87288. xaxis.normalize();
  87289. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  87290. var a = this._bone1Length;
  87291. var b = this._bone2Length;
  87292. var c = BABYLON.Vector3.Distance(bonePos, target);
  87293. if (this._maxReach > 0) {
  87294. c = Math.min(this._maxReach, c);
  87295. }
  87296. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  87297. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  87298. if (acosa > 1) {
  87299. acosa = 1;
  87300. }
  87301. if (acosb > 1) {
  87302. acosb = 1;
  87303. }
  87304. if (acosa < -1) {
  87305. acosa = -1;
  87306. }
  87307. if (acosb < -1) {
  87308. acosb = -1;
  87309. }
  87310. var angA = Math.acos(acosa);
  87311. var angB = Math.acos(acosb);
  87312. var angC = -angA - angB;
  87313. if (this._rightHandedSystem) {
  87314. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  87315. mat2.multiplyToRef(mat1, mat1);
  87316. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  87317. mat2.multiplyToRef(mat1, mat1);
  87318. }
  87319. else {
  87320. var _tmpVec = BoneIKController._tmpVecs[5];
  87321. _tmpVec.copyFrom(this._bendAxis);
  87322. _tmpVec.x *= -1;
  87323. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  87324. mat2.multiplyToRef(mat1, mat1);
  87325. }
  87326. if (this.poleAngle) {
  87327. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  87328. mat1.multiplyToRef(mat2, mat1);
  87329. }
  87330. if (this._bone1) {
  87331. if (this.slerpAmount < 1) {
  87332. if (!this._slerping) {
  87333. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  87334. }
  87335. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  87336. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  87337. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  87338. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  87339. this._slerping = true;
  87340. }
  87341. else {
  87342. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  87343. this._bone1Mat.copyFrom(mat1);
  87344. this._slerping = false;
  87345. }
  87346. }
  87347. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  87348. this._bone2Ang = angC;
  87349. };
  87350. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87351. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  87352. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87353. return BoneIKController;
  87354. }());
  87355. BABYLON.BoneIKController = BoneIKController;
  87356. })(BABYLON || (BABYLON = {}));
  87357. //# sourceMappingURL=babylon.boneIKController.js.map
  87358. var BABYLON;
  87359. (function (BABYLON) {
  87360. /**
  87361. * Class used to make a bone look toward a point in space
  87362. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  87363. */
  87364. var BoneLookController = /** @class */ (function () {
  87365. /**
  87366. * Create a BoneLookController
  87367. * @param mesh the mesh that the bone belongs to
  87368. * @param bone the bone that will be looking to the target
  87369. * @param target the target Vector3 to look at
  87370. * @param settings optional settings:
  87371. * * maxYaw: the maximum angle the bone will yaw to
  87372. * * minYaw: the minimum angle the bone will yaw to
  87373. * * maxPitch: the maximum angle the bone will pitch to
  87374. * * minPitch: the minimum angle the bone will yaw to
  87375. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  87376. * * upAxis: the up axis of the coordinate system
  87377. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  87378. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  87379. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  87380. * * adjustYaw: used to make an adjustment to the yaw of the bone
  87381. * * adjustPitch: used to make an adjustment to the pitch of the bone
  87382. * * adjustRoll: used to make an adjustment to the roll of the bone
  87383. **/
  87384. function BoneLookController(mesh, bone, target, options) {
  87385. /**
  87386. * The up axis of the coordinate system that is used when the bone is rotated
  87387. */
  87388. this.upAxis = BABYLON.Vector3.Up();
  87389. /**
  87390. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  87391. */
  87392. this.upAxisSpace = BABYLON.Space.LOCAL;
  87393. /**
  87394. * Used to make an adjustment to the yaw of the bone
  87395. */
  87396. this.adjustYaw = 0;
  87397. /**
  87398. * Used to make an adjustment to the pitch of the bone
  87399. */
  87400. this.adjustPitch = 0;
  87401. /**
  87402. * Used to make an adjustment to the roll of the bone
  87403. */
  87404. this.adjustRoll = 0;
  87405. /**
  87406. * 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)
  87407. */
  87408. this.slerpAmount = 1;
  87409. this._boneQuat = BABYLON.Quaternion.Identity();
  87410. this._slerping = false;
  87411. this._firstFrameSkipped = false;
  87412. this._fowardAxis = BABYLON.Vector3.Forward();
  87413. this.mesh = mesh;
  87414. this.bone = bone;
  87415. this.target = target;
  87416. if (options) {
  87417. if (options.adjustYaw) {
  87418. this.adjustYaw = options.adjustYaw;
  87419. }
  87420. if (options.adjustPitch) {
  87421. this.adjustPitch = options.adjustPitch;
  87422. }
  87423. if (options.adjustRoll) {
  87424. this.adjustRoll = options.adjustRoll;
  87425. }
  87426. if (options.maxYaw != null) {
  87427. this.maxYaw = options.maxYaw;
  87428. }
  87429. else {
  87430. this.maxYaw = Math.PI;
  87431. }
  87432. if (options.minYaw != null) {
  87433. this.minYaw = options.minYaw;
  87434. }
  87435. else {
  87436. this.minYaw = -Math.PI;
  87437. }
  87438. if (options.maxPitch != null) {
  87439. this.maxPitch = options.maxPitch;
  87440. }
  87441. else {
  87442. this.maxPitch = Math.PI;
  87443. }
  87444. if (options.minPitch != null) {
  87445. this.minPitch = options.minPitch;
  87446. }
  87447. else {
  87448. this.minPitch = -Math.PI;
  87449. }
  87450. if (options.slerpAmount != null) {
  87451. this.slerpAmount = options.slerpAmount;
  87452. }
  87453. if (options.upAxis != null) {
  87454. this.upAxis = options.upAxis;
  87455. }
  87456. if (options.upAxisSpace != null) {
  87457. this.upAxisSpace = options.upAxisSpace;
  87458. }
  87459. if (options.yawAxis != null || options.pitchAxis != null) {
  87460. var newYawAxis = BABYLON.Axis.Y;
  87461. var newPitchAxis = BABYLON.Axis.X;
  87462. if (options.yawAxis != null) {
  87463. newYawAxis = options.yawAxis.clone();
  87464. newYawAxis.normalize();
  87465. }
  87466. if (options.pitchAxis != null) {
  87467. newPitchAxis = options.pitchAxis.clone();
  87468. newPitchAxis.normalize();
  87469. }
  87470. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  87471. this._transformYawPitch = BABYLON.Matrix.Identity();
  87472. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  87473. this._transformYawPitchInv = this._transformYawPitch.clone();
  87474. this._transformYawPitch.invert();
  87475. }
  87476. }
  87477. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  87478. this.upAxisSpace = BABYLON.Space.LOCAL;
  87479. }
  87480. }
  87481. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  87482. /**
  87483. * Gets or sets the minimum yaw angle that the bone can look to
  87484. */
  87485. get: function () {
  87486. return this._minYaw;
  87487. },
  87488. set: function (value) {
  87489. this._minYaw = value;
  87490. this._minYawSin = Math.sin(value);
  87491. this._minYawCos = Math.cos(value);
  87492. if (this._maxYaw != null) {
  87493. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87494. this._yawRange = this._maxYaw - this._minYaw;
  87495. }
  87496. },
  87497. enumerable: true,
  87498. configurable: true
  87499. });
  87500. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  87501. /**
  87502. * Gets or sets the maximum yaw angle that the bone can look to
  87503. */
  87504. get: function () {
  87505. return this._maxYaw;
  87506. },
  87507. set: function (value) {
  87508. this._maxYaw = value;
  87509. this._maxYawSin = Math.sin(value);
  87510. this._maxYawCos = Math.cos(value);
  87511. if (this._minYaw != null) {
  87512. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87513. this._yawRange = this._maxYaw - this._minYaw;
  87514. }
  87515. },
  87516. enumerable: true,
  87517. configurable: true
  87518. });
  87519. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  87520. /**
  87521. * Gets or sets the minimum pitch angle that the bone can look to
  87522. */
  87523. get: function () {
  87524. return this._minPitch;
  87525. },
  87526. set: function (value) {
  87527. this._minPitch = value;
  87528. this._minPitchTan = Math.tan(value);
  87529. },
  87530. enumerable: true,
  87531. configurable: true
  87532. });
  87533. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  87534. /**
  87535. * Gets or sets the maximum pitch angle that the bone can look to
  87536. */
  87537. get: function () {
  87538. return this._maxPitch;
  87539. },
  87540. set: function (value) {
  87541. this._maxPitch = value;
  87542. this._maxPitchTan = Math.tan(value);
  87543. },
  87544. enumerable: true,
  87545. configurable: true
  87546. });
  87547. /**
  87548. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  87549. */
  87550. BoneLookController.prototype.update = function () {
  87551. //skip the first frame when slerping so that the mesh rotation is correct
  87552. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  87553. this._firstFrameSkipped = true;
  87554. return;
  87555. }
  87556. var bone = this.bone;
  87557. var bonePos = BoneLookController._tmpVecs[0];
  87558. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  87559. var target = this.target;
  87560. var _tmpMat1 = BoneLookController._tmpMats[0];
  87561. var _tmpMat2 = BoneLookController._tmpMats[1];
  87562. var mesh = this.mesh;
  87563. var parentBone = bone.getParent();
  87564. var upAxis = BoneLookController._tmpVecs[1];
  87565. upAxis.copyFrom(this.upAxis);
  87566. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  87567. if (this._transformYawPitch) {
  87568. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  87569. }
  87570. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  87571. }
  87572. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  87573. mesh.getDirectionToRef(upAxis, upAxis);
  87574. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  87575. upAxis.normalize();
  87576. }
  87577. }
  87578. var checkYaw = false;
  87579. var checkPitch = false;
  87580. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  87581. checkYaw = true;
  87582. }
  87583. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  87584. checkPitch = true;
  87585. }
  87586. if (checkYaw || checkPitch) {
  87587. var spaceMat = BoneLookController._tmpMats[2];
  87588. var spaceMatInv = BoneLookController._tmpMats[3];
  87589. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  87590. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  87591. }
  87592. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  87593. spaceMat.copyFrom(mesh.getWorldMatrix());
  87594. }
  87595. else {
  87596. var forwardAxis = BoneLookController._tmpVecs[2];
  87597. forwardAxis.copyFrom(this._fowardAxis);
  87598. if (this._transformYawPitch) {
  87599. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  87600. }
  87601. if (parentBone) {
  87602. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  87603. }
  87604. else {
  87605. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  87606. }
  87607. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  87608. rightAxis.normalize();
  87609. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  87610. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  87611. }
  87612. spaceMat.invertToRef(spaceMatInv);
  87613. var xzlen = null;
  87614. if (checkPitch) {
  87615. var localTarget = BoneLookController._tmpVecs[3];
  87616. target.subtractToRef(bonePos, localTarget);
  87617. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87618. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87619. var pitch = Math.atan2(localTarget.y, xzlen);
  87620. var newPitch = pitch;
  87621. if (pitch > this._maxPitch) {
  87622. localTarget.y = this._maxPitchTan * xzlen;
  87623. newPitch = this._maxPitch;
  87624. }
  87625. else if (pitch < this._minPitch) {
  87626. localTarget.y = this._minPitchTan * xzlen;
  87627. newPitch = this._minPitch;
  87628. }
  87629. if (pitch != newPitch) {
  87630. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87631. localTarget.addInPlace(bonePos);
  87632. target = localTarget;
  87633. }
  87634. }
  87635. if (checkYaw) {
  87636. var localTarget = BoneLookController._tmpVecs[4];
  87637. target.subtractToRef(bonePos, localTarget);
  87638. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87639. var yaw = Math.atan2(localTarget.x, localTarget.z);
  87640. var newYaw = yaw;
  87641. if (yaw > this._maxYaw || yaw < this._minYaw) {
  87642. if (xzlen == null) {
  87643. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87644. }
  87645. if (this._yawRange > Math.PI) {
  87646. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  87647. localTarget.z = this._maxYawCos * xzlen;
  87648. localTarget.x = this._maxYawSin * xzlen;
  87649. newYaw = this._maxYaw;
  87650. }
  87651. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  87652. localTarget.z = this._minYawCos * xzlen;
  87653. localTarget.x = this._minYawSin * xzlen;
  87654. newYaw = this._minYaw;
  87655. }
  87656. }
  87657. else {
  87658. if (yaw > this._maxYaw) {
  87659. localTarget.z = this._maxYawCos * xzlen;
  87660. localTarget.x = this._maxYawSin * xzlen;
  87661. newYaw = this._maxYaw;
  87662. }
  87663. else if (yaw < this._minYaw) {
  87664. localTarget.z = this._minYawCos * xzlen;
  87665. localTarget.x = this._minYawSin * xzlen;
  87666. newYaw = this._minYaw;
  87667. }
  87668. }
  87669. }
  87670. if (this._slerping && this._yawRange > Math.PI) {
  87671. //are we going to be crossing into the min/max region?
  87672. var boneFwd = BoneLookController._tmpVecs[8];
  87673. boneFwd.copyFrom(BABYLON.Axis.Z);
  87674. if (this._transformYawPitch) {
  87675. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  87676. }
  87677. var boneRotMat = BoneLookController._tmpMats[4];
  87678. this._boneQuat.toRotationMatrix(boneRotMat);
  87679. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  87680. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  87681. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  87682. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  87683. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  87684. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  87685. if (angBtwTar > angBtwMidYaw) {
  87686. if (xzlen == null) {
  87687. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87688. }
  87689. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  87690. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  87691. if (angBtwMin < angBtwMax) {
  87692. newYaw = boneYaw + Math.PI * .75;
  87693. localTarget.z = Math.cos(newYaw) * xzlen;
  87694. localTarget.x = Math.sin(newYaw) * xzlen;
  87695. }
  87696. else {
  87697. newYaw = boneYaw - Math.PI * .75;
  87698. localTarget.z = Math.cos(newYaw) * xzlen;
  87699. localTarget.x = Math.sin(newYaw) * xzlen;
  87700. }
  87701. }
  87702. }
  87703. if (yaw != newYaw) {
  87704. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87705. localTarget.addInPlace(bonePos);
  87706. target = localTarget;
  87707. }
  87708. }
  87709. }
  87710. var zaxis = BoneLookController._tmpVecs[5];
  87711. var xaxis = BoneLookController._tmpVecs[6];
  87712. var yaxis = BoneLookController._tmpVecs[7];
  87713. var _tmpQuat = BoneLookController._tmpQuat;
  87714. target.subtractToRef(bonePos, zaxis);
  87715. zaxis.normalize();
  87716. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  87717. xaxis.normalize();
  87718. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  87719. yaxis.normalize();
  87720. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  87721. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  87722. return;
  87723. }
  87724. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  87725. return;
  87726. }
  87727. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  87728. return;
  87729. }
  87730. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  87731. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  87732. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  87733. }
  87734. if (this.slerpAmount < 1) {
  87735. if (!this._slerping) {
  87736. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  87737. }
  87738. if (this._transformYawPitch) {
  87739. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87740. }
  87741. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  87742. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  87743. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  87744. this._slerping = true;
  87745. }
  87746. else {
  87747. if (this._transformYawPitch) {
  87748. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87749. }
  87750. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  87751. this._slerping = false;
  87752. }
  87753. };
  87754. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  87755. var angDiff = ang2 - ang1;
  87756. angDiff %= Math.PI * 2;
  87757. if (angDiff > Math.PI) {
  87758. angDiff -= Math.PI * 2;
  87759. }
  87760. else if (angDiff < -Math.PI) {
  87761. angDiff += Math.PI * 2;
  87762. }
  87763. return angDiff;
  87764. };
  87765. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  87766. ang1 %= (2 * Math.PI);
  87767. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87768. ang2 %= (2 * Math.PI);
  87769. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87770. var ab = 0;
  87771. if (ang1 < ang2) {
  87772. ab = ang2 - ang1;
  87773. }
  87774. else {
  87775. ab = ang1 - ang2;
  87776. }
  87777. if (ab > Math.PI) {
  87778. ab = Math.PI * 2 - ab;
  87779. }
  87780. return ab;
  87781. };
  87782. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  87783. ang %= (2 * Math.PI);
  87784. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  87785. ang1 %= (2 * Math.PI);
  87786. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87787. ang2 %= (2 * Math.PI);
  87788. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87789. if (ang1 < ang2) {
  87790. if (ang > ang1 && ang < ang2) {
  87791. return true;
  87792. }
  87793. }
  87794. else {
  87795. if (ang > ang2 && ang < ang1) {
  87796. return true;
  87797. }
  87798. }
  87799. return false;
  87800. };
  87801. 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()];
  87802. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  87803. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87804. return BoneLookController;
  87805. }());
  87806. BABYLON.BoneLookController = BoneLookController;
  87807. })(BABYLON || (BABYLON = {}));
  87808. //# sourceMappingURL=babylon.boneLookController.js.map
  87809. var BABYLON;
  87810. (function (BABYLON) {
  87811. /**
  87812. * Class used to handle skinning animations
  87813. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87814. */
  87815. var Skeleton = /** @class */ (function () {
  87816. /**
  87817. * Creates a new skeleton
  87818. * @param name defines the skeleton name
  87819. * @param id defines the skeleton Id
  87820. * @param scene defines the hosting scene
  87821. */
  87822. function Skeleton(
  87823. /** defines the skeleton name */
  87824. name,
  87825. /** defines the skeleton Id */
  87826. id, scene) {
  87827. this.name = name;
  87828. this.id = id;
  87829. /**
  87830. * Gets the list of child bones
  87831. */
  87832. this.bones = new Array();
  87833. /**
  87834. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  87835. */
  87836. this.needInitialSkinMatrix = false;
  87837. this._isDirty = true;
  87838. this._meshesWithPoseMatrix = new Array();
  87839. this._identity = BABYLON.Matrix.Identity();
  87840. this._ranges = {};
  87841. this._lastAbsoluteTransformsUpdateId = -1;
  87842. /**
  87843. * Specifies if the skeleton should be serialized
  87844. */
  87845. this.doNotSerialize = false;
  87846. this._animationPropertiesOverride = null;
  87847. // Events
  87848. /**
  87849. * An observable triggered before computing the skeleton's matrices
  87850. */
  87851. this.onBeforeComputeObservable = new BABYLON.Observable();
  87852. this.bones = [];
  87853. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87854. scene.skeletons.push(this);
  87855. //make sure it will recalculate the matrix next time prepare is called.
  87856. this._isDirty = true;
  87857. }
  87858. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  87859. /**
  87860. * Gets or sets the animation properties override
  87861. */
  87862. get: function () {
  87863. if (!this._animationPropertiesOverride) {
  87864. return this._scene.animationPropertiesOverride;
  87865. }
  87866. return this._animationPropertiesOverride;
  87867. },
  87868. set: function (value) {
  87869. this._animationPropertiesOverride = value;
  87870. },
  87871. enumerable: true,
  87872. configurable: true
  87873. });
  87874. // Members
  87875. /**
  87876. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  87877. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  87878. * @returns a Float32Array containing matrices data
  87879. */
  87880. Skeleton.prototype.getTransformMatrices = function (mesh) {
  87881. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  87882. return mesh._bonesTransformMatrices;
  87883. }
  87884. if (!this._transformMatrices) {
  87885. this.prepare();
  87886. }
  87887. return this._transformMatrices;
  87888. };
  87889. /**
  87890. * Gets the current hosting scene
  87891. * @returns a scene object
  87892. */
  87893. Skeleton.prototype.getScene = function () {
  87894. return this._scene;
  87895. };
  87896. // Methods
  87897. /**
  87898. * Gets a string representing the current skeleton data
  87899. * @param fullDetails defines a boolean indicating if we want a verbose version
  87900. * @returns a string representing the current skeleton data
  87901. */
  87902. Skeleton.prototype.toString = function (fullDetails) {
  87903. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  87904. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  87905. if (fullDetails) {
  87906. ret += ", Ranges: {";
  87907. var first = true;
  87908. for (var name_1 in this._ranges) {
  87909. if (first) {
  87910. ret += ", ";
  87911. first = false;
  87912. }
  87913. ret += name_1;
  87914. }
  87915. ret += "}";
  87916. }
  87917. return ret;
  87918. };
  87919. /**
  87920. * Get bone's index searching by name
  87921. * @param name defines bone's name to search for
  87922. * @return the indice of the bone. Returns -1 if not found
  87923. */
  87924. Skeleton.prototype.getBoneIndexByName = function (name) {
  87925. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  87926. if (this.bones[boneIndex].name === name) {
  87927. return boneIndex;
  87928. }
  87929. }
  87930. return -1;
  87931. };
  87932. /**
  87933. * Creater a new animation range
  87934. * @param name defines the name of the range
  87935. * @param from defines the start key
  87936. * @param to defines the end key
  87937. */
  87938. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  87939. // check name not already in use
  87940. if (!this._ranges[name]) {
  87941. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  87942. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87943. if (this.bones[i].animations[0]) {
  87944. this.bones[i].animations[0].createRange(name, from, to);
  87945. }
  87946. }
  87947. }
  87948. };
  87949. /**
  87950. * Delete a specific animation range
  87951. * @param name defines the name of the range
  87952. * @param deleteFrames defines if frames must be removed as well
  87953. */
  87954. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  87955. if (deleteFrames === void 0) { deleteFrames = true; }
  87956. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87957. if (this.bones[i].animations[0]) {
  87958. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  87959. }
  87960. }
  87961. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  87962. };
  87963. /**
  87964. * Gets a specific animation range
  87965. * @param name defines the name of the range to look for
  87966. * @returns the requested animation range or null if not found
  87967. */
  87968. Skeleton.prototype.getAnimationRange = function (name) {
  87969. return this._ranges[name];
  87970. };
  87971. /**
  87972. * Gets the list of all animation ranges defined on this skeleton
  87973. * @returns an array
  87974. */
  87975. Skeleton.prototype.getAnimationRanges = function () {
  87976. var animationRanges = [];
  87977. var name;
  87978. var i = 0;
  87979. for (name in this._ranges) {
  87980. animationRanges[i] = this._ranges[name];
  87981. i++;
  87982. }
  87983. return animationRanges;
  87984. };
  87985. /**
  87986. * Copy animation range from a source skeleton.
  87987. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  87988. * @param source defines the source skeleton
  87989. * @param name defines the name of the range to copy
  87990. * @param rescaleAsRequired defines if rescaling must be applied if required
  87991. * @returns true if operation was successful
  87992. */
  87993. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  87994. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87995. if (this._ranges[name] || !source.getAnimationRange(name)) {
  87996. return false;
  87997. }
  87998. var ret = true;
  87999. var frameOffset = this._getHighestAnimationFrame() + 1;
  88000. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88001. var boneDict = {};
  88002. var sourceBones = source.bones;
  88003. var nBones;
  88004. var i;
  88005. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88006. boneDict[sourceBones[i].name] = sourceBones[i];
  88007. }
  88008. if (this.bones.length !== sourceBones.length) {
  88009. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88010. ret = false;
  88011. }
  88012. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88013. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88014. var boneName = this.bones[i].name;
  88015. var sourceBone = boneDict[boneName];
  88016. if (sourceBone) {
  88017. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88018. }
  88019. else {
  88020. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88021. ret = false;
  88022. }
  88023. }
  88024. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88025. var range = source.getAnimationRange(name);
  88026. if (range) {
  88027. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88028. }
  88029. return ret;
  88030. };
  88031. /**
  88032. * Forces the skeleton to go to rest pose
  88033. */
  88034. Skeleton.prototype.returnToRest = function () {
  88035. for (var index = 0; index < this.bones.length; index++) {
  88036. this.bones[index].returnToRest();
  88037. }
  88038. };
  88039. Skeleton.prototype._getHighestAnimationFrame = function () {
  88040. var ret = 0;
  88041. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88042. if (this.bones[i].animations[0]) {
  88043. var highest = this.bones[i].animations[0].getHighestFrame();
  88044. if (ret < highest) {
  88045. ret = highest;
  88046. }
  88047. }
  88048. }
  88049. return ret;
  88050. };
  88051. /**
  88052. * Begin a specific animation range
  88053. * @param name defines the name of the range to start
  88054. * @param loop defines if looping must be turned on (false by default)
  88055. * @param speedRatio defines the speed ratio to apply (1 by default)
  88056. * @param onAnimationEnd defines a callback which will be called when animation will end
  88057. * @returns a new animatable
  88058. */
  88059. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88060. var range = this.getAnimationRange(name);
  88061. if (!range) {
  88062. return null;
  88063. }
  88064. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88065. };
  88066. /** @hidden */
  88067. Skeleton.prototype._markAsDirty = function () {
  88068. this._isDirty = true;
  88069. };
  88070. /** @hidden */
  88071. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88072. this._meshesWithPoseMatrix.push(mesh);
  88073. };
  88074. /** @hidden */
  88075. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88076. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88077. if (index > -1) {
  88078. this._meshesWithPoseMatrix.splice(index, 1);
  88079. }
  88080. };
  88081. /** @hidden */
  88082. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88083. this.onBeforeComputeObservable.notifyObservers(this);
  88084. for (var index = 0; index < this.bones.length; index++) {
  88085. var bone = this.bones[index];
  88086. var parentBone = bone.getParent();
  88087. if (parentBone) {
  88088. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88089. }
  88090. else {
  88091. if (initialSkinMatrix) {
  88092. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88093. }
  88094. else {
  88095. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88096. }
  88097. }
  88098. if (bone._index !== -1) {
  88099. var mappedIndex = bone._index === null ? index : bone._index;
  88100. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88101. }
  88102. }
  88103. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88104. };
  88105. /**
  88106. * Build all resources required to render a skeleton
  88107. */
  88108. Skeleton.prototype.prepare = function () {
  88109. if (!this._isDirty) {
  88110. return;
  88111. }
  88112. if (this.needInitialSkinMatrix) {
  88113. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88114. var mesh = this._meshesWithPoseMatrix[index];
  88115. var poseMatrix = mesh.getPoseMatrix();
  88116. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88117. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88118. }
  88119. if (this._synchronizedWithMesh !== mesh) {
  88120. this._synchronizedWithMesh = mesh;
  88121. // Prepare bones
  88122. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88123. var bone = this.bones[boneIndex];
  88124. if (!bone.getParent()) {
  88125. var matrix = bone.getBaseMatrix();
  88126. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88127. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88128. }
  88129. }
  88130. }
  88131. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88132. }
  88133. }
  88134. else {
  88135. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88136. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88137. }
  88138. this._computeTransformMatrices(this._transformMatrices, null);
  88139. }
  88140. this._isDirty = false;
  88141. this._scene._activeBones.addCount(this.bones.length, false);
  88142. };
  88143. /**
  88144. * Gets the list of animatables currently running for this skeleton
  88145. * @returns an array of animatables
  88146. */
  88147. Skeleton.prototype.getAnimatables = function () {
  88148. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88149. this._animatables = [];
  88150. for (var index = 0; index < this.bones.length; index++) {
  88151. this._animatables.push(this.bones[index]);
  88152. }
  88153. }
  88154. return this._animatables;
  88155. };
  88156. /**
  88157. * Clone the current skeleton
  88158. * @param name defines the name of the new skeleton
  88159. * @param id defines the id of the enw skeleton
  88160. * @returns the new skeleton
  88161. */
  88162. Skeleton.prototype.clone = function (name, id) {
  88163. var result = new Skeleton(name, id || name, this._scene);
  88164. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88165. for (var index = 0; index < this.bones.length; index++) {
  88166. var source = this.bones[index];
  88167. var parentBone = null;
  88168. var parent_1 = source.getParent();
  88169. if (parent_1) {
  88170. var parentIndex = this.bones.indexOf(parent_1);
  88171. parentBone = result.bones[parentIndex];
  88172. }
  88173. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88174. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88175. }
  88176. if (this._ranges) {
  88177. result._ranges = {};
  88178. for (var rangeName in this._ranges) {
  88179. var range = this._ranges[rangeName];
  88180. if (range) {
  88181. result._ranges[rangeName] = range.clone();
  88182. }
  88183. }
  88184. }
  88185. this._isDirty = true;
  88186. return result;
  88187. };
  88188. /**
  88189. * Enable animation blending for this skeleton
  88190. * @param blendingSpeed defines the blending speed to apply
  88191. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88192. */
  88193. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88194. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88195. this.bones.forEach(function (bone) {
  88196. bone.animations.forEach(function (animation) {
  88197. animation.enableBlending = true;
  88198. animation.blendingSpeed = blendingSpeed;
  88199. });
  88200. });
  88201. };
  88202. /**
  88203. * Releases all resources associated with the current skeleton
  88204. */
  88205. Skeleton.prototype.dispose = function () {
  88206. this._meshesWithPoseMatrix = [];
  88207. // Animations
  88208. this.getScene().stopAnimation(this);
  88209. // Remove from scene
  88210. this.getScene().removeSkeleton(this);
  88211. };
  88212. /**
  88213. * Serialize the skeleton in a JSON object
  88214. * @returns a JSON object
  88215. */
  88216. Skeleton.prototype.serialize = function () {
  88217. var serializationObject = {};
  88218. serializationObject.name = this.name;
  88219. serializationObject.id = this.id;
  88220. if (this.dimensionsAtRest) {
  88221. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88222. }
  88223. serializationObject.bones = [];
  88224. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88225. for (var index = 0; index < this.bones.length; index++) {
  88226. var bone = this.bones[index];
  88227. var parent_2 = bone.getParent();
  88228. var serializedBone = {
  88229. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88230. name: bone.name,
  88231. matrix: bone.getBaseMatrix().toArray(),
  88232. rest: bone.getRestPose().toArray()
  88233. };
  88234. serializationObject.bones.push(serializedBone);
  88235. if (bone.length) {
  88236. serializedBone.length = bone.length;
  88237. }
  88238. if (bone.metadata) {
  88239. serializedBone.metadata = bone.metadata;
  88240. }
  88241. if (bone.animations && bone.animations.length > 0) {
  88242. serializedBone.animation = bone.animations[0].serialize();
  88243. }
  88244. serializationObject.ranges = [];
  88245. for (var name in this._ranges) {
  88246. var source = this._ranges[name];
  88247. if (!source) {
  88248. continue;
  88249. }
  88250. var range = {};
  88251. range.name = name;
  88252. range.from = source.from;
  88253. range.to = source.to;
  88254. serializationObject.ranges.push(range);
  88255. }
  88256. }
  88257. return serializationObject;
  88258. };
  88259. /**
  88260. * Creates a new skeleton from serialized data
  88261. * @param parsedSkeleton defines the serialized data
  88262. * @param scene defines the hosting scene
  88263. * @returns a new skeleton
  88264. */
  88265. Skeleton.Parse = function (parsedSkeleton, scene) {
  88266. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88267. if (parsedSkeleton.dimensionsAtRest) {
  88268. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88269. }
  88270. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88271. var index;
  88272. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88273. var parsedBone = parsedSkeleton.bones[index];
  88274. var parentBone = null;
  88275. if (parsedBone.parentBoneIndex > -1) {
  88276. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88277. }
  88278. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88279. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88280. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88281. bone.id = parsedBone.id;
  88282. }
  88283. if (parsedBone.length) {
  88284. bone.length = parsedBone.length;
  88285. }
  88286. if (parsedBone.metadata) {
  88287. bone.metadata = parsedBone.metadata;
  88288. }
  88289. if (parsedBone.animation) {
  88290. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  88291. }
  88292. }
  88293. // placed after bones, so createAnimationRange can cascade down
  88294. if (parsedSkeleton.ranges) {
  88295. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  88296. var data = parsedSkeleton.ranges[index];
  88297. skeleton.createAnimationRange(data.name, data.from, data.to);
  88298. }
  88299. }
  88300. return skeleton;
  88301. };
  88302. /**
  88303. * Compute all node absolute transforms
  88304. * @param forceUpdate defines if computation must be done even if cache is up to date
  88305. */
  88306. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  88307. if (forceUpdate === void 0) { forceUpdate = false; }
  88308. var renderId = this._scene.getRenderId();
  88309. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  88310. this.bones[0].computeAbsoluteTransforms();
  88311. this._lastAbsoluteTransformsUpdateId = renderId;
  88312. }
  88313. };
  88314. /**
  88315. * Gets the root pose matrix
  88316. * @returns a matrix
  88317. */
  88318. Skeleton.prototype.getPoseMatrix = function () {
  88319. var poseMatrix = null;
  88320. if (this._meshesWithPoseMatrix.length > 0) {
  88321. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  88322. }
  88323. return poseMatrix;
  88324. };
  88325. /**
  88326. * Sorts bones per internal index
  88327. */
  88328. Skeleton.prototype.sortBones = function () {
  88329. var bones = new Array();
  88330. var visited = new Array(this.bones.length);
  88331. for (var index = 0; index < this.bones.length; index++) {
  88332. this._sortBones(index, bones, visited);
  88333. }
  88334. this.bones = bones;
  88335. };
  88336. Skeleton.prototype._sortBones = function (index, bones, visited) {
  88337. if (visited[index]) {
  88338. return;
  88339. }
  88340. visited[index] = true;
  88341. var bone = this.bones[index];
  88342. if (bone._index === undefined) {
  88343. bone._index = index;
  88344. }
  88345. var parentBone = bone.getParent();
  88346. if (parentBone) {
  88347. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  88348. }
  88349. bones.push(bone);
  88350. };
  88351. return Skeleton;
  88352. }());
  88353. BABYLON.Skeleton = Skeleton;
  88354. })(BABYLON || (BABYLON = {}));
  88355. //# sourceMappingURL=babylon.skeleton.js.map
  88356. var BABYLON;
  88357. (function (BABYLON) {
  88358. ;
  88359. /**
  88360. * This groups tools to convert HDR texture to native colors array.
  88361. */
  88362. var HDRTools = /** @class */ (function () {
  88363. function HDRTools() {
  88364. }
  88365. HDRTools.Ldexp = function (mantissa, exponent) {
  88366. if (exponent > 1023) {
  88367. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  88368. }
  88369. if (exponent < -1074) {
  88370. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  88371. }
  88372. return mantissa * Math.pow(2, exponent);
  88373. };
  88374. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  88375. if (exponent > 0) { /*nonzero pixel*/
  88376. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  88377. float32array[index + 0] = red * exponent;
  88378. float32array[index + 1] = green * exponent;
  88379. float32array[index + 2] = blue * exponent;
  88380. }
  88381. else {
  88382. float32array[index + 0] = 0;
  88383. float32array[index + 1] = 0;
  88384. float32array[index + 2] = 0;
  88385. }
  88386. };
  88387. HDRTools.readStringLine = function (uint8array, startIndex) {
  88388. var line = "";
  88389. var character = "";
  88390. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  88391. character = String.fromCharCode(uint8array[i]);
  88392. if (character == "\n") {
  88393. break;
  88394. }
  88395. line += character;
  88396. }
  88397. return line;
  88398. };
  88399. /**
  88400. * Reads header information from an RGBE texture stored in a native array.
  88401. * More information on this format are available here:
  88402. * https://en.wikipedia.org/wiki/RGBE_image_format
  88403. *
  88404. * @param uint8array The binary file stored in native array.
  88405. * @return The header information.
  88406. */
  88407. HDRTools.RGBE_ReadHeader = function (uint8array) {
  88408. var height = 0;
  88409. var width = 0;
  88410. var line = this.readStringLine(uint8array, 0);
  88411. if (line[0] != '#' || line[1] != '?') {
  88412. throw "Bad HDR Format.";
  88413. }
  88414. var endOfHeader = false;
  88415. var findFormat = false;
  88416. var lineIndex = 0;
  88417. do {
  88418. lineIndex += (line.length + 1);
  88419. line = this.readStringLine(uint8array, lineIndex);
  88420. if (line == "FORMAT=32-bit_rle_rgbe") {
  88421. findFormat = true;
  88422. }
  88423. else if (line.length == 0) {
  88424. endOfHeader = true;
  88425. }
  88426. } while (!endOfHeader);
  88427. if (!findFormat) {
  88428. throw "HDR Bad header format, unsupported FORMAT";
  88429. }
  88430. lineIndex += (line.length + 1);
  88431. line = this.readStringLine(uint8array, lineIndex);
  88432. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  88433. var match = sizeRegexp.exec(line);
  88434. // TODO. Support +Y and -X if needed.
  88435. if (!match || match.length < 3) {
  88436. throw "HDR Bad header format, no size";
  88437. }
  88438. width = parseInt(match[2]);
  88439. height = parseInt(match[1]);
  88440. if (width < 8 || width > 0x7fff) {
  88441. throw "HDR Bad header format, unsupported size";
  88442. }
  88443. lineIndex += (line.length + 1);
  88444. return {
  88445. height: height,
  88446. width: width,
  88447. dataPosition: lineIndex
  88448. };
  88449. };
  88450. /**
  88451. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  88452. * This RGBE texture needs to store the information as a panorama.
  88453. *
  88454. * More information on this format are available here:
  88455. * https://en.wikipedia.org/wiki/RGBE_image_format
  88456. *
  88457. * @param buffer The binary file stored in an array buffer.
  88458. * @param size The expected size of the extracted cubemap.
  88459. * @return The Cube Map information.
  88460. */
  88461. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  88462. var uint8array = new Uint8Array(buffer);
  88463. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  88464. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88465. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  88466. return cubeMapData;
  88467. };
  88468. /**
  88469. * Returns the pixels data extracted from an RGBE texture.
  88470. * This pixels will be stored left to right up to down in the R G B order in one array.
  88471. *
  88472. * More information on this format are available here:
  88473. * https://en.wikipedia.org/wiki/RGBE_image_format
  88474. *
  88475. * @param uint8array The binary file stored in an array buffer.
  88476. * @param hdrInfo The header information of the file.
  88477. * @return The pixels data in RGB right to left up to down order.
  88478. */
  88479. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  88480. // Keep for multi format supports.
  88481. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88482. };
  88483. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  88484. var num_scanlines = hdrInfo.height;
  88485. var scanline_width = hdrInfo.width;
  88486. var a, b, c, d, count;
  88487. var dataIndex = hdrInfo.dataPosition;
  88488. var index = 0, endIndex = 0, i = 0;
  88489. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  88490. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  88491. // 3 channels of 4 bytes per pixel in float.
  88492. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  88493. var resultArray = new Float32Array(resultBuffer);
  88494. // read in each successive scanline
  88495. while (num_scanlines > 0) {
  88496. a = uint8array[dataIndex++];
  88497. b = uint8array[dataIndex++];
  88498. c = uint8array[dataIndex++];
  88499. d = uint8array[dataIndex++];
  88500. if (a != 2 || b != 2 || (c & 0x80)) {
  88501. // this file is not run length encoded
  88502. throw "HDR Bad header format, not RLE";
  88503. }
  88504. if (((c << 8) | d) != scanline_width) {
  88505. throw "HDR Bad header format, wrong scan line width";
  88506. }
  88507. index = 0;
  88508. // read each of the four channels for the scanline into the buffer
  88509. for (i = 0; i < 4; i++) {
  88510. endIndex = (i + 1) * scanline_width;
  88511. while (index < endIndex) {
  88512. a = uint8array[dataIndex++];
  88513. b = uint8array[dataIndex++];
  88514. if (a > 128) {
  88515. // a run of the same value
  88516. count = a - 128;
  88517. if ((count == 0) || (count > endIndex - index)) {
  88518. throw "HDR Bad Format, bad scanline data (run)";
  88519. }
  88520. while (count-- > 0) {
  88521. scanLineArray[index++] = b;
  88522. }
  88523. }
  88524. else {
  88525. // a non-run
  88526. count = a;
  88527. if ((count == 0) || (count > endIndex - index)) {
  88528. throw "HDR Bad Format, bad scanline data (non-run)";
  88529. }
  88530. scanLineArray[index++] = b;
  88531. if (--count > 0) {
  88532. for (var j = 0; j < count; j++) {
  88533. scanLineArray[index++] = uint8array[dataIndex++];
  88534. }
  88535. }
  88536. }
  88537. }
  88538. }
  88539. // now convert data from buffer into floats
  88540. for (i = 0; i < scanline_width; i++) {
  88541. a = scanLineArray[i];
  88542. b = scanLineArray[i + scanline_width];
  88543. c = scanLineArray[i + 2 * scanline_width];
  88544. d = scanLineArray[i + 3 * scanline_width];
  88545. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  88546. }
  88547. num_scanlines--;
  88548. }
  88549. return resultArray;
  88550. };
  88551. return HDRTools;
  88552. }());
  88553. BABYLON.HDRTools = HDRTools;
  88554. })(BABYLON || (BABYLON = {}));
  88555. //# sourceMappingURL=babylon.hdr.js.map
  88556. var BABYLON;
  88557. (function (BABYLON) {
  88558. /**
  88559. * This represents a texture coming from an HDR input.
  88560. *
  88561. * The only supported format is currently panorama picture stored in RGBE format.
  88562. * Example of such files can be found on HDRLib: http://hdrlib.com/
  88563. */
  88564. var HDRCubeTexture = /** @class */ (function (_super) {
  88565. __extends(HDRCubeTexture, _super);
  88566. /**
  88567. * Instantiates an HDRTexture from the following parameters.
  88568. *
  88569. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  88570. * @param scene The scene the texture will be used in
  88571. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  88572. * @param noMipmap Forces to not generate the mipmap if true
  88573. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  88574. * @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)
  88575. * @param reserved Reserved flag for internal use.
  88576. */
  88577. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  88578. if (noMipmap === void 0) { noMipmap = false; }
  88579. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88580. if (gammaSpace === void 0) { gammaSpace = false; }
  88581. if (reserved === void 0) { reserved = false; }
  88582. if (onLoad === void 0) { onLoad = null; }
  88583. if (onError === void 0) { onError = null; }
  88584. var _this = _super.call(this, scene) || this;
  88585. _this._generateHarmonics = true;
  88586. _this._onLoad = null;
  88587. _this._onError = null;
  88588. /**
  88589. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  88590. */
  88591. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  88592. _this._isBlocking = true;
  88593. _this._rotationY = 0;
  88594. /**
  88595. * Gets or sets the center of the bounding box associated with the cube texture
  88596. * It must define where the camera used to render the texture was set
  88597. */
  88598. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  88599. if (!url) {
  88600. return _this;
  88601. }
  88602. _this.name = url;
  88603. _this.url = url;
  88604. _this.hasAlpha = false;
  88605. _this.isCube = true;
  88606. _this._textureMatrix = BABYLON.Matrix.Identity();
  88607. _this._onLoad = onLoad;
  88608. _this._onError = onError;
  88609. _this.gammaSpace = gammaSpace;
  88610. _this._noMipmap = noMipmap;
  88611. _this._size = size;
  88612. _this._texture = _this._getFromCache(url, _this._noMipmap);
  88613. if (!_this._texture) {
  88614. if (!scene.useDelayedTextureLoading) {
  88615. _this.loadTexture();
  88616. }
  88617. else {
  88618. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88619. }
  88620. }
  88621. return _this;
  88622. }
  88623. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  88624. /**
  88625. * Gets wether or not the texture is blocking during loading.
  88626. */
  88627. get: function () {
  88628. return this._isBlocking;
  88629. },
  88630. /**
  88631. * Sets wether or not the texture is blocking during loading.
  88632. */
  88633. set: function (value) {
  88634. this._isBlocking = value;
  88635. },
  88636. enumerable: true,
  88637. configurable: true
  88638. });
  88639. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  88640. /**
  88641. * Gets texture matrix rotation angle around Y axis radians.
  88642. */
  88643. get: function () {
  88644. return this._rotationY;
  88645. },
  88646. /**
  88647. * Sets texture matrix rotation angle around Y axis in radians.
  88648. */
  88649. set: function (value) {
  88650. this._rotationY = value;
  88651. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  88652. },
  88653. enumerable: true,
  88654. configurable: true
  88655. });
  88656. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  88657. get: function () {
  88658. return this._boundingBoxSize;
  88659. },
  88660. /**
  88661. * Gets or sets the size of the bounding box associated with the cube texture
  88662. * When defined, the cubemap will switch to local mode
  88663. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  88664. * @example https://www.babylonjs-playground.com/#RNASML
  88665. */
  88666. set: function (value) {
  88667. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  88668. return;
  88669. }
  88670. this._boundingBoxSize = value;
  88671. var scene = this.getScene();
  88672. if (scene) {
  88673. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  88674. }
  88675. },
  88676. enumerable: true,
  88677. configurable: true
  88678. });
  88679. /**
  88680. * Occurs when the file is raw .hdr file.
  88681. */
  88682. HDRCubeTexture.prototype.loadTexture = function () {
  88683. var _this = this;
  88684. var callback = function (buffer) {
  88685. _this.lodGenerationOffset = 0.0;
  88686. _this.lodGenerationScale = 0.8;
  88687. var scene = _this.getScene();
  88688. if (!scene) {
  88689. return null;
  88690. }
  88691. // Extract the raw linear data.
  88692. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  88693. // Generate harmonics if needed.
  88694. if (_this._generateHarmonics) {
  88695. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  88696. _this.sphericalPolynomial = sphericalPolynomial;
  88697. }
  88698. var results = [];
  88699. var byteArray = null;
  88700. // Push each faces.
  88701. for (var j = 0; j < 6; j++) {
  88702. // Create uintarray fallback.
  88703. if (!scene.getEngine().getCaps().textureFloat) {
  88704. // 3 channels of 1 bytes per pixel in bytes.
  88705. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  88706. byteArray = new Uint8Array(byteBuffer);
  88707. }
  88708. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  88709. // If special cases.
  88710. if (_this.gammaSpace || byteArray) {
  88711. for (var i = 0; i < _this._size * _this._size; i++) {
  88712. // Put in gamma space if requested.
  88713. if (_this.gammaSpace) {
  88714. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  88715. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  88716. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  88717. }
  88718. // Convert to int texture for fallback.
  88719. if (byteArray) {
  88720. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  88721. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  88722. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  88723. // May use luminance instead if the result is not accurate.
  88724. var max = Math.max(Math.max(r, g), b);
  88725. if (max > 255) {
  88726. var scale = 255 / max;
  88727. r *= scale;
  88728. g *= scale;
  88729. b *= scale;
  88730. }
  88731. byteArray[(i * 3) + 0] = r;
  88732. byteArray[(i * 3) + 1] = g;
  88733. byteArray[(i * 3) + 2] = b;
  88734. }
  88735. }
  88736. }
  88737. if (byteArray) {
  88738. results.push(byteArray);
  88739. }
  88740. else {
  88741. results.push(dataFace);
  88742. }
  88743. }
  88744. return results;
  88745. };
  88746. var scene = this.getScene();
  88747. if (scene) {
  88748. 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);
  88749. }
  88750. };
  88751. HDRCubeTexture.prototype.clone = function () {
  88752. var scene = this.getScene();
  88753. if (!scene) {
  88754. return this;
  88755. }
  88756. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  88757. // Base texture
  88758. newTexture.level = this.level;
  88759. newTexture.wrapU = this.wrapU;
  88760. newTexture.wrapV = this.wrapV;
  88761. newTexture.coordinatesIndex = this.coordinatesIndex;
  88762. newTexture.coordinatesMode = this.coordinatesMode;
  88763. return newTexture;
  88764. };
  88765. // Methods
  88766. HDRCubeTexture.prototype.delayLoad = function () {
  88767. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88768. return;
  88769. }
  88770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88771. this._texture = this._getFromCache(this.url, this._noMipmap);
  88772. if (!this._texture) {
  88773. this.loadTexture();
  88774. }
  88775. };
  88776. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  88777. return this._textureMatrix;
  88778. };
  88779. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  88780. this._textureMatrix = value;
  88781. };
  88782. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88783. var texture = null;
  88784. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88785. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  88786. texture.name = parsedTexture.name;
  88787. texture.hasAlpha = parsedTexture.hasAlpha;
  88788. texture.level = parsedTexture.level;
  88789. texture.coordinatesMode = parsedTexture.coordinatesMode;
  88790. texture.isBlocking = parsedTexture.isBlocking;
  88791. }
  88792. if (texture) {
  88793. if (parsedTexture.boundingBoxPosition) {
  88794. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  88795. }
  88796. if (parsedTexture.boundingBoxSize) {
  88797. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  88798. }
  88799. if (parsedTexture.rotationY) {
  88800. texture.rotationY = parsedTexture.rotationY;
  88801. }
  88802. }
  88803. return texture;
  88804. };
  88805. HDRCubeTexture.prototype.serialize = function () {
  88806. if (!this.name) {
  88807. return null;
  88808. }
  88809. var serializationObject = {};
  88810. serializationObject.name = this.name;
  88811. serializationObject.hasAlpha = this.hasAlpha;
  88812. serializationObject.isCube = true;
  88813. serializationObject.level = this.level;
  88814. serializationObject.size = this._size;
  88815. serializationObject.coordinatesMode = this.coordinatesMode;
  88816. serializationObject.useInGammaSpace = this.gammaSpace;
  88817. serializationObject.generateHarmonics = this._generateHarmonics;
  88818. serializationObject.customType = "BABYLON.HDRCubeTexture";
  88819. serializationObject.noMipmap = this._noMipmap;
  88820. serializationObject.isBlocking = this._isBlocking;
  88821. serializationObject.rotationY = this._rotationY;
  88822. return serializationObject;
  88823. };
  88824. HDRCubeTexture._facesMapping = [
  88825. "right",
  88826. "left",
  88827. "up",
  88828. "down",
  88829. "front",
  88830. "back"
  88831. ];
  88832. return HDRCubeTexture;
  88833. }(BABYLON.BaseTexture));
  88834. BABYLON.HDRCubeTexture = HDRCubeTexture;
  88835. })(BABYLON || (BABYLON = {}));
  88836. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  88837. var BABYLON;
  88838. (function (BABYLON) {
  88839. /**
  88840. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  88841. */
  88842. var PanoramaToCubeMapTools = /** @class */ (function () {
  88843. function PanoramaToCubeMapTools() {
  88844. }
  88845. /**
  88846. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  88847. *
  88848. * @param float32Array The source data.
  88849. * @param inputWidth The width of the input panorama.
  88850. * @param inputhHeight The height of the input panorama.
  88851. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  88852. * @return The cubemap data
  88853. */
  88854. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  88855. if (!float32Array) {
  88856. throw "ConvertPanoramaToCubemap: input cannot be null";
  88857. }
  88858. if (float32Array.length != inputWidth * inputHeight * 3) {
  88859. throw "ConvertPanoramaToCubemap: input size is wrong";
  88860. }
  88861. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  88862. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  88863. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  88864. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  88865. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  88866. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  88867. return {
  88868. front: textureFront,
  88869. back: textureBack,
  88870. left: textureLeft,
  88871. right: textureRight,
  88872. up: textureUp,
  88873. down: textureDown,
  88874. size: size,
  88875. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88876. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  88877. gammaSpace: false,
  88878. };
  88879. };
  88880. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  88881. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  88882. var textureArray = new Float32Array(buffer);
  88883. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  88884. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  88885. var dy = 1 / texSize;
  88886. var fy = 0;
  88887. for (var y = 0; y < texSize; y++) {
  88888. var xv1 = faceData[0];
  88889. var xv2 = faceData[2];
  88890. for (var x = 0; x < texSize; x++) {
  88891. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  88892. v.normalize();
  88893. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  88894. // 3 channels per pixels
  88895. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  88896. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  88897. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  88898. xv1 = xv1.add(rotDX1);
  88899. xv2 = xv2.add(rotDX2);
  88900. }
  88901. fy += dy;
  88902. }
  88903. return textureArray;
  88904. };
  88905. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  88906. var theta = Math.atan2(vDir.z, vDir.x);
  88907. var phi = Math.acos(vDir.y);
  88908. while (theta < -Math.PI)
  88909. theta += 2 * Math.PI;
  88910. while (theta > Math.PI)
  88911. theta -= 2 * Math.PI;
  88912. var dx = theta / Math.PI;
  88913. var dy = phi / Math.PI;
  88914. // recenter.
  88915. dx = dx * 0.5 + 0.5;
  88916. var px = Math.round(dx * inputWidth);
  88917. if (px < 0)
  88918. px = 0;
  88919. else if (px >= inputWidth)
  88920. px = inputWidth - 1;
  88921. var py = Math.round(dy * inputHeight);
  88922. if (py < 0)
  88923. py = 0;
  88924. else if (py >= inputHeight)
  88925. py = inputHeight - 1;
  88926. var inputY = (inputHeight - py - 1);
  88927. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  88928. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  88929. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  88930. return {
  88931. r: r,
  88932. g: g,
  88933. b: b
  88934. };
  88935. };
  88936. PanoramaToCubeMapTools.FACE_FRONT = [
  88937. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88938. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88939. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88940. new BABYLON.Vector3(1.0, 1.0, -1.0)
  88941. ];
  88942. PanoramaToCubeMapTools.FACE_BACK = [
  88943. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88944. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88945. new BABYLON.Vector3(1.0, 1.0, 1.0),
  88946. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  88947. ];
  88948. PanoramaToCubeMapTools.FACE_RIGHT = [
  88949. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88950. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88951. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88952. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88953. ];
  88954. PanoramaToCubeMapTools.FACE_LEFT = [
  88955. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88956. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88957. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88958. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  88959. ];
  88960. PanoramaToCubeMapTools.FACE_DOWN = [
  88961. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88962. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88963. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88964. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88965. ];
  88966. PanoramaToCubeMapTools.FACE_UP = [
  88967. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88968. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88969. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88970. new BABYLON.Vector3(1.0, -1.0, -1.0)
  88971. ];
  88972. return PanoramaToCubeMapTools;
  88973. }());
  88974. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  88975. })(BABYLON || (BABYLON = {}));
  88976. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  88977. var BABYLON;
  88978. (function (BABYLON) {
  88979. var IndexedVector2 = /** @class */ (function (_super) {
  88980. __extends(IndexedVector2, _super);
  88981. function IndexedVector2(original, index) {
  88982. var _this = _super.call(this, original.x, original.y) || this;
  88983. _this.index = index;
  88984. return _this;
  88985. }
  88986. return IndexedVector2;
  88987. }(BABYLON.Vector2));
  88988. var PolygonPoints = /** @class */ (function () {
  88989. function PolygonPoints() {
  88990. this.elements = new Array();
  88991. }
  88992. PolygonPoints.prototype.add = function (originalPoints) {
  88993. var _this = this;
  88994. var result = new Array();
  88995. originalPoints.forEach(function (point) {
  88996. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  88997. var newPoint = new IndexedVector2(point, _this.elements.length);
  88998. result.push(newPoint);
  88999. _this.elements.push(newPoint);
  89000. }
  89001. });
  89002. return result;
  89003. };
  89004. PolygonPoints.prototype.computeBounds = function () {
  89005. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89006. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89007. this.elements.forEach(function (point) {
  89008. // x
  89009. if (point.x < lmin.x) {
  89010. lmin.x = point.x;
  89011. }
  89012. else if (point.x > lmax.x) {
  89013. lmax.x = point.x;
  89014. }
  89015. // y
  89016. if (point.y < lmin.y) {
  89017. lmin.y = point.y;
  89018. }
  89019. else if (point.y > lmax.y) {
  89020. lmax.y = point.y;
  89021. }
  89022. });
  89023. return {
  89024. min: lmin,
  89025. max: lmax,
  89026. width: lmax.x - lmin.x,
  89027. height: lmax.y - lmin.y
  89028. };
  89029. };
  89030. return PolygonPoints;
  89031. }());
  89032. var Polygon = /** @class */ (function () {
  89033. function Polygon() {
  89034. }
  89035. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89036. return [
  89037. new BABYLON.Vector2(xmin, ymin),
  89038. new BABYLON.Vector2(xmax, ymin),
  89039. new BABYLON.Vector2(xmax, ymax),
  89040. new BABYLON.Vector2(xmin, ymax)
  89041. ];
  89042. };
  89043. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89044. if (cx === void 0) { cx = 0; }
  89045. if (cy === void 0) { cy = 0; }
  89046. if (numberOfSides === void 0) { numberOfSides = 32; }
  89047. var result = new Array();
  89048. var angle = 0;
  89049. var increment = (Math.PI * 2) / numberOfSides;
  89050. for (var i = 0; i < numberOfSides; i++) {
  89051. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89052. angle -= increment;
  89053. }
  89054. return result;
  89055. };
  89056. Polygon.Parse = function (input) {
  89057. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89058. var i, result = [];
  89059. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89060. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89061. }
  89062. return result;
  89063. };
  89064. Polygon.StartingAt = function (x, y) {
  89065. return BABYLON.Path2.StartingAt(x, y);
  89066. };
  89067. return Polygon;
  89068. }());
  89069. BABYLON.Polygon = Polygon;
  89070. var PolygonMeshBuilder = /** @class */ (function () {
  89071. function PolygonMeshBuilder(name, contours, scene) {
  89072. this._points = new PolygonPoints();
  89073. this._outlinepoints = new PolygonPoints();
  89074. this._holes = new Array();
  89075. this._epoints = new Array();
  89076. this._eholes = new Array();
  89077. this._name = name;
  89078. this._scene = scene;
  89079. var points;
  89080. if (contours instanceof BABYLON.Path2) {
  89081. points = contours.getPoints();
  89082. }
  89083. else {
  89084. points = contours;
  89085. }
  89086. this._addToepoint(points);
  89087. this._points.add(points);
  89088. this._outlinepoints.add(points);
  89089. if (typeof earcut === 'undefined') {
  89090. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89091. }
  89092. }
  89093. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89094. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89095. var p = points_1[_i];
  89096. this._epoints.push(p.x, p.y);
  89097. }
  89098. };
  89099. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89100. this._points.add(hole);
  89101. var holepoints = new PolygonPoints();
  89102. holepoints.add(hole);
  89103. this._holes.push(holepoints);
  89104. this._eholes.push(this._epoints.length / 2);
  89105. this._addToepoint(hole);
  89106. return this;
  89107. };
  89108. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89109. var _this = this;
  89110. if (updatable === void 0) { updatable = false; }
  89111. if (depth === void 0) { depth = 0; }
  89112. var result = new BABYLON.Mesh(this._name, this._scene);
  89113. var normals = new Array();
  89114. var positions = new Array();
  89115. var uvs = new Array();
  89116. var bounds = this._points.computeBounds();
  89117. this._points.elements.forEach(function (p) {
  89118. normals.push(0, 1.0, 0);
  89119. positions.push(p.x, 0, p.y);
  89120. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89121. });
  89122. var indices = new Array();
  89123. var res = earcut(this._epoints, this._eholes, 2);
  89124. for (var i = 0; i < res.length; i++) {
  89125. indices.push(res[i]);
  89126. }
  89127. if (depth > 0) {
  89128. var positionscount = (positions.length / 3); //get the current pointcount
  89129. this._points.elements.forEach(function (p) {
  89130. normals.push(0, -1.0, 0);
  89131. positions.push(p.x, -depth, p.y);
  89132. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89133. });
  89134. var totalCount = indices.length;
  89135. for (var i = 0; i < totalCount; i += 3) {
  89136. var i0 = indices[i + 0];
  89137. var i1 = indices[i + 1];
  89138. var i2 = indices[i + 2];
  89139. indices.push(i2 + positionscount);
  89140. indices.push(i1 + positionscount);
  89141. indices.push(i0 + positionscount);
  89142. }
  89143. //Add the sides
  89144. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89145. this._holes.forEach(function (hole) {
  89146. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89147. });
  89148. }
  89149. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89150. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89151. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89152. result.setIndices(indices);
  89153. return result;
  89154. };
  89155. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89156. var StartIndex = positions.length / 3;
  89157. var ulength = 0;
  89158. for (var i = 0; i < points.elements.length; i++) {
  89159. var p = points.elements[i];
  89160. var p1;
  89161. if ((i + 1) > points.elements.length - 1) {
  89162. p1 = points.elements[0];
  89163. }
  89164. else {
  89165. p1 = points.elements[i + 1];
  89166. }
  89167. positions.push(p.x, 0, p.y);
  89168. positions.push(p.x, -depth, p.y);
  89169. positions.push(p1.x, 0, p1.y);
  89170. positions.push(p1.x, -depth, p1.y);
  89171. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89172. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89173. var v3 = v2.subtract(v1);
  89174. var v4 = new BABYLON.Vector3(0, 1, 0);
  89175. var vn = BABYLON.Vector3.Cross(v3, v4);
  89176. vn = vn.normalize();
  89177. uvs.push(ulength / bounds.width, 0);
  89178. uvs.push(ulength / bounds.width, 1);
  89179. ulength += v3.length();
  89180. uvs.push((ulength / bounds.width), 0);
  89181. uvs.push((ulength / bounds.width), 1);
  89182. if (!flip) {
  89183. normals.push(-vn.x, -vn.y, -vn.z);
  89184. normals.push(-vn.x, -vn.y, -vn.z);
  89185. normals.push(-vn.x, -vn.y, -vn.z);
  89186. normals.push(-vn.x, -vn.y, -vn.z);
  89187. indices.push(StartIndex);
  89188. indices.push(StartIndex + 1);
  89189. indices.push(StartIndex + 2);
  89190. indices.push(StartIndex + 1);
  89191. indices.push(StartIndex + 3);
  89192. indices.push(StartIndex + 2);
  89193. }
  89194. else {
  89195. normals.push(vn.x, vn.y, vn.z);
  89196. normals.push(vn.x, vn.y, vn.z);
  89197. normals.push(vn.x, vn.y, vn.z);
  89198. normals.push(vn.x, vn.y, vn.z);
  89199. indices.push(StartIndex);
  89200. indices.push(StartIndex + 2);
  89201. indices.push(StartIndex + 1);
  89202. indices.push(StartIndex + 1);
  89203. indices.push(StartIndex + 2);
  89204. indices.push(StartIndex + 3);
  89205. }
  89206. StartIndex += 4;
  89207. }
  89208. ;
  89209. };
  89210. return PolygonMeshBuilder;
  89211. }());
  89212. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89213. })(BABYLON || (BABYLON = {}));
  89214. //# sourceMappingURL=babylon.polygonMesh.js.map
  89215. var BABYLON;
  89216. (function (BABYLON) {
  89217. // Unique ID when we import meshes from Babylon to CSG
  89218. var currentCSGMeshId = 0;
  89219. // # class Vertex
  89220. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89221. // one to provide additional features like texture coordinates and vertex
  89222. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89223. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89224. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89225. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89226. // is not used anywhere else.
  89227. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89228. var Vertex = /** @class */ (function () {
  89229. function Vertex(pos, normal, uv) {
  89230. this.pos = pos;
  89231. this.normal = normal;
  89232. this.uv = uv;
  89233. }
  89234. Vertex.prototype.clone = function () {
  89235. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89236. };
  89237. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89238. // orientation of a polygon is flipped.
  89239. Vertex.prototype.flip = function () {
  89240. this.normal = this.normal.scale(-1);
  89241. };
  89242. // Create a new vertex between this vertex and `other` by linearly
  89243. // interpolating all properties using a parameter of `t`. Subclasses should
  89244. // override this to interpolate additional properties.
  89245. Vertex.prototype.interpolate = function (other, t) {
  89246. 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));
  89247. };
  89248. return Vertex;
  89249. }());
  89250. // # class Plane
  89251. // Represents a plane in 3D space.
  89252. var Plane = /** @class */ (function () {
  89253. function Plane(normal, w) {
  89254. this.normal = normal;
  89255. this.w = w;
  89256. }
  89257. Plane.FromPoints = function (a, b, c) {
  89258. var v0 = c.subtract(a);
  89259. var v1 = b.subtract(a);
  89260. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89261. return null;
  89262. }
  89263. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89264. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89265. };
  89266. Plane.prototype.clone = function () {
  89267. return new Plane(this.normal.clone(), this.w);
  89268. };
  89269. Plane.prototype.flip = function () {
  89270. this.normal.scaleInPlace(-1);
  89271. this.w = -this.w;
  89272. };
  89273. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89274. // fragments in the appropriate lists. Coplanar polygons go into either
  89275. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89276. // respect to this plane. Polygons in front or in back of this plane go into
  89277. // either `front` or `back`.
  89278. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89279. var COPLANAR = 0;
  89280. var FRONT = 1;
  89281. var BACK = 2;
  89282. var SPANNING = 3;
  89283. // Classify each point as well as the entire polygon into one of the above
  89284. // four classes.
  89285. var polygonType = 0;
  89286. var types = [];
  89287. var i;
  89288. var t;
  89289. for (i = 0; i < polygon.vertices.length; i++) {
  89290. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  89291. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  89292. polygonType |= type;
  89293. types.push(type);
  89294. }
  89295. // Put the polygon in the correct list, splitting it when necessary.
  89296. switch (polygonType) {
  89297. case COPLANAR:
  89298. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  89299. break;
  89300. case FRONT:
  89301. front.push(polygon);
  89302. break;
  89303. case BACK:
  89304. back.push(polygon);
  89305. break;
  89306. case SPANNING:
  89307. var f = [], b = [];
  89308. for (i = 0; i < polygon.vertices.length; i++) {
  89309. var j = (i + 1) % polygon.vertices.length;
  89310. var ti = types[i], tj = types[j];
  89311. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  89312. if (ti !== BACK)
  89313. f.push(vi);
  89314. if (ti !== FRONT)
  89315. b.push(ti !== BACK ? vi.clone() : vi);
  89316. if ((ti | tj) === SPANNING) {
  89317. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  89318. var v = vi.interpolate(vj, t);
  89319. f.push(v);
  89320. b.push(v.clone());
  89321. }
  89322. }
  89323. var poly;
  89324. if (f.length >= 3) {
  89325. poly = new Polygon(f, polygon.shared);
  89326. if (poly.plane)
  89327. front.push(poly);
  89328. }
  89329. if (b.length >= 3) {
  89330. poly = new Polygon(b, polygon.shared);
  89331. if (poly.plane)
  89332. back.push(poly);
  89333. }
  89334. break;
  89335. }
  89336. };
  89337. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  89338. // point is on the plane.
  89339. Plane.EPSILON = 1e-5;
  89340. return Plane;
  89341. }());
  89342. // # class Polygon
  89343. // Represents a convex polygon. The vertices used to initialize a polygon must
  89344. // be coplanar and form a convex loop.
  89345. //
  89346. // Each convex polygon has a `shared` property, which is shared between all
  89347. // polygons that are clones of each other or were split from the same polygon.
  89348. // This can be used to define per-polygon properties (such as surface color).
  89349. var Polygon = /** @class */ (function () {
  89350. function Polygon(vertices, shared) {
  89351. this.vertices = vertices;
  89352. this.shared = shared;
  89353. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  89354. }
  89355. Polygon.prototype.clone = function () {
  89356. var vertices = this.vertices.map(function (v) { return v.clone(); });
  89357. return new Polygon(vertices, this.shared);
  89358. };
  89359. Polygon.prototype.flip = function () {
  89360. this.vertices.reverse().map(function (v) { v.flip(); });
  89361. this.plane.flip();
  89362. };
  89363. return Polygon;
  89364. }());
  89365. // # class Node
  89366. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  89367. // by picking a polygon to split along. That polygon (and all other coplanar
  89368. // polygons) are added directly to that node and the other polygons are added to
  89369. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  89370. // no distinction between internal and leaf nodes.
  89371. var Node = /** @class */ (function () {
  89372. function Node(polygons) {
  89373. this.plane = null;
  89374. this.front = null;
  89375. this.back = null;
  89376. this.polygons = new Array();
  89377. if (polygons) {
  89378. this.build(polygons);
  89379. }
  89380. }
  89381. Node.prototype.clone = function () {
  89382. var node = new Node();
  89383. node.plane = this.plane && this.plane.clone();
  89384. node.front = this.front && this.front.clone();
  89385. node.back = this.back && this.back.clone();
  89386. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  89387. return node;
  89388. };
  89389. // Convert solid space to empty space and empty space to solid space.
  89390. Node.prototype.invert = function () {
  89391. for (var i = 0; i < this.polygons.length; i++) {
  89392. this.polygons[i].flip();
  89393. }
  89394. if (this.plane) {
  89395. this.plane.flip();
  89396. }
  89397. if (this.front) {
  89398. this.front.invert();
  89399. }
  89400. if (this.back) {
  89401. this.back.invert();
  89402. }
  89403. var temp = this.front;
  89404. this.front = this.back;
  89405. this.back = temp;
  89406. };
  89407. // Recursively remove all polygons in `polygons` that are inside this BSP
  89408. // tree.
  89409. Node.prototype.clipPolygons = function (polygons) {
  89410. if (!this.plane)
  89411. return polygons.slice();
  89412. var front = new Array(), back = new Array();
  89413. for (var i = 0; i < polygons.length; i++) {
  89414. this.plane.splitPolygon(polygons[i], front, back, front, back);
  89415. }
  89416. if (this.front) {
  89417. front = this.front.clipPolygons(front);
  89418. }
  89419. if (this.back) {
  89420. back = this.back.clipPolygons(back);
  89421. }
  89422. else {
  89423. back = [];
  89424. }
  89425. return front.concat(back);
  89426. };
  89427. // Remove all polygons in this BSP tree that are inside the other BSP tree
  89428. // `bsp`.
  89429. Node.prototype.clipTo = function (bsp) {
  89430. this.polygons = bsp.clipPolygons(this.polygons);
  89431. if (this.front)
  89432. this.front.clipTo(bsp);
  89433. if (this.back)
  89434. this.back.clipTo(bsp);
  89435. };
  89436. // Return a list of all polygons in this BSP tree.
  89437. Node.prototype.allPolygons = function () {
  89438. var polygons = this.polygons.slice();
  89439. if (this.front)
  89440. polygons = polygons.concat(this.front.allPolygons());
  89441. if (this.back)
  89442. polygons = polygons.concat(this.back.allPolygons());
  89443. return polygons;
  89444. };
  89445. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  89446. // new polygons are filtered down to the bottom of the tree and become new
  89447. // nodes there. Each set of polygons is partitioned using the first polygon
  89448. // (no heuristic is used to pick a good split).
  89449. Node.prototype.build = function (polygons) {
  89450. if (!polygons.length)
  89451. return;
  89452. if (!this.plane)
  89453. this.plane = polygons[0].plane.clone();
  89454. var front = new Array(), back = new Array();
  89455. for (var i = 0; i < polygons.length; i++) {
  89456. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  89457. }
  89458. if (front.length) {
  89459. if (!this.front)
  89460. this.front = new Node();
  89461. this.front.build(front);
  89462. }
  89463. if (back.length) {
  89464. if (!this.back)
  89465. this.back = new Node();
  89466. this.back.build(back);
  89467. }
  89468. };
  89469. return Node;
  89470. }());
  89471. var CSG = /** @class */ (function () {
  89472. function CSG() {
  89473. this.polygons = new Array();
  89474. }
  89475. // Convert BABYLON.Mesh to BABYLON.CSG
  89476. CSG.FromMesh = function (mesh) {
  89477. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  89478. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  89479. if (mesh instanceof BABYLON.Mesh) {
  89480. mesh.computeWorldMatrix(true);
  89481. matrix = mesh.getWorldMatrix();
  89482. meshPosition = mesh.position.clone();
  89483. meshRotation = mesh.rotation.clone();
  89484. if (mesh.rotationQuaternion) {
  89485. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  89486. }
  89487. meshScaling = mesh.scaling.clone();
  89488. }
  89489. else {
  89490. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  89491. }
  89492. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89493. var subMeshes = mesh.subMeshes;
  89494. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  89495. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  89496. vertices = [];
  89497. for (var j = 0; j < 3; j++) {
  89498. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  89499. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  89500. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  89501. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  89502. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  89503. vertex = new Vertex(position, normal, uv);
  89504. vertices.push(vertex);
  89505. }
  89506. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  89507. // To handle the case of degenerated triangle
  89508. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  89509. if (polygon.plane)
  89510. polygons.push(polygon);
  89511. }
  89512. }
  89513. var csg = CSG.FromPolygons(polygons);
  89514. csg.matrix = matrix;
  89515. csg.position = meshPosition;
  89516. csg.rotation = meshRotation;
  89517. csg.scaling = meshScaling;
  89518. csg.rotationQuaternion = meshRotationQuaternion;
  89519. currentCSGMeshId++;
  89520. return csg;
  89521. };
  89522. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  89523. CSG.FromPolygons = function (polygons) {
  89524. var csg = new CSG();
  89525. csg.polygons = polygons;
  89526. return csg;
  89527. };
  89528. CSG.prototype.clone = function () {
  89529. var csg = new CSG();
  89530. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  89531. csg.copyTransformAttributes(this);
  89532. return csg;
  89533. };
  89534. CSG.prototype.union = function (csg) {
  89535. var a = new Node(this.clone().polygons);
  89536. var b = new Node(csg.clone().polygons);
  89537. a.clipTo(b);
  89538. b.clipTo(a);
  89539. b.invert();
  89540. b.clipTo(a);
  89541. b.invert();
  89542. a.build(b.allPolygons());
  89543. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89544. };
  89545. CSG.prototype.unionInPlace = function (csg) {
  89546. var a = new Node(this.polygons);
  89547. var b = new Node(csg.polygons);
  89548. a.clipTo(b);
  89549. b.clipTo(a);
  89550. b.invert();
  89551. b.clipTo(a);
  89552. b.invert();
  89553. a.build(b.allPolygons());
  89554. this.polygons = a.allPolygons();
  89555. };
  89556. CSG.prototype.subtract = function (csg) {
  89557. var a = new Node(this.clone().polygons);
  89558. var b = new Node(csg.clone().polygons);
  89559. a.invert();
  89560. a.clipTo(b);
  89561. b.clipTo(a);
  89562. b.invert();
  89563. b.clipTo(a);
  89564. b.invert();
  89565. a.build(b.allPolygons());
  89566. a.invert();
  89567. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89568. };
  89569. CSG.prototype.subtractInPlace = function (csg) {
  89570. var a = new Node(this.polygons);
  89571. var b = new Node(csg.polygons);
  89572. a.invert();
  89573. a.clipTo(b);
  89574. b.clipTo(a);
  89575. b.invert();
  89576. b.clipTo(a);
  89577. b.invert();
  89578. a.build(b.allPolygons());
  89579. a.invert();
  89580. this.polygons = a.allPolygons();
  89581. };
  89582. CSG.prototype.intersect = function (csg) {
  89583. var a = new Node(this.clone().polygons);
  89584. var b = new Node(csg.clone().polygons);
  89585. a.invert();
  89586. b.clipTo(a);
  89587. b.invert();
  89588. a.clipTo(b);
  89589. b.clipTo(a);
  89590. a.build(b.allPolygons());
  89591. a.invert();
  89592. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89593. };
  89594. CSG.prototype.intersectInPlace = function (csg) {
  89595. var a = new Node(this.polygons);
  89596. var b = new Node(csg.polygons);
  89597. a.invert();
  89598. b.clipTo(a);
  89599. b.invert();
  89600. a.clipTo(b);
  89601. b.clipTo(a);
  89602. a.build(b.allPolygons());
  89603. a.invert();
  89604. this.polygons = a.allPolygons();
  89605. };
  89606. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  89607. // not modified.
  89608. CSG.prototype.inverse = function () {
  89609. var csg = this.clone();
  89610. csg.inverseInPlace();
  89611. return csg;
  89612. };
  89613. CSG.prototype.inverseInPlace = function () {
  89614. this.polygons.map(function (p) { p.flip(); });
  89615. };
  89616. // This is used to keep meshes transformations so they can be restored
  89617. // when we build back a Babylon Mesh
  89618. // NB : All CSG operations are performed in world coordinates
  89619. CSG.prototype.copyTransformAttributes = function (csg) {
  89620. this.matrix = csg.matrix;
  89621. this.position = csg.position;
  89622. this.rotation = csg.rotation;
  89623. this.scaling = csg.scaling;
  89624. this.rotationQuaternion = csg.rotationQuaternion;
  89625. return this;
  89626. };
  89627. // Build Raw mesh from CSG
  89628. // Coordinates here are in world space
  89629. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  89630. var matrix = this.matrix.clone();
  89631. matrix.invert();
  89632. 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;
  89633. if (keepSubMeshes) {
  89634. // Sort Polygons, since subMeshes are indices range
  89635. polygons.sort(function (a, b) {
  89636. if (a.shared.meshId === b.shared.meshId) {
  89637. return a.shared.subMeshId - b.shared.subMeshId;
  89638. }
  89639. else {
  89640. return a.shared.meshId - b.shared.meshId;
  89641. }
  89642. });
  89643. }
  89644. for (var i = 0, il = polygons.length; i < il; i++) {
  89645. polygon = polygons[i];
  89646. // Building SubMeshes
  89647. if (!subMesh_dict[polygon.shared.meshId]) {
  89648. subMesh_dict[polygon.shared.meshId] = {};
  89649. }
  89650. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  89651. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  89652. indexStart: +Infinity,
  89653. indexEnd: -Infinity,
  89654. materialIndex: polygon.shared.materialIndex
  89655. };
  89656. }
  89657. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  89658. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  89659. polygonIndices[0] = 0;
  89660. polygonIndices[1] = j - 1;
  89661. polygonIndices[2] = j;
  89662. for (var k = 0; k < 3; k++) {
  89663. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  89664. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  89665. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  89666. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  89667. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  89668. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  89669. // Check if 2 points can be merged
  89670. if (!(typeof vertex_idx !== 'undefined' &&
  89671. normals[vertex_idx * 3] === localNormal.x &&
  89672. normals[vertex_idx * 3 + 1] === localNormal.y &&
  89673. normals[vertex_idx * 3 + 2] === localNormal.z &&
  89674. uvs[vertex_idx * 2] === uv.x &&
  89675. uvs[vertex_idx * 2 + 1] === uv.y)) {
  89676. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  89677. uvs.push(uv.x, uv.y);
  89678. normals.push(normal.x, normal.y, normal.z);
  89679. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  89680. }
  89681. indices.push(vertex_idx);
  89682. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  89683. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  89684. currentIndex++;
  89685. }
  89686. }
  89687. }
  89688. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  89689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  89690. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  89691. mesh.setIndices(indices, null);
  89692. if (keepSubMeshes) {
  89693. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  89694. var materialIndexOffset = 0, materialMaxIndex;
  89695. mesh.subMeshes = new Array();
  89696. for (var m in subMesh_dict) {
  89697. materialMaxIndex = -1;
  89698. for (var sm in subMesh_dict[m]) {
  89699. subMesh_obj = subMesh_dict[m][sm];
  89700. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  89701. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  89702. }
  89703. materialIndexOffset += ++materialMaxIndex;
  89704. }
  89705. }
  89706. return mesh;
  89707. };
  89708. // Build Mesh from CSG taking material and transforms into account
  89709. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  89710. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  89711. mesh.material = material;
  89712. mesh.position.copyFrom(this.position);
  89713. mesh.rotation.copyFrom(this.rotation);
  89714. if (this.rotationQuaternion) {
  89715. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  89716. }
  89717. mesh.scaling.copyFrom(this.scaling);
  89718. mesh.computeWorldMatrix(true);
  89719. return mesh;
  89720. };
  89721. return CSG;
  89722. }());
  89723. BABYLON.CSG = CSG;
  89724. })(BABYLON || (BABYLON = {}));
  89725. //# sourceMappingURL=babylon.csg.js.map
  89726. var BABYLON;
  89727. (function (BABYLON) {
  89728. var LensFlare = /** @class */ (function () {
  89729. function LensFlare(size, position, color, imgUrl, system) {
  89730. this.size = size;
  89731. this.position = position;
  89732. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89733. this.color = color || new BABYLON.Color3(1, 1, 1);
  89734. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  89735. this._system = system;
  89736. system.lensFlares.push(this);
  89737. }
  89738. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  89739. return new LensFlare(size, position, color, imgUrl, system);
  89740. };
  89741. LensFlare.prototype.dispose = function () {
  89742. if (this.texture) {
  89743. this.texture.dispose();
  89744. }
  89745. // Remove from scene
  89746. var index = this._system.lensFlares.indexOf(this);
  89747. this._system.lensFlares.splice(index, 1);
  89748. };
  89749. ;
  89750. return LensFlare;
  89751. }());
  89752. BABYLON.LensFlare = LensFlare;
  89753. })(BABYLON || (BABYLON = {}));
  89754. //# sourceMappingURL=babylon.lensFlare.js.map
  89755. var BABYLON;
  89756. (function (BABYLON) {
  89757. // Adds the parser to the scene parsers.
  89758. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  89759. // Lens flares
  89760. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  89761. if (!container.lensFlareSystems) {
  89762. container.lensFlareSystems = new Array();
  89763. }
  89764. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  89765. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  89766. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  89767. container.lensFlareSystems.push(lf);
  89768. }
  89769. }
  89770. });
  89771. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  89772. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89773. if (this.lensFlareSystems[index].name === name) {
  89774. return this.lensFlareSystems[index];
  89775. }
  89776. }
  89777. return null;
  89778. };
  89779. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  89780. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89781. if (this.lensFlareSystems[index].id === id) {
  89782. return this.lensFlareSystems[index];
  89783. }
  89784. }
  89785. return null;
  89786. };
  89787. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  89788. var index = this.lensFlareSystems.indexOf(toRemove);
  89789. if (index !== -1) {
  89790. this.lensFlareSystems.splice(index, 1);
  89791. }
  89792. return index;
  89793. };
  89794. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  89795. this.lensFlareSystems.push(newLensFlareSystem);
  89796. };
  89797. /**
  89798. * Defines the lens flare scene component responsible to manage any lens flares
  89799. * in a given scene.
  89800. */
  89801. var LensFlareSystemSceneComponent = /** @class */ (function () {
  89802. /**
  89803. * Creates a new instance of the component for the given scene
  89804. * @param scene Defines the scene to register the component in
  89805. */
  89806. function LensFlareSystemSceneComponent(scene) {
  89807. /**
  89808. * The component name helpfull to identify the component in the list of scene components.
  89809. */
  89810. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  89811. this.scene = scene;
  89812. scene.lensFlareSystems = new Array();
  89813. }
  89814. /**
  89815. * Registers the component in a given scene
  89816. */
  89817. LensFlareSystemSceneComponent.prototype.register = function () {
  89818. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  89819. };
  89820. /**
  89821. * Rebuilds the elements related to this component in case of
  89822. * context lost for instance.
  89823. */
  89824. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  89825. // Nothing to do for lens flare
  89826. };
  89827. /**
  89828. * Adds all the element from the container to the scene
  89829. * @param container the container holding the elements
  89830. */
  89831. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  89832. var _this = this;
  89833. if (!container.lensFlareSystems) {
  89834. return;
  89835. }
  89836. container.lensFlareSystems.forEach(function (o) {
  89837. _this.scene.addLensFlareSystem(o);
  89838. });
  89839. };
  89840. /**
  89841. * Removes all the elements in the container from the scene
  89842. * @param container contains the elements to remove
  89843. */
  89844. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  89845. var _this = this;
  89846. if (!container.lensFlareSystems) {
  89847. return;
  89848. }
  89849. container.lensFlareSystems.forEach(function (o) {
  89850. _this.scene.removeLensFlareSystem(o);
  89851. });
  89852. };
  89853. /**
  89854. * Serializes the component data to the specified json object
  89855. * @param serializationObject The object to serialize to
  89856. */
  89857. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  89858. // Lens flares
  89859. serializationObject.lensFlareSystems = [];
  89860. var lensFlareSystems = this.scene.lensFlareSystems;
  89861. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  89862. var lensFlareSystem = lensFlareSystems_1[_i];
  89863. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  89864. }
  89865. };
  89866. /**
  89867. * Disposes the component and the associated ressources.
  89868. */
  89869. LensFlareSystemSceneComponent.prototype.dispose = function () {
  89870. var lensFlareSystems = this.scene.lensFlareSystems;
  89871. while (lensFlareSystems.length) {
  89872. lensFlareSystems[0].dispose();
  89873. }
  89874. };
  89875. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  89876. // Lens flares
  89877. if (this.scene.lensFlaresEnabled) {
  89878. var lensFlareSystems = this.scene.lensFlareSystems;
  89879. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89880. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  89881. var lensFlareSystem = lensFlareSystems_2[_i];
  89882. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  89883. lensFlareSystem.render();
  89884. }
  89885. }
  89886. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89887. }
  89888. };
  89889. return LensFlareSystemSceneComponent;
  89890. }());
  89891. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  89892. })(BABYLON || (BABYLON = {}));
  89893. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  89894. var BABYLON;
  89895. (function (BABYLON) {
  89896. var LensFlareSystem = /** @class */ (function () {
  89897. function LensFlareSystem(name, emitter, scene) {
  89898. this.name = name;
  89899. this.lensFlares = new Array();
  89900. this.borderLimit = 300;
  89901. this.viewportBorder = 0;
  89902. this.layerMask = 0x0FFFFFFF;
  89903. this._vertexBuffers = {};
  89904. this._isEnabled = true;
  89905. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89906. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  89907. if (!component) {
  89908. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  89909. scene._addComponent(component);
  89910. }
  89911. this._emitter = emitter;
  89912. this.id = name;
  89913. scene.lensFlareSystems.push(this);
  89914. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  89915. var engine = scene.getEngine();
  89916. // VBO
  89917. var vertices = [];
  89918. vertices.push(1, 1);
  89919. vertices.push(-1, 1);
  89920. vertices.push(-1, -1);
  89921. vertices.push(1, -1);
  89922. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89923. // Indices
  89924. var indices = [];
  89925. indices.push(0);
  89926. indices.push(1);
  89927. indices.push(2);
  89928. indices.push(0);
  89929. indices.push(2);
  89930. indices.push(3);
  89931. this._indexBuffer = engine.createIndexBuffer(indices);
  89932. // Effects
  89933. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  89934. }
  89935. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  89936. get: function () {
  89937. return this._isEnabled;
  89938. },
  89939. set: function (value) {
  89940. this._isEnabled = value;
  89941. },
  89942. enumerable: true,
  89943. configurable: true
  89944. });
  89945. LensFlareSystem.prototype.getScene = function () {
  89946. return this._scene;
  89947. };
  89948. LensFlareSystem.prototype.getEmitter = function () {
  89949. return this._emitter;
  89950. };
  89951. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  89952. this._emitter = newEmitter;
  89953. };
  89954. LensFlareSystem.prototype.getEmitterPosition = function () {
  89955. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  89956. };
  89957. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  89958. var position = this.getEmitterPosition();
  89959. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  89960. this._positionX = position.x;
  89961. this._positionY = position.y;
  89962. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  89963. if (this.viewportBorder > 0) {
  89964. globalViewport.x -= this.viewportBorder;
  89965. globalViewport.y -= this.viewportBorder;
  89966. globalViewport.width += this.viewportBorder * 2;
  89967. globalViewport.height += this.viewportBorder * 2;
  89968. position.x += this.viewportBorder;
  89969. position.y += this.viewportBorder;
  89970. this._positionX += this.viewportBorder;
  89971. this._positionY += this.viewportBorder;
  89972. }
  89973. if (position.z > 0) {
  89974. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  89975. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  89976. return true;
  89977. }
  89978. return true;
  89979. }
  89980. return false;
  89981. };
  89982. /** @hidden */
  89983. LensFlareSystem.prototype._isVisible = function () {
  89984. if (!this._isEnabled || !this._scene.activeCamera) {
  89985. return false;
  89986. }
  89987. var emitterPosition = this.getEmitterPosition();
  89988. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  89989. var distance = direction.length();
  89990. direction.normalize();
  89991. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  89992. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  89993. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  89994. };
  89995. LensFlareSystem.prototype.render = function () {
  89996. if (!this._effect.isReady() || !this._scene.activeCamera)
  89997. return false;
  89998. var engine = this._scene.getEngine();
  89999. var viewport = this._scene.activeCamera.viewport;
  90000. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90001. // Position
  90002. if (!this.computeEffectivePosition(globalViewport)) {
  90003. return false;
  90004. }
  90005. // Visibility
  90006. if (!this._isVisible()) {
  90007. return false;
  90008. }
  90009. // Intensity
  90010. var awayX;
  90011. var awayY;
  90012. if (this._positionX < this.borderLimit + globalViewport.x) {
  90013. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90014. }
  90015. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90016. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90017. }
  90018. else {
  90019. awayX = 0;
  90020. }
  90021. if (this._positionY < this.borderLimit + globalViewport.y) {
  90022. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90023. }
  90024. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90025. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90026. }
  90027. else {
  90028. awayY = 0;
  90029. }
  90030. var away = (awayX > awayY) ? awayX : awayY;
  90031. away -= this.viewportBorder;
  90032. if (away > this.borderLimit) {
  90033. away = this.borderLimit;
  90034. }
  90035. var intensity = 1.0 - (away / this.borderLimit);
  90036. if (intensity < 0) {
  90037. return false;
  90038. }
  90039. if (intensity > 1.0) {
  90040. intensity = 1.0;
  90041. }
  90042. if (this.viewportBorder > 0) {
  90043. globalViewport.x += this.viewportBorder;
  90044. globalViewport.y += this.viewportBorder;
  90045. globalViewport.width -= this.viewportBorder * 2;
  90046. globalViewport.height -= this.viewportBorder * 2;
  90047. this._positionX -= this.viewportBorder;
  90048. this._positionY -= this.viewportBorder;
  90049. }
  90050. // Position
  90051. var centerX = globalViewport.x + globalViewport.width / 2;
  90052. var centerY = globalViewport.y + globalViewport.height / 2;
  90053. var distX = centerX - this._positionX;
  90054. var distY = centerY - this._positionY;
  90055. // Effects
  90056. engine.enableEffect(this._effect);
  90057. engine.setState(false);
  90058. engine.setDepthBuffer(false);
  90059. // VBOs
  90060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90061. // Flares
  90062. for (var index = 0; index < this.lensFlares.length; index++) {
  90063. var flare = this.lensFlares[index];
  90064. engine.setAlphaMode(flare.alphaMode);
  90065. var x = centerX - (distX * flare.position);
  90066. var y = centerY - (distY * flare.position);
  90067. var cw = flare.size;
  90068. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90069. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90070. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90071. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90072. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90073. // Texture
  90074. this._effect.setTexture("textureSampler", flare.texture);
  90075. // Color
  90076. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90077. // Draw order
  90078. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90079. }
  90080. engine.setDepthBuffer(true);
  90081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90082. return true;
  90083. };
  90084. LensFlareSystem.prototype.dispose = function () {
  90085. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90086. if (vertexBuffer) {
  90087. vertexBuffer.dispose();
  90088. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90089. }
  90090. if (this._indexBuffer) {
  90091. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90092. this._indexBuffer = null;
  90093. }
  90094. while (this.lensFlares.length) {
  90095. this.lensFlares[0].dispose();
  90096. }
  90097. // Remove from scene
  90098. var index = this._scene.lensFlareSystems.indexOf(this);
  90099. this._scene.lensFlareSystems.splice(index, 1);
  90100. };
  90101. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90102. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90103. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90104. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90105. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90106. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90107. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90108. var parsedFlare = parsedLensFlareSystem.flares[index];
  90109. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90110. }
  90111. return lensFlareSystem;
  90112. };
  90113. LensFlareSystem.prototype.serialize = function () {
  90114. var serializationObject = {};
  90115. serializationObject.id = this.id;
  90116. serializationObject.name = this.name;
  90117. serializationObject.emitterId = this.getEmitter().id;
  90118. serializationObject.borderLimit = this.borderLimit;
  90119. serializationObject.flares = [];
  90120. for (var index = 0; index < this.lensFlares.length; index++) {
  90121. var flare = this.lensFlares[index];
  90122. serializationObject.flares.push({
  90123. size: flare.size,
  90124. position: flare.position,
  90125. color: flare.color.asArray(),
  90126. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90127. });
  90128. }
  90129. return serializationObject;
  90130. };
  90131. return LensFlareSystem;
  90132. }());
  90133. BABYLON.LensFlareSystem = LensFlareSystem;
  90134. })(BABYLON || (BABYLON = {}));
  90135. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90136. var BABYLON;
  90137. (function (BABYLON) {
  90138. /**
  90139. * This is a holder class for the physics joint created by the physics plugin.
  90140. * It holds a set of functions to control the underlying joint.
  90141. */
  90142. var PhysicsJoint = /** @class */ (function () {
  90143. function PhysicsJoint(type, jointData) {
  90144. this.type = type;
  90145. this.jointData = jointData;
  90146. jointData.nativeParams = jointData.nativeParams || {};
  90147. }
  90148. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  90149. get: function () {
  90150. return this._physicsJoint;
  90151. },
  90152. set: function (newJoint) {
  90153. if (this._physicsJoint) {
  90154. //remove from the wolrd
  90155. }
  90156. this._physicsJoint = newJoint;
  90157. },
  90158. enumerable: true,
  90159. configurable: true
  90160. });
  90161. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  90162. set: function (physicsPlugin) {
  90163. this._physicsPlugin = physicsPlugin;
  90164. },
  90165. enumerable: true,
  90166. configurable: true
  90167. });
  90168. /**
  90169. * Execute a function that is physics-plugin specific.
  90170. * @param {Function} func the function that will be executed.
  90171. * It accepts two parameters: the physics world and the physics joint.
  90172. */
  90173. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  90174. func(this._physicsPlugin.world, this._physicsJoint);
  90175. };
  90176. //TODO check if the native joints are the same
  90177. //Joint Types
  90178. PhysicsJoint.DistanceJoint = 0;
  90179. PhysicsJoint.HingeJoint = 1;
  90180. PhysicsJoint.BallAndSocketJoint = 2;
  90181. PhysicsJoint.WheelJoint = 3;
  90182. PhysicsJoint.SliderJoint = 4;
  90183. //OIMO
  90184. PhysicsJoint.PrismaticJoint = 5;
  90185. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  90186. PhysicsJoint.UniversalJoint = 6;
  90187. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  90188. //Cannon
  90189. //Similar to a Ball-Joint. Different in params
  90190. PhysicsJoint.PointToPointJoint = 8;
  90191. //Cannon only at the moment
  90192. PhysicsJoint.SpringJoint = 9;
  90193. PhysicsJoint.LockJoint = 10;
  90194. return PhysicsJoint;
  90195. }());
  90196. BABYLON.PhysicsJoint = PhysicsJoint;
  90197. /**
  90198. * A class representing a physics distance joint.
  90199. */
  90200. var DistanceJoint = /** @class */ (function (_super) {
  90201. __extends(DistanceJoint, _super);
  90202. function DistanceJoint(jointData) {
  90203. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  90204. }
  90205. /**
  90206. * Update the predefined distance.
  90207. */
  90208. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  90209. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  90210. };
  90211. return DistanceJoint;
  90212. }(PhysicsJoint));
  90213. BABYLON.DistanceJoint = DistanceJoint;
  90214. var MotorEnabledJoint = /** @class */ (function (_super) {
  90215. __extends(MotorEnabledJoint, _super);
  90216. function MotorEnabledJoint(type, jointData) {
  90217. return _super.call(this, type, jointData) || this;
  90218. }
  90219. /**
  90220. * Set the motor values.
  90221. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90222. * @param {number} force the force to apply
  90223. * @param {number} maxForce max force for this motor.
  90224. */
  90225. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  90226. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90227. };
  90228. /**
  90229. * Set the motor's limits.
  90230. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90231. */
  90232. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90233. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90234. };
  90235. return MotorEnabledJoint;
  90236. }(PhysicsJoint));
  90237. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  90238. /**
  90239. * This class represents a single hinge physics joint
  90240. */
  90241. var HingeJoint = /** @class */ (function (_super) {
  90242. __extends(HingeJoint, _super);
  90243. function HingeJoint(jointData) {
  90244. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  90245. }
  90246. /**
  90247. * Set the motor values.
  90248. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90249. * @param {number} force the force to apply
  90250. * @param {number} maxForce max force for this motor.
  90251. */
  90252. HingeJoint.prototype.setMotor = function (force, maxForce) {
  90253. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90254. };
  90255. /**
  90256. * Set the motor's limits.
  90257. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90258. */
  90259. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90260. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90261. };
  90262. return HingeJoint;
  90263. }(MotorEnabledJoint));
  90264. BABYLON.HingeJoint = HingeJoint;
  90265. /**
  90266. * This class represents a dual hinge physics joint (same as wheel joint)
  90267. */
  90268. var Hinge2Joint = /** @class */ (function (_super) {
  90269. __extends(Hinge2Joint, _super);
  90270. function Hinge2Joint(jointData) {
  90271. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  90272. }
  90273. /**
  90274. * Set the motor values.
  90275. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90276. * @param {number} force the force to apply
  90277. * @param {number} maxForce max force for this motor.
  90278. * @param {motorIndex} the motor's index, 0 or 1.
  90279. */
  90280. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  90281. if (motorIndex === void 0) { motorIndex = 0; }
  90282. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  90283. };
  90284. /**
  90285. * Set the motor limits.
  90286. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90287. * @param {number} upperLimit the upper limit
  90288. * @param {number} lowerLimit lower limit
  90289. * @param {motorIndex} the motor's index, 0 or 1.
  90290. */
  90291. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  90292. if (motorIndex === void 0) { motorIndex = 0; }
  90293. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  90294. };
  90295. return Hinge2Joint;
  90296. }(MotorEnabledJoint));
  90297. BABYLON.Hinge2Joint = Hinge2Joint;
  90298. })(BABYLON || (BABYLON = {}));
  90299. //# sourceMappingURL=babylon.physicsJoint.js.map
  90300. var BABYLON;
  90301. (function (BABYLON) {
  90302. var PhysicsImpostor = /** @class */ (function () {
  90303. function PhysicsImpostor(object, type, _options, _scene) {
  90304. if (_options === void 0) { _options = { mass: 0 }; }
  90305. var _this = this;
  90306. this.object = object;
  90307. this.type = type;
  90308. this._options = _options;
  90309. this._scene = _scene;
  90310. this._bodyUpdateRequired = false;
  90311. this._onBeforePhysicsStepCallbacks = new Array();
  90312. this._onAfterPhysicsStepCallbacks = new Array();
  90313. this._onPhysicsCollideCallbacks = [];
  90314. this._deltaPosition = BABYLON.Vector3.Zero();
  90315. this._isDisposed = false;
  90316. //temp variables for parent rotation calculations
  90317. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  90318. this._tmpQuat = new BABYLON.Quaternion();
  90319. this._tmpQuat2 = new BABYLON.Quaternion();
  90320. /**
  90321. * this function is executed by the physics engine.
  90322. */
  90323. this.beforeStep = function () {
  90324. if (!_this._physicsEngine) {
  90325. return;
  90326. }
  90327. _this.object.translate(_this._deltaPosition, -1);
  90328. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  90329. _this.object.computeWorldMatrix(false);
  90330. if (_this.object.parent && _this.object.rotationQuaternion) {
  90331. _this.getParentsRotation();
  90332. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  90333. }
  90334. else {
  90335. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  90336. }
  90337. if (!_this._options.disableBidirectionalTransformation) {
  90338. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  90339. }
  90340. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  90341. func(_this);
  90342. });
  90343. };
  90344. /**
  90345. * this function is executed by the physics engine.
  90346. */
  90347. this.afterStep = function () {
  90348. if (!_this._physicsEngine) {
  90349. return;
  90350. }
  90351. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  90352. func(_this);
  90353. });
  90354. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  90355. // object has now its world rotation. needs to be converted to local.
  90356. if (_this.object.parent && _this.object.rotationQuaternion) {
  90357. _this.getParentsRotation();
  90358. _this._tmpQuat.conjugateInPlace();
  90359. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  90360. }
  90361. // take the position set and make it the absolute position of this object.
  90362. _this.object.setAbsolutePosition(_this.object.position);
  90363. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  90364. _this.object.translate(_this._deltaPosition, 1);
  90365. };
  90366. /**
  90367. * Legacy collision detection event support
  90368. */
  90369. this.onCollideEvent = null;
  90370. //event and body object due to cannon's event-based architecture.
  90371. this.onCollide = function (e) {
  90372. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  90373. return;
  90374. }
  90375. if (!_this._physicsEngine) {
  90376. return;
  90377. }
  90378. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  90379. if (otherImpostor) {
  90380. // Legacy collision detection event support
  90381. if (_this.onCollideEvent) {
  90382. _this.onCollideEvent(_this, otherImpostor);
  90383. }
  90384. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  90385. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  90386. }).forEach(function (obj) {
  90387. obj.callback(_this, otherImpostor);
  90388. });
  90389. }
  90390. };
  90391. //sanity check!
  90392. if (!this.object) {
  90393. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  90394. return;
  90395. }
  90396. //legacy support for old syntax.
  90397. if (!this._scene && object.getScene) {
  90398. this._scene = object.getScene();
  90399. }
  90400. if (!this._scene) {
  90401. return;
  90402. }
  90403. this._physicsEngine = this._scene.getPhysicsEngine();
  90404. if (!this._physicsEngine) {
  90405. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  90406. }
  90407. else {
  90408. //set the object's quaternion, if not set
  90409. if (!this.object.rotationQuaternion) {
  90410. if (this.object.rotation) {
  90411. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  90412. }
  90413. else {
  90414. this.object.rotationQuaternion = new BABYLON.Quaternion();
  90415. }
  90416. }
  90417. //default options params
  90418. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  90419. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  90420. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  90421. this._joints = [];
  90422. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  90423. if (!this.object.parent || this._options.ignoreParent) {
  90424. this._init();
  90425. }
  90426. else if (this.object.parent.physicsImpostor) {
  90427. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  90428. }
  90429. }
  90430. }
  90431. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  90432. get: function () {
  90433. return this._isDisposed;
  90434. },
  90435. enumerable: true,
  90436. configurable: true
  90437. });
  90438. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  90439. get: function () {
  90440. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  90441. },
  90442. set: function (value) {
  90443. this.setMass(value);
  90444. },
  90445. enumerable: true,
  90446. configurable: true
  90447. });
  90448. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  90449. get: function () {
  90450. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  90451. },
  90452. set: function (value) {
  90453. if (!this._physicsEngine) {
  90454. return;
  90455. }
  90456. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  90457. },
  90458. enumerable: true,
  90459. configurable: true
  90460. });
  90461. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  90462. get: function () {
  90463. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  90464. },
  90465. set: function (value) {
  90466. if (!this._physicsEngine) {
  90467. return;
  90468. }
  90469. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  90470. },
  90471. enumerable: true,
  90472. configurable: true
  90473. });
  90474. /**
  90475. * This function will completly initialize this impostor.
  90476. * It will create a new body - but only if this mesh has no parent.
  90477. * If it has, this impostor will not be used other than to define the impostor
  90478. * of the child mesh.
  90479. * @hidden
  90480. */
  90481. PhysicsImpostor.prototype._init = function () {
  90482. if (!this._physicsEngine) {
  90483. return;
  90484. }
  90485. this._physicsEngine.removeImpostor(this);
  90486. this.physicsBody = null;
  90487. this._parent = this._parent || this._getPhysicsParent();
  90488. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  90489. this._physicsEngine.addImpostor(this);
  90490. }
  90491. };
  90492. PhysicsImpostor.prototype._getPhysicsParent = function () {
  90493. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  90494. var parentMesh = this.object.parent;
  90495. return parentMesh.physicsImpostor;
  90496. }
  90497. return null;
  90498. };
  90499. /**
  90500. * Should a new body be generated.
  90501. */
  90502. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  90503. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  90504. };
  90505. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  90506. this.forceUpdate();
  90507. };
  90508. /**
  90509. * Force a regeneration of this or the parent's impostor's body.
  90510. * Use under cautious - This will remove all joints already implemented.
  90511. */
  90512. PhysicsImpostor.prototype.forceUpdate = function () {
  90513. this._init();
  90514. if (this.parent && !this._options.ignoreParent) {
  90515. this.parent.forceUpdate();
  90516. }
  90517. };
  90518. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  90519. /*public get mesh(): AbstractMesh {
  90520. return this._mesh;
  90521. }*/
  90522. /**
  90523. * Gets the body that holds this impostor. Either its own, or its parent.
  90524. */
  90525. get: function () {
  90526. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  90527. },
  90528. /**
  90529. * Set the physics body. Used mainly by the physics engine/plugin
  90530. */
  90531. set: function (physicsBody) {
  90532. if (this._physicsBody && this._physicsEngine) {
  90533. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  90534. }
  90535. this._physicsBody = physicsBody;
  90536. this.resetUpdateFlags();
  90537. },
  90538. enumerable: true,
  90539. configurable: true
  90540. });
  90541. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  90542. get: function () {
  90543. return !this._options.ignoreParent && this._parent ? this._parent : null;
  90544. },
  90545. set: function (value) {
  90546. this._parent = value;
  90547. },
  90548. enumerable: true,
  90549. configurable: true
  90550. });
  90551. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  90552. this._bodyUpdateRequired = false;
  90553. };
  90554. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  90555. if (this.object.getBoundingInfo) {
  90556. var q = this.object.rotationQuaternion;
  90557. //reset rotation
  90558. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  90559. //calculate the world matrix with no rotation
  90560. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90561. var boundingInfo = this.object.getBoundingInfo();
  90562. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  90563. //bring back the rotation
  90564. this.object.rotationQuaternion = q;
  90565. //calculate the world matrix with the new rotation
  90566. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90567. return size;
  90568. }
  90569. else {
  90570. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  90571. }
  90572. };
  90573. PhysicsImpostor.prototype.getObjectCenter = function () {
  90574. if (this.object.getBoundingInfo) {
  90575. var boundingInfo = this.object.getBoundingInfo();
  90576. return boundingInfo.boundingBox.centerWorld;
  90577. }
  90578. else {
  90579. return this.object.position;
  90580. }
  90581. };
  90582. /**
  90583. * Get a specific parametes from the options parameter.
  90584. */
  90585. PhysicsImpostor.prototype.getParam = function (paramName) {
  90586. return this._options[paramName];
  90587. };
  90588. /**
  90589. * Sets a specific parameter in the options given to the physics plugin
  90590. */
  90591. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  90592. this._options[paramName] = value;
  90593. this._bodyUpdateRequired = true;
  90594. };
  90595. /**
  90596. * Specifically change the body's mass option. Won't recreate the physics body object
  90597. */
  90598. PhysicsImpostor.prototype.setMass = function (mass) {
  90599. if (this.getParam("mass") !== mass) {
  90600. this.setParam("mass", mass);
  90601. }
  90602. if (this._physicsEngine) {
  90603. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  90604. }
  90605. };
  90606. PhysicsImpostor.prototype.getLinearVelocity = function () {
  90607. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  90608. };
  90609. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  90610. if (this._physicsEngine) {
  90611. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  90612. }
  90613. };
  90614. PhysicsImpostor.prototype.getAngularVelocity = function () {
  90615. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  90616. };
  90617. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  90618. if (this._physicsEngine) {
  90619. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  90620. }
  90621. };
  90622. /**
  90623. * Execute a function with the physics plugin native code.
  90624. * Provide a function the will have two variables - the world object and the physics body object.
  90625. */
  90626. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  90627. if (this._physicsEngine) {
  90628. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  90629. }
  90630. };
  90631. /**
  90632. * Register a function that will be executed before the physics world is stepping forward.
  90633. */
  90634. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  90635. this._onBeforePhysicsStepCallbacks.push(func);
  90636. };
  90637. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  90638. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  90639. if (index > -1) {
  90640. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  90641. }
  90642. else {
  90643. BABYLON.Tools.Warn("Function to remove was not found");
  90644. }
  90645. };
  90646. /**
  90647. * Register a function that will be executed after the physics step
  90648. */
  90649. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  90650. this._onAfterPhysicsStepCallbacks.push(func);
  90651. };
  90652. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  90653. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  90654. if (index > -1) {
  90655. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  90656. }
  90657. else {
  90658. BABYLON.Tools.Warn("Function to remove was not found");
  90659. }
  90660. };
  90661. /**
  90662. * register a function that will be executed when this impostor collides against a different body.
  90663. */
  90664. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  90665. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90666. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  90667. };
  90668. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  90669. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90670. var index = -1;
  90671. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  90672. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  90673. // chcek the arrays match
  90674. var sameList = cbDef.otherImpostors.every(function (impostor) {
  90675. return collidedAgainstList.indexOf(impostor) > -1;
  90676. });
  90677. if (sameList) {
  90678. index = idx;
  90679. }
  90680. return sameList;
  90681. }
  90682. return false;
  90683. });
  90684. if (found) {
  90685. this._onPhysicsCollideCallbacks.splice(index, 1);
  90686. }
  90687. else {
  90688. BABYLON.Tools.Warn("Function to remove was not found");
  90689. }
  90690. };
  90691. PhysicsImpostor.prototype.getParentsRotation = function () {
  90692. var parent = this.object.parent;
  90693. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  90694. while (parent) {
  90695. if (parent.rotationQuaternion) {
  90696. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  90697. }
  90698. else {
  90699. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  90700. }
  90701. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  90702. parent = parent.parent;
  90703. }
  90704. return this._tmpQuat;
  90705. };
  90706. /**
  90707. * Apply a force
  90708. */
  90709. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  90710. if (this._physicsEngine) {
  90711. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  90712. }
  90713. return this;
  90714. };
  90715. /**
  90716. * Apply an impulse
  90717. */
  90718. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  90719. if (this._physicsEngine) {
  90720. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  90721. }
  90722. return this;
  90723. };
  90724. /**
  90725. * A help function to create a joint.
  90726. */
  90727. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  90728. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  90729. this.addJoint(otherImpostor, joint);
  90730. return this;
  90731. };
  90732. /**
  90733. * Add a joint to this impostor with a different impostor.
  90734. */
  90735. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  90736. this._joints.push({
  90737. otherImpostor: otherImpostor,
  90738. joint: joint
  90739. });
  90740. if (this._physicsEngine) {
  90741. this._physicsEngine.addJoint(this, otherImpostor, joint);
  90742. }
  90743. return this;
  90744. };
  90745. /**
  90746. * Will keep this body still, in a sleep mode.
  90747. */
  90748. PhysicsImpostor.prototype.sleep = function () {
  90749. if (this._physicsEngine) {
  90750. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  90751. }
  90752. return this;
  90753. };
  90754. /**
  90755. * Wake the body up.
  90756. */
  90757. PhysicsImpostor.prototype.wakeUp = function () {
  90758. if (this._physicsEngine) {
  90759. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  90760. }
  90761. return this;
  90762. };
  90763. PhysicsImpostor.prototype.clone = function (newObject) {
  90764. if (!newObject)
  90765. return null;
  90766. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  90767. };
  90768. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  90769. var _this = this;
  90770. //no dispose if no physics engine is available.
  90771. if (!this._physicsEngine) {
  90772. return;
  90773. }
  90774. this._joints.forEach(function (j) {
  90775. if (_this._physicsEngine) {
  90776. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  90777. }
  90778. });
  90779. //dispose the physics body
  90780. this._physicsEngine.removeImpostor(this);
  90781. if (this.parent) {
  90782. this.parent.forceUpdate();
  90783. }
  90784. else {
  90785. /*this._object.getChildMeshes().forEach(function(mesh) {
  90786. if (mesh.physicsImpostor) {
  90787. if (disposeChildren) {
  90788. mesh.physicsImpostor.dispose();
  90789. mesh.physicsImpostor = null;
  90790. }
  90791. }
  90792. })*/
  90793. }
  90794. this._isDisposed = true;
  90795. };
  90796. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  90797. this._deltaPosition.copyFrom(position);
  90798. };
  90799. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  90800. if (!this._deltaRotation) {
  90801. this._deltaRotation = new BABYLON.Quaternion();
  90802. }
  90803. this._deltaRotation.copyFrom(rotation);
  90804. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  90805. };
  90806. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  90807. if (this._physicsEngine) {
  90808. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  90809. }
  90810. return this;
  90811. };
  90812. PhysicsImpostor.prototype.getRadius = function () {
  90813. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  90814. };
  90815. /**
  90816. * Sync a bone with this impostor
  90817. * @param bone The bone to sync to the impostor.
  90818. * @param boneMesh The mesh that the bone is influencing.
  90819. * @param jointPivot The pivot of the joint / bone in local space.
  90820. * @param distToJoint Optional distance from the impostor to the joint.
  90821. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90822. */
  90823. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  90824. var tempVec = PhysicsImpostor._tmpVecs[0];
  90825. var mesh = this.object;
  90826. if (mesh.rotationQuaternion) {
  90827. if (adjustRotation) {
  90828. var tempQuat = PhysicsImpostor._tmpQuat;
  90829. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  90830. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  90831. }
  90832. else {
  90833. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  90834. }
  90835. }
  90836. tempVec.x = 0;
  90837. tempVec.y = 0;
  90838. tempVec.z = 0;
  90839. if (jointPivot) {
  90840. tempVec.x = jointPivot.x;
  90841. tempVec.y = jointPivot.y;
  90842. tempVec.z = jointPivot.z;
  90843. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  90844. if (distToJoint === undefined || distToJoint === null) {
  90845. distToJoint = jointPivot.length();
  90846. }
  90847. tempVec.x *= distToJoint;
  90848. tempVec.y *= distToJoint;
  90849. tempVec.z *= distToJoint;
  90850. }
  90851. if (bone.getParent()) {
  90852. tempVec.addInPlace(mesh.getAbsolutePosition());
  90853. bone.setAbsolutePosition(tempVec, boneMesh);
  90854. }
  90855. else {
  90856. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  90857. boneMesh.position.x -= tempVec.x;
  90858. boneMesh.position.y -= tempVec.y;
  90859. boneMesh.position.z -= tempVec.z;
  90860. }
  90861. };
  90862. /**
  90863. * Sync impostor to a bone
  90864. * @param bone The bone that the impostor will be synced to.
  90865. * @param boneMesh The mesh that the bone is influencing.
  90866. * @param jointPivot The pivot of the joint / bone in local space.
  90867. * @param distToJoint Optional distance from the impostor to the joint.
  90868. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90869. * @param boneAxis Optional vector3 axis the bone is aligned with
  90870. */
  90871. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  90872. var mesh = this.object;
  90873. if (mesh.rotationQuaternion) {
  90874. if (adjustRotation) {
  90875. var tempQuat = PhysicsImpostor._tmpQuat;
  90876. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  90877. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  90878. }
  90879. else {
  90880. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  90881. }
  90882. }
  90883. var pos = PhysicsImpostor._tmpVecs[0];
  90884. var boneDir = PhysicsImpostor._tmpVecs[1];
  90885. if (!boneAxis) {
  90886. boneAxis = PhysicsImpostor._tmpVecs[2];
  90887. boneAxis.x = 0;
  90888. boneAxis.y = 1;
  90889. boneAxis.z = 0;
  90890. }
  90891. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  90892. bone.getAbsolutePositionToRef(boneMesh, pos);
  90893. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  90894. distToJoint = jointPivot.length();
  90895. }
  90896. if (distToJoint !== undefined && distToJoint !== null) {
  90897. pos.x += boneDir.x * distToJoint;
  90898. pos.y += boneDir.y * distToJoint;
  90899. pos.z += boneDir.z * distToJoint;
  90900. }
  90901. mesh.setAbsolutePosition(pos);
  90902. };
  90903. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  90904. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  90905. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90906. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  90907. //Impostor types
  90908. PhysicsImpostor.NoImpostor = 0;
  90909. PhysicsImpostor.SphereImpostor = 1;
  90910. PhysicsImpostor.BoxImpostor = 2;
  90911. PhysicsImpostor.PlaneImpostor = 3;
  90912. PhysicsImpostor.MeshImpostor = 4;
  90913. PhysicsImpostor.CylinderImpostor = 7;
  90914. PhysicsImpostor.ParticleImpostor = 8;
  90915. PhysicsImpostor.HeightmapImpostor = 9;
  90916. return PhysicsImpostor;
  90917. }());
  90918. BABYLON.PhysicsImpostor = PhysicsImpostor;
  90919. })(BABYLON || (BABYLON = {}));
  90920. //# sourceMappingURL=babylon.physicsImpostor.js.map
  90921. var BABYLON;
  90922. (function (BABYLON) {
  90923. /**
  90924. * Class used to control physics engine
  90925. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90926. */
  90927. var PhysicsEngine = /** @class */ (function () {
  90928. /**
  90929. * Creates a new Physics Engine
  90930. * @param gravity defines the gravity vector used by the simulation
  90931. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  90932. */
  90933. function PhysicsEngine(gravity, _physicsPlugin) {
  90934. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  90935. this._physicsPlugin = _physicsPlugin;
  90936. this._impostors = [];
  90937. this._joints = [];
  90938. if (!this._physicsPlugin.isSupported()) {
  90939. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  90940. + "Please make sure it is included.");
  90941. }
  90942. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  90943. this.setGravity(gravity);
  90944. this.setTimeStep();
  90945. }
  90946. /**
  90947. * Sets the gravity vector used by the simulation
  90948. * @param gravity defines the gravity vector to use
  90949. */
  90950. PhysicsEngine.prototype.setGravity = function (gravity) {
  90951. this.gravity = gravity;
  90952. this._physicsPlugin.setGravity(this.gravity);
  90953. };
  90954. /**
  90955. * Set the time step of the physics engine.
  90956. * Default is 1/60.
  90957. * To slow it down, enter 1/600 for example.
  90958. * To speed it up, 1/30
  90959. * @param newTimeStep defines the new timestep to apply to this world.
  90960. */
  90961. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  90962. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  90963. this._physicsPlugin.setTimeStep(newTimeStep);
  90964. };
  90965. /**
  90966. * Get the time step of the physics engine.
  90967. * @returns the current time step
  90968. */
  90969. PhysicsEngine.prototype.getTimeStep = function () {
  90970. return this._physicsPlugin.getTimeStep();
  90971. };
  90972. /**
  90973. * Release all resources
  90974. */
  90975. PhysicsEngine.prototype.dispose = function () {
  90976. this._impostors.forEach(function (impostor) {
  90977. impostor.dispose();
  90978. });
  90979. this._physicsPlugin.dispose();
  90980. };
  90981. /**
  90982. * Gets the name of the current physics plugin
  90983. * @returns the name of the plugin
  90984. */
  90985. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  90986. return this._physicsPlugin.name;
  90987. };
  90988. /**
  90989. * Adding a new impostor for the impostor tracking.
  90990. * This will be done by the impostor itself.
  90991. * @param impostor the impostor to add
  90992. */
  90993. PhysicsEngine.prototype.addImpostor = function (impostor) {
  90994. impostor.uniqueId = this._impostors.push(impostor);
  90995. //if no parent, generate the body
  90996. if (!impostor.parent) {
  90997. this._physicsPlugin.generatePhysicsBody(impostor);
  90998. }
  90999. };
  91000. /**
  91001. * Remove an impostor from the engine.
  91002. * This impostor and its mesh will not longer be updated by the physics engine.
  91003. * @param impostor the impostor to remove
  91004. */
  91005. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91006. var index = this._impostors.indexOf(impostor);
  91007. if (index > -1) {
  91008. var removed = this._impostors.splice(index, 1);
  91009. //Is it needed?
  91010. if (removed.length) {
  91011. //this will also remove it from the world.
  91012. removed[0].physicsBody = null;
  91013. }
  91014. }
  91015. };
  91016. /**
  91017. * Add a joint to the physics engine
  91018. * @param mainImpostor defines the main impostor to which the joint is added.
  91019. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91020. * @param joint defines the joint that will connect both impostors.
  91021. */
  91022. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91023. var impostorJoint = {
  91024. mainImpostor: mainImpostor,
  91025. connectedImpostor: connectedImpostor,
  91026. joint: joint
  91027. };
  91028. joint.physicsPlugin = this._physicsPlugin;
  91029. this._joints.push(impostorJoint);
  91030. this._physicsPlugin.generateJoint(impostorJoint);
  91031. };
  91032. /**
  91033. * Removes a joint from the simulation
  91034. * @param mainImpostor defines the impostor used with the joint
  91035. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91036. * @param joint defines the joint to remove
  91037. */
  91038. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91039. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91040. return (impostorJoint.connectedImpostor === connectedImpostor
  91041. && impostorJoint.joint === joint
  91042. && impostorJoint.mainImpostor === mainImpostor);
  91043. });
  91044. if (matchingJoints.length) {
  91045. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91046. //TODO remove it from the list as well
  91047. }
  91048. };
  91049. /**
  91050. * Called by the scene. No need to call it.
  91051. * @param delta defines the timespam between frames
  91052. */
  91053. PhysicsEngine.prototype._step = function (delta) {
  91054. var _this = this;
  91055. //check if any mesh has no body / requires an update
  91056. this._impostors.forEach(function (impostor) {
  91057. if (impostor.isBodyInitRequired()) {
  91058. _this._physicsPlugin.generatePhysicsBody(impostor);
  91059. }
  91060. });
  91061. if (delta > 0.1) {
  91062. delta = 0.1;
  91063. }
  91064. else if (delta <= 0) {
  91065. delta = 1.0 / 60.0;
  91066. }
  91067. this._physicsPlugin.executeStep(delta, this._impostors);
  91068. };
  91069. /**
  91070. * Gets the current plugin used to run the simulation
  91071. * @returns current plugin
  91072. */
  91073. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91074. return this._physicsPlugin;
  91075. };
  91076. /**
  91077. * Gets the list of physic impostors
  91078. * @returns an array of PhysicsImpostor
  91079. */
  91080. PhysicsEngine.prototype.getImpostors = function () {
  91081. return this._impostors;
  91082. };
  91083. /**
  91084. * Gets the impostor for a physics enabled object
  91085. * @param object defines the object impersonated by the impostor
  91086. * @returns the PhysicsImpostor or null if not found
  91087. */
  91088. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91089. for (var i = 0; i < this._impostors.length; ++i) {
  91090. if (this._impostors[i].object === object) {
  91091. return this._impostors[i];
  91092. }
  91093. }
  91094. return null;
  91095. };
  91096. /**
  91097. * Gets the impostor for a physics body object
  91098. * @param body defines physics body used by the impostor
  91099. * @returns the PhysicsImpostor or null if not found
  91100. */
  91101. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91102. for (var i = 0; i < this._impostors.length; ++i) {
  91103. if (this._impostors[i].physicsBody === body) {
  91104. return this._impostors[i];
  91105. }
  91106. }
  91107. return null;
  91108. };
  91109. /**
  91110. * Global value used to control the smallest number supported by the simulation
  91111. */
  91112. PhysicsEngine.Epsilon = 0.001;
  91113. return PhysicsEngine;
  91114. }());
  91115. BABYLON.PhysicsEngine = PhysicsEngine;
  91116. })(BABYLON || (BABYLON = {}));
  91117. //# sourceMappingURL=babylon.physicsEngine.js.map
  91118. var BABYLON;
  91119. (function (BABYLON) {
  91120. var PhysicsHelper = /** @class */ (function () {
  91121. function PhysicsHelper(scene) {
  91122. this._scene = scene;
  91123. this._physicsEngine = this._scene.getPhysicsEngine();
  91124. if (!this._physicsEngine) {
  91125. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91126. }
  91127. }
  91128. /**
  91129. * @param {Vector3} origin the origin of the explosion
  91130. * @param {number} radius the explosion radius
  91131. * @param {number} strength the explosion strength
  91132. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91133. */
  91134. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91135. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91136. if (!this._physicsEngine) {
  91137. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91138. return null;
  91139. }
  91140. var impostors = this._physicsEngine.getImpostors();
  91141. if (impostors.length === 0) {
  91142. return null;
  91143. }
  91144. var event = new PhysicsRadialExplosionEvent(this._scene);
  91145. impostors.forEach(function (impostor) {
  91146. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91147. if (!impostorForceAndContactPoint) {
  91148. return;
  91149. }
  91150. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91151. });
  91152. event.dispose(false);
  91153. return event;
  91154. };
  91155. /**
  91156. * @param {Vector3} origin the origin of the explosion
  91157. * @param {number} radius the explosion radius
  91158. * @param {number} strength the explosion strength
  91159. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91160. */
  91161. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  91162. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91163. if (!this._physicsEngine) {
  91164. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91165. return null;
  91166. }
  91167. var impostors = this._physicsEngine.getImpostors();
  91168. if (impostors.length === 0) {
  91169. return null;
  91170. }
  91171. var event = new PhysicsRadialExplosionEvent(this._scene);
  91172. impostors.forEach(function (impostor) {
  91173. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  91174. if (!impostorForceAndContactPoint) {
  91175. return;
  91176. }
  91177. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91178. });
  91179. event.dispose(false);
  91180. return event;
  91181. };
  91182. /**
  91183. * @param {Vector3} origin the origin of the explosion
  91184. * @param {number} radius the explosion radius
  91185. * @param {number} strength the explosion strength
  91186. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91187. */
  91188. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  91189. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91190. if (!this._physicsEngine) {
  91191. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91192. return null;
  91193. }
  91194. var impostors = this._physicsEngine.getImpostors();
  91195. if (impostors.length === 0) {
  91196. return null;
  91197. }
  91198. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  91199. event.dispose(false);
  91200. return event;
  91201. };
  91202. /**
  91203. * @param {Vector3} origin the origin of the updraft
  91204. * @param {number} radius the radius of the updraft
  91205. * @param {number} strength the strength of the updraft
  91206. * @param {number} height the height of the updraft
  91207. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  91208. */
  91209. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  91210. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  91211. if (!this._physicsEngine) {
  91212. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91213. return null;
  91214. }
  91215. if (this._physicsEngine.getImpostors().length === 0) {
  91216. return null;
  91217. }
  91218. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  91219. event.dispose(false);
  91220. return event;
  91221. };
  91222. /**
  91223. * @param {Vector3} origin the of the vortex
  91224. * @param {number} radius the radius of the vortex
  91225. * @param {number} strength the strength of the vortex
  91226. * @param {number} height the height of the vortex
  91227. */
  91228. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  91229. if (!this._physicsEngine) {
  91230. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91231. return null;
  91232. }
  91233. if (this._physicsEngine.getImpostors().length === 0) {
  91234. return null;
  91235. }
  91236. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  91237. event.dispose(false);
  91238. return event;
  91239. };
  91240. return PhysicsHelper;
  91241. }());
  91242. BABYLON.PhysicsHelper = PhysicsHelper;
  91243. /***** Radial explosion *****/
  91244. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  91245. function PhysicsRadialExplosionEvent(scene) {
  91246. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  91247. this._rays = [];
  91248. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  91249. this._scene = scene;
  91250. }
  91251. /**
  91252. * Returns the data related to the radial explosion event (sphere & rays).
  91253. * @returns {PhysicsRadialExplosionEventData}
  91254. */
  91255. PhysicsRadialExplosionEvent.prototype.getData = function () {
  91256. this._dataFetched = true;
  91257. return {
  91258. sphere: this._sphere,
  91259. rays: this._rays,
  91260. };
  91261. };
  91262. /**
  91263. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  91264. * @param impostor
  91265. * @param {Vector3} origin the origin of the explosion
  91266. * @param {number} radius the explosion radius
  91267. * @param {number} strength the explosion strength
  91268. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  91269. * @returns {Nullable<PhysicsForceAndContactPoint>}
  91270. */
  91271. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  91272. if (impostor.mass === 0) {
  91273. return null;
  91274. }
  91275. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  91276. return null;
  91277. }
  91278. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91279. return null;
  91280. }
  91281. var impostorObjectCenter = impostor.getObjectCenter();
  91282. var direction = impostorObjectCenter.subtract(origin);
  91283. var ray = new BABYLON.Ray(origin, direction, radius);
  91284. this._rays.push(ray);
  91285. var hit = ray.intersectsMesh(impostor.object);
  91286. var contactPoint = hit.pickedPoint;
  91287. if (!contactPoint) {
  91288. return null;
  91289. }
  91290. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  91291. if (distanceFromOrigin > radius) {
  91292. return null;
  91293. }
  91294. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  91295. ? strength
  91296. : strength * (1 - (distanceFromOrigin / radius));
  91297. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91298. return { force: force, contactPoint: contactPoint };
  91299. };
  91300. /**
  91301. * Disposes the sphere.
  91302. * @param {bolean} force
  91303. */
  91304. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  91305. var _this = this;
  91306. if (force === void 0) { force = true; }
  91307. if (force) {
  91308. this._sphere.dispose();
  91309. }
  91310. else {
  91311. setTimeout(function () {
  91312. if (!_this._dataFetched) {
  91313. _this._sphere.dispose();
  91314. }
  91315. }, 0);
  91316. }
  91317. };
  91318. /*** Helpers ***/
  91319. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  91320. if (!this._sphere) {
  91321. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  91322. this._sphere.isVisible = false;
  91323. }
  91324. };
  91325. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  91326. var impostorObject = impostor.object;
  91327. this._prepareSphere();
  91328. this._sphere.position = origin;
  91329. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  91330. this._sphere._updateBoundingInfo();
  91331. this._sphere.computeWorldMatrix(true);
  91332. return this._sphere.intersectsMesh(impostorObject, true);
  91333. };
  91334. return PhysicsRadialExplosionEvent;
  91335. }());
  91336. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  91337. /***** Gravitational Field *****/
  91338. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  91339. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  91340. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91341. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91342. this._physicsHelper = physicsHelper;
  91343. this._scene = scene;
  91344. this._origin = origin;
  91345. this._radius = radius;
  91346. this._strength = strength;
  91347. this._falloff = falloff;
  91348. this._tickCallback = this._tick.bind(this);
  91349. }
  91350. /**
  91351. * Returns the data related to the gravitational field event (sphere).
  91352. * @returns {PhysicsGravitationalFieldEventData}
  91353. */
  91354. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  91355. this._dataFetched = true;
  91356. return {
  91357. sphere: this._sphere,
  91358. };
  91359. };
  91360. /**
  91361. * Enables the gravitational field.
  91362. */
  91363. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  91364. this._tickCallback.call(this);
  91365. this._scene.registerBeforeRender(this._tickCallback);
  91366. };
  91367. /**
  91368. * Disables the gravitational field.
  91369. */
  91370. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  91371. this._scene.unregisterBeforeRender(this._tickCallback);
  91372. };
  91373. /**
  91374. * Disposes the sphere.
  91375. * @param {bolean} force
  91376. */
  91377. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  91378. var _this = this;
  91379. if (force === void 0) { force = true; }
  91380. if (force) {
  91381. this._sphere.dispose();
  91382. }
  91383. else {
  91384. setTimeout(function () {
  91385. if (!_this._dataFetched) {
  91386. _this._sphere.dispose();
  91387. }
  91388. }, 0);
  91389. }
  91390. };
  91391. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  91392. // Since the params won't change, we fetch the event only once
  91393. if (this._sphere) {
  91394. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91395. }
  91396. else {
  91397. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91398. if (radialExplosionEvent) {
  91399. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  91400. }
  91401. }
  91402. };
  91403. return PhysicsGravitationalFieldEvent;
  91404. }());
  91405. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  91406. /***** Updraft *****/
  91407. var PhysicsUpdraftEvent = /** @class */ (function () {
  91408. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  91409. this._scene = _scene;
  91410. this._origin = _origin;
  91411. this._radius = _radius;
  91412. this._strength = _strength;
  91413. this._height = _height;
  91414. this._updraftMode = _updraftMode;
  91415. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91416. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  91417. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91418. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91419. this._physicsEngine = this._scene.getPhysicsEngine();
  91420. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91421. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91422. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91423. this._originDirection = this._origin.subtract(this._originTop).normalize();
  91424. }
  91425. this._tickCallback = this._tick.bind(this);
  91426. }
  91427. /**
  91428. * Returns the data related to the updraft event (cylinder).
  91429. * @returns {PhysicsUpdraftEventData}
  91430. */
  91431. PhysicsUpdraftEvent.prototype.getData = function () {
  91432. this._dataFetched = true;
  91433. return {
  91434. cylinder: this._cylinder,
  91435. };
  91436. };
  91437. /**
  91438. * Enables the updraft.
  91439. */
  91440. PhysicsUpdraftEvent.prototype.enable = function () {
  91441. this._tickCallback.call(this);
  91442. this._scene.registerBeforeRender(this._tickCallback);
  91443. };
  91444. /**
  91445. * Disables the cortex.
  91446. */
  91447. PhysicsUpdraftEvent.prototype.disable = function () {
  91448. this._scene.unregisterBeforeRender(this._tickCallback);
  91449. };
  91450. /**
  91451. * Disposes the sphere.
  91452. * @param {bolean} force
  91453. */
  91454. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  91455. var _this = this;
  91456. if (force === void 0) { force = true; }
  91457. if (force) {
  91458. this._cylinder.dispose();
  91459. }
  91460. else {
  91461. setTimeout(function () {
  91462. if (!_this._dataFetched) {
  91463. _this._cylinder.dispose();
  91464. }
  91465. }, 0);
  91466. }
  91467. };
  91468. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91469. if (impostor.mass === 0) {
  91470. return null;
  91471. }
  91472. if (!this._intersectsWithCylinder(impostor)) {
  91473. return null;
  91474. }
  91475. var impostorObjectCenter = impostor.getObjectCenter();
  91476. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91477. var direction = this._originDirection;
  91478. }
  91479. else {
  91480. var direction = impostorObjectCenter.subtract(this._originTop);
  91481. }
  91482. var multiplier = this._strength * -1;
  91483. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91484. return { force: force, contactPoint: impostorObjectCenter };
  91485. };
  91486. PhysicsUpdraftEvent.prototype._tick = function () {
  91487. var _this = this;
  91488. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91489. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91490. if (!impostorForceAndContactPoint) {
  91491. return;
  91492. }
  91493. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91494. });
  91495. };
  91496. /*** Helpers ***/
  91497. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  91498. if (!this._cylinder) {
  91499. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  91500. height: this._height,
  91501. diameter: this._radius * 2,
  91502. }, this._scene);
  91503. this._cylinder.isVisible = false;
  91504. }
  91505. };
  91506. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  91507. var impostorObject = impostor.object;
  91508. this._prepareCylinder();
  91509. this._cylinder.position = this._cylinderPosition;
  91510. return this._cylinder.intersectsMesh(impostorObject, true);
  91511. };
  91512. return PhysicsUpdraftEvent;
  91513. }());
  91514. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  91515. /***** Vortex *****/
  91516. var PhysicsVortexEvent = /** @class */ (function () {
  91517. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  91518. this._scene = _scene;
  91519. this._origin = _origin;
  91520. this._radius = _radius;
  91521. this._strength = _strength;
  91522. this._height = _height;
  91523. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91524. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  91525. this._updraftMultiplier = 0.02;
  91526. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91527. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91528. this._physicsEngine = this._scene.getPhysicsEngine();
  91529. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91530. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91531. this._tickCallback = this._tick.bind(this);
  91532. }
  91533. /**
  91534. * Returns the data related to the vortex event (cylinder).
  91535. * @returns {PhysicsVortexEventData}
  91536. */
  91537. PhysicsVortexEvent.prototype.getData = function () {
  91538. this._dataFetched = true;
  91539. return {
  91540. cylinder: this._cylinder,
  91541. };
  91542. };
  91543. /**
  91544. * Enables the vortex.
  91545. */
  91546. PhysicsVortexEvent.prototype.enable = function () {
  91547. this._tickCallback.call(this);
  91548. this._scene.registerBeforeRender(this._tickCallback);
  91549. };
  91550. /**
  91551. * Disables the cortex.
  91552. */
  91553. PhysicsVortexEvent.prototype.disable = function () {
  91554. this._scene.unregisterBeforeRender(this._tickCallback);
  91555. };
  91556. /**
  91557. * Disposes the sphere.
  91558. * @param {bolean} force
  91559. */
  91560. PhysicsVortexEvent.prototype.dispose = function (force) {
  91561. var _this = this;
  91562. if (force === void 0) { force = true; }
  91563. if (force) {
  91564. this._cylinder.dispose();
  91565. }
  91566. else {
  91567. setTimeout(function () {
  91568. if (!_this._dataFetched) {
  91569. _this._cylinder.dispose();
  91570. }
  91571. }, 0);
  91572. }
  91573. };
  91574. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91575. if (impostor.mass === 0) {
  91576. return null;
  91577. }
  91578. if (!this._intersectsWithCylinder(impostor)) {
  91579. return null;
  91580. }
  91581. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91582. return null;
  91583. }
  91584. var impostorObjectCenter = impostor.getObjectCenter();
  91585. 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)
  91586. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  91587. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  91588. var hit = ray.intersectsMesh(impostor.object);
  91589. var contactPoint = hit.pickedPoint;
  91590. if (!contactPoint) {
  91591. return null;
  91592. }
  91593. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  91594. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  91595. var directionToOrigin = contactPoint.normalize();
  91596. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91597. directionToOrigin = directionToOrigin.negate();
  91598. }
  91599. // TODO: find a more physically based solution
  91600. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91601. var forceX = directionToOrigin.x * this._strength / 8;
  91602. var forceY = directionToOrigin.y * this._updraftMultiplier;
  91603. var forceZ = directionToOrigin.z * this._strength / 8;
  91604. }
  91605. else {
  91606. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  91607. var forceY = this._originTop.y * this._updraftMultiplier;
  91608. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  91609. }
  91610. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  91611. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  91612. return { force: force, contactPoint: impostorObjectCenter };
  91613. };
  91614. PhysicsVortexEvent.prototype._tick = function () {
  91615. var _this = this;
  91616. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91617. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91618. if (!impostorForceAndContactPoint) {
  91619. return;
  91620. }
  91621. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91622. });
  91623. };
  91624. /*** Helpers ***/
  91625. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  91626. if (!this._cylinder) {
  91627. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  91628. height: this._height,
  91629. diameter: this._radius * 2,
  91630. }, this._scene);
  91631. this._cylinder.isVisible = false;
  91632. }
  91633. };
  91634. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  91635. var impostorObject = impostor.object;
  91636. this._prepareCylinder();
  91637. this._cylinder.position = this._cylinderPosition;
  91638. return this._cylinder.intersectsMesh(impostorObject, true);
  91639. };
  91640. return PhysicsVortexEvent;
  91641. }());
  91642. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  91643. /***** Enums *****/
  91644. /**
  91645. * The strenght of the force in correspondence to the distance of the affected object
  91646. */
  91647. var PhysicsRadialImpulseFalloff;
  91648. (function (PhysicsRadialImpulseFalloff) {
  91649. /** Defines that impulse is constant in strength across it's whole radius */
  91650. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  91651. /** DEfines that impulse gets weaker if it's further from the origin */
  91652. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  91653. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  91654. /**
  91655. * The strenght of the force in correspondence to the distance of the affected object
  91656. */
  91657. var PhysicsUpdraftMode;
  91658. (function (PhysicsUpdraftMode) {
  91659. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  91660. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  91661. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  91662. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  91663. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  91664. })(BABYLON || (BABYLON = {}));
  91665. //# sourceMappingURL=babylon.physicsHelper.js.map
  91666. var BABYLON;
  91667. (function (BABYLON) {
  91668. /** @hidden */
  91669. var CannonJSPlugin = /** @class */ (function () {
  91670. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  91671. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  91672. if (iterations === void 0) { iterations = 10; }
  91673. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  91674. this.name = "CannonJSPlugin";
  91675. this._physicsMaterials = new Array();
  91676. this._fixedTimeStep = 1 / 60;
  91677. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  91678. this.BJSCANNON = CANNON;
  91679. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  91680. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  91681. this._tmpPosition = BABYLON.Vector3.Zero();
  91682. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  91683. this._tmpUnityRotation = new BABYLON.Quaternion();
  91684. if (!this.isSupported()) {
  91685. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  91686. return;
  91687. }
  91688. this._extendNamespace();
  91689. this.world = new this.BJSCANNON.World();
  91690. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  91691. this.world.solver.iterations = iterations;
  91692. }
  91693. CannonJSPlugin.prototype.setGravity = function (gravity) {
  91694. this.world.gravity.copy(gravity);
  91695. };
  91696. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  91697. this._fixedTimeStep = timeStep;
  91698. };
  91699. CannonJSPlugin.prototype.getTimeStep = function () {
  91700. return this._fixedTimeStep;
  91701. };
  91702. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  91703. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  91704. };
  91705. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  91706. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91707. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91708. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  91709. };
  91710. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  91711. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91712. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91713. impostor.physicsBody.applyForce(impulse, worldPoint);
  91714. };
  91715. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  91716. //parent-child relationship. Does this impostor has a parent impostor?
  91717. if (impostor.parent) {
  91718. if (impostor.physicsBody) {
  91719. this.removePhysicsBody(impostor);
  91720. //TODO is that needed?
  91721. impostor.forceUpdate();
  91722. }
  91723. return;
  91724. }
  91725. //should a new body be created for this impostor?
  91726. if (impostor.isBodyInitRequired()) {
  91727. var shape = this._createShape(impostor);
  91728. //unregister events, if body is being changed
  91729. var oldBody = impostor.physicsBody;
  91730. if (oldBody) {
  91731. this.removePhysicsBody(impostor);
  91732. }
  91733. //create the body and material
  91734. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  91735. var bodyCreationObject = {
  91736. mass: impostor.getParam("mass"),
  91737. material: material
  91738. };
  91739. // A simple extend, in case native options were used.
  91740. var nativeOptions = impostor.getParam("nativeOptions");
  91741. for (var key in nativeOptions) {
  91742. if (nativeOptions.hasOwnProperty(key)) {
  91743. bodyCreationObject[key] = nativeOptions[key];
  91744. }
  91745. }
  91746. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  91747. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  91748. this.world.addEventListener("preStep", impostor.beforeStep);
  91749. this.world.addEventListener("postStep", impostor.afterStep);
  91750. impostor.physicsBody.addShape(shape);
  91751. this.world.add(impostor.physicsBody);
  91752. //try to keep the body moving in the right direction by taking old properties.
  91753. //Should be tested!
  91754. if (oldBody) {
  91755. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  91756. impostor.physicsBody[param].copy(oldBody[param]);
  91757. });
  91758. }
  91759. this._processChildMeshes(impostor);
  91760. }
  91761. //now update the body's transformation
  91762. this._updatePhysicsBodyTransformation(impostor);
  91763. };
  91764. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  91765. var _this = this;
  91766. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  91767. var currentRotation = mainImpostor.object.rotationQuaternion;
  91768. if (meshChildren.length) {
  91769. var processMesh = function (localPosition, mesh) {
  91770. if (!currentRotation || !mesh.rotationQuaternion) {
  91771. return;
  91772. }
  91773. var childImpostor = mesh.getPhysicsImpostor();
  91774. if (childImpostor) {
  91775. var parent = childImpostor.parent;
  91776. if (parent !== mainImpostor) {
  91777. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  91778. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  91779. if (childImpostor.physicsBody) {
  91780. _this.removePhysicsBody(childImpostor);
  91781. childImpostor.physicsBody = null;
  91782. }
  91783. childImpostor.parent = mainImpostor;
  91784. childImpostor.resetUpdateFlags();
  91785. 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));
  91786. //Add the mass of the children.
  91787. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  91788. }
  91789. }
  91790. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  91791. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  91792. };
  91793. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  91794. }
  91795. };
  91796. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  91797. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  91798. this.world.removeEventListener("preStep", impostor.beforeStep);
  91799. this.world.removeEventListener("postStep", impostor.afterStep);
  91800. this.world.remove(impostor.physicsBody);
  91801. };
  91802. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  91803. var mainBody = impostorJoint.mainImpostor.physicsBody;
  91804. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  91805. if (!mainBody || !connectedBody) {
  91806. return;
  91807. }
  91808. var constraint;
  91809. var jointData = impostorJoint.joint.jointData;
  91810. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  91811. var constraintData = {
  91812. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  91813. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  91814. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  91815. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  91816. maxForce: jointData.nativeParams.maxForce,
  91817. collideConnected: !!jointData.collision
  91818. };
  91819. switch (impostorJoint.joint.type) {
  91820. case BABYLON.PhysicsJoint.HingeJoint:
  91821. case BABYLON.PhysicsJoint.Hinge2Joint:
  91822. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  91823. break;
  91824. case BABYLON.PhysicsJoint.DistanceJoint:
  91825. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  91826. break;
  91827. case BABYLON.PhysicsJoint.SpringJoint:
  91828. var springData = jointData;
  91829. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  91830. restLength: springData.length,
  91831. stiffness: springData.stiffness,
  91832. damping: springData.damping,
  91833. localAnchorA: constraintData.pivotA,
  91834. localAnchorB: constraintData.pivotB
  91835. });
  91836. break;
  91837. case BABYLON.PhysicsJoint.LockJoint:
  91838. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  91839. break;
  91840. case BABYLON.PhysicsJoint.PointToPointJoint:
  91841. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  91842. default:
  91843. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  91844. break;
  91845. }
  91846. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  91847. constraint.collideConnected = !!jointData.collision;
  91848. impostorJoint.joint.physicsJoint = constraint;
  91849. //don't add spring as constraint, as it is not one.
  91850. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91851. this.world.addConstraint(constraint);
  91852. }
  91853. else {
  91854. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  91855. constraint.applyForce();
  91856. };
  91857. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91858. }
  91859. };
  91860. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  91861. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91862. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  91863. }
  91864. else {
  91865. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91866. }
  91867. };
  91868. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  91869. var index;
  91870. var mat;
  91871. for (index = 0; index < this._physicsMaterials.length; index++) {
  91872. mat = this._physicsMaterials[index];
  91873. if (mat.friction === friction && mat.restitution === restitution) {
  91874. return mat;
  91875. }
  91876. }
  91877. var currentMat = new this.BJSCANNON.Material(name);
  91878. currentMat.friction = friction;
  91879. currentMat.restitution = restitution;
  91880. this._physicsMaterials.push(currentMat);
  91881. return currentMat;
  91882. };
  91883. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  91884. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  91885. };
  91886. CannonJSPlugin.prototype._createShape = function (impostor) {
  91887. var object = impostor.object;
  91888. var returnValue;
  91889. var extendSize = impostor.getObjectExtendSize();
  91890. switch (impostor.type) {
  91891. case BABYLON.PhysicsImpostor.SphereImpostor:
  91892. var radiusX = extendSize.x;
  91893. var radiusY = extendSize.y;
  91894. var radiusZ = extendSize.z;
  91895. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  91896. break;
  91897. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  91898. case BABYLON.PhysicsImpostor.CylinderImpostor:
  91899. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  91900. break;
  91901. case BABYLON.PhysicsImpostor.BoxImpostor:
  91902. var box = extendSize.scale(0.5);
  91903. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  91904. break;
  91905. case BABYLON.PhysicsImpostor.PlaneImpostor:
  91906. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  91907. returnValue = new this.BJSCANNON.Plane();
  91908. break;
  91909. case BABYLON.PhysicsImpostor.MeshImpostor:
  91910. // should transform the vertex data to world coordinates!!
  91911. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  91912. var rawFaces = object.getIndices ? object.getIndices() : [];
  91913. if (!rawVerts)
  91914. return;
  91915. // get only scale! so the object could transform correctly.
  91916. var oldPosition = object.position.clone();
  91917. var oldRotation = object.rotation && object.rotation.clone();
  91918. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  91919. object.position.copyFromFloats(0, 0, 0);
  91920. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91921. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91922. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91923. var transform = object.computeWorldMatrix(true);
  91924. // convert rawVerts to object space
  91925. var temp = new Array();
  91926. var index;
  91927. for (index = 0; index < rawVerts.length; index += 3) {
  91928. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  91929. }
  91930. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  91931. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  91932. //now set back the transformation!
  91933. object.position.copyFrom(oldPosition);
  91934. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  91935. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  91936. break;
  91937. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  91938. var oldPosition2 = object.position.clone();
  91939. var oldRotation2 = object.rotation && object.rotation.clone();
  91940. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  91941. object.position.copyFromFloats(0, 0, 0);
  91942. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91943. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91944. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91945. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  91946. returnValue = this._createHeightmap(object);
  91947. object.position.copyFrom(oldPosition2);
  91948. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  91949. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  91950. object.computeWorldMatrix(true);
  91951. break;
  91952. case BABYLON.PhysicsImpostor.ParticleImpostor:
  91953. returnValue = new this.BJSCANNON.Particle();
  91954. break;
  91955. }
  91956. return returnValue;
  91957. };
  91958. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  91959. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91960. var transform = object.computeWorldMatrix(true);
  91961. // convert rawVerts to object space
  91962. var temp = new Array();
  91963. var index;
  91964. for (index = 0; index < pos.length; index += 3) {
  91965. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  91966. }
  91967. pos = temp;
  91968. var matrix = new Array();
  91969. //For now pointDepth will not be used and will be automatically calculated.
  91970. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  91971. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  91972. var boundingInfo = object.getBoundingInfo();
  91973. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  91974. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  91975. var elementSize = dim * 2 / arraySize;
  91976. for (var i = 0; i < pos.length; i = i + 3) {
  91977. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  91978. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  91979. var y = -pos[i + 2] + minY;
  91980. if (!matrix[x]) {
  91981. matrix[x] = [];
  91982. }
  91983. if (!matrix[x][z]) {
  91984. matrix[x][z] = y;
  91985. }
  91986. matrix[x][z] = Math.max(y, matrix[x][z]);
  91987. }
  91988. for (var x = 0; x <= arraySize; ++x) {
  91989. if (!matrix[x]) {
  91990. var loc = 1;
  91991. while (!matrix[(x + loc) % arraySize]) {
  91992. loc++;
  91993. }
  91994. matrix[x] = matrix[(x + loc) % arraySize].slice();
  91995. //console.log("missing x", x);
  91996. }
  91997. for (var z = 0; z <= arraySize; ++z) {
  91998. if (!matrix[x][z]) {
  91999. var loc = 1;
  92000. var newValue;
  92001. while (newValue === undefined) {
  92002. newValue = matrix[x][(z + loc++) % arraySize];
  92003. }
  92004. matrix[x][z] = newValue;
  92005. }
  92006. }
  92007. }
  92008. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92009. elementSize: elementSize
  92010. });
  92011. //For future reference, needed for body transformation
  92012. shape.minY = minY;
  92013. return shape;
  92014. };
  92015. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92016. var object = impostor.object;
  92017. //make sure it is updated...
  92018. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92019. // The delta between the mesh position and the mesh bounding box center
  92020. var bInfo = object.getBoundingInfo();
  92021. if (!bInfo)
  92022. return;
  92023. var center = impostor.getObjectCenter();
  92024. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92025. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92026. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92027. this._tmpPosition.copyFrom(center);
  92028. var quaternion = object.rotationQuaternion;
  92029. if (!quaternion) {
  92030. return;
  92031. }
  92032. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92033. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92034. //-90 DEG in X, precalculated
  92035. quaternion = quaternion.multiply(this._minus90X);
  92036. //Invert! (Precalculated, 90 deg in X)
  92037. //No need to clone. this will never change.
  92038. impostor.setDeltaRotation(this._plus90X);
  92039. }
  92040. //If it is a heightfield, if should be centered.
  92041. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92042. var mesh = object;
  92043. var boundingInfo = mesh.getBoundingInfo();
  92044. //calculate the correct body position:
  92045. var rotationQuaternion = mesh.rotationQuaternion;
  92046. mesh.rotationQuaternion = this._tmpUnityRotation;
  92047. mesh.computeWorldMatrix(true);
  92048. //get original center with no rotation
  92049. var c = center.clone();
  92050. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92051. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92052. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92053. mesh.setPreTransformMatrix(p);
  92054. mesh.computeWorldMatrix(true);
  92055. //calculate the translation
  92056. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92057. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92058. //add it inverted to the delta
  92059. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92060. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92061. //rotation is back
  92062. mesh.rotationQuaternion = rotationQuaternion;
  92063. mesh.setPreTransformMatrix(oldPivot);
  92064. mesh.computeWorldMatrix(true);
  92065. }
  92066. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92067. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92068. //this._tmpPosition.copyFrom(object.position);
  92069. }
  92070. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92071. //Now update the impostor object
  92072. impostor.physicsBody.position.copy(this._tmpPosition);
  92073. impostor.physicsBody.quaternion.copy(quaternion);
  92074. };
  92075. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92076. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92077. if (impostor.object.rotationQuaternion) {
  92078. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92079. }
  92080. };
  92081. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92082. impostor.physicsBody.position.copy(newPosition);
  92083. impostor.physicsBody.quaternion.copy(newRotation);
  92084. };
  92085. CannonJSPlugin.prototype.isSupported = function () {
  92086. return this.BJSCANNON !== undefined;
  92087. };
  92088. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92089. impostor.physicsBody.velocity.copy(velocity);
  92090. };
  92091. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92092. impostor.physicsBody.angularVelocity.copy(velocity);
  92093. };
  92094. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92095. var v = impostor.physicsBody.velocity;
  92096. if (!v) {
  92097. return null;
  92098. }
  92099. return new BABYLON.Vector3(v.x, v.y, v.z);
  92100. };
  92101. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92102. var v = impostor.physicsBody.angularVelocity;
  92103. if (!v) {
  92104. return null;
  92105. }
  92106. return new BABYLON.Vector3(v.x, v.y, v.z);
  92107. };
  92108. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92109. impostor.physicsBody.mass = mass;
  92110. impostor.physicsBody.updateMassProperties();
  92111. };
  92112. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92113. return impostor.physicsBody.mass;
  92114. };
  92115. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92116. return impostor.physicsBody.material.friction;
  92117. };
  92118. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92119. impostor.physicsBody.material.friction = friction;
  92120. };
  92121. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92122. return impostor.physicsBody.material.restitution;
  92123. };
  92124. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92125. impostor.physicsBody.material.restitution = restitution;
  92126. };
  92127. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92128. impostor.physicsBody.sleep();
  92129. };
  92130. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92131. impostor.physicsBody.wakeUp();
  92132. };
  92133. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92134. joint.physicsJoint.distance = maxDistance;
  92135. };
  92136. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92137. // if (!motorIndex) {
  92138. // joint.physicsJoint.enableMotor();
  92139. // }
  92140. // }
  92141. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92142. // if (!motorIndex) {
  92143. // joint.physicsJoint.disableMotor();
  92144. // }
  92145. // }
  92146. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92147. if (!motorIndex) {
  92148. joint.physicsJoint.enableMotor();
  92149. joint.physicsJoint.setMotorSpeed(speed);
  92150. if (maxForce) {
  92151. this.setLimit(joint, maxForce);
  92152. }
  92153. }
  92154. };
  92155. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  92156. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  92157. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  92158. };
  92159. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92160. var body = impostor.physicsBody;
  92161. mesh.position.x = body.position.x;
  92162. mesh.position.y = body.position.y;
  92163. mesh.position.z = body.position.z;
  92164. if (mesh.rotationQuaternion) {
  92165. mesh.rotationQuaternion.x = body.quaternion.x;
  92166. mesh.rotationQuaternion.y = body.quaternion.y;
  92167. mesh.rotationQuaternion.z = body.quaternion.z;
  92168. mesh.rotationQuaternion.w = body.quaternion.w;
  92169. }
  92170. };
  92171. CannonJSPlugin.prototype.getRadius = function (impostor) {
  92172. var shape = impostor.physicsBody.shapes[0];
  92173. return shape.boundingSphereRadius;
  92174. };
  92175. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92176. var shape = impostor.physicsBody.shapes[0];
  92177. result.x = shape.halfExtents.x * 2;
  92178. result.y = shape.halfExtents.y * 2;
  92179. result.z = shape.halfExtents.z * 2;
  92180. };
  92181. CannonJSPlugin.prototype.dispose = function () {
  92182. };
  92183. CannonJSPlugin.prototype._extendNamespace = function () {
  92184. //this will force cannon to execute at least one step when using interpolation
  92185. var step_tmp1 = new this.BJSCANNON.Vec3();
  92186. var Engine = this.BJSCANNON;
  92187. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  92188. maxSubSteps = maxSubSteps || 10;
  92189. timeSinceLastCalled = timeSinceLastCalled || 0;
  92190. if (timeSinceLastCalled === 0) {
  92191. this.internalStep(dt);
  92192. this.time += dt;
  92193. }
  92194. else {
  92195. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  92196. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  92197. var t0 = performance.now();
  92198. for (var i = 0; i !== internalSteps; i++) {
  92199. this.internalStep(dt);
  92200. if (performance.now() - t0 > dt * 1000) {
  92201. break;
  92202. }
  92203. }
  92204. this.time += timeSinceLastCalled;
  92205. var h = this.time % dt;
  92206. var h_div_dt = h / dt;
  92207. var interpvelo = step_tmp1;
  92208. var bodies = this.bodies;
  92209. for (var j = 0; j !== bodies.length; j++) {
  92210. var b = bodies[j];
  92211. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  92212. b.position.vsub(b.previousPosition, interpvelo);
  92213. interpvelo.scale(h_div_dt, interpvelo);
  92214. b.position.vadd(interpvelo, b.interpolatedPosition);
  92215. }
  92216. else {
  92217. b.interpolatedPosition.copy(b.position);
  92218. b.interpolatedQuaternion.copy(b.quaternion);
  92219. }
  92220. }
  92221. }
  92222. };
  92223. };
  92224. return CannonJSPlugin;
  92225. }());
  92226. BABYLON.CannonJSPlugin = CannonJSPlugin;
  92227. })(BABYLON || (BABYLON = {}));
  92228. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  92229. var BABYLON;
  92230. (function (BABYLON) {
  92231. /** @hidden */
  92232. var OimoJSPlugin = /** @class */ (function () {
  92233. function OimoJSPlugin(iterations) {
  92234. this.name = "OimoJSPlugin";
  92235. this._tmpImpostorsArray = [];
  92236. this._tmpPositionVector = BABYLON.Vector3.Zero();
  92237. this.BJSOIMO = OIMO;
  92238. this.world = new this.BJSOIMO.World({
  92239. iterations: iterations
  92240. });
  92241. this.world.clear();
  92242. }
  92243. OimoJSPlugin.prototype.setGravity = function (gravity) {
  92244. this.world.gravity.copy(gravity);
  92245. };
  92246. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  92247. this.world.timeStep = timeStep;
  92248. };
  92249. OimoJSPlugin.prototype.getTimeStep = function () {
  92250. return this.world.timeStep;
  92251. };
  92252. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  92253. var _this = this;
  92254. impostors.forEach(function (impostor) {
  92255. impostor.beforeStep();
  92256. });
  92257. this.world.step();
  92258. impostors.forEach(function (impostor) {
  92259. impostor.afterStep();
  92260. //update the ordered impostors array
  92261. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  92262. });
  92263. //check for collisions
  92264. var contact = this.world.contacts;
  92265. while (contact !== null) {
  92266. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  92267. contact = contact.next;
  92268. continue;
  92269. }
  92270. //is this body colliding with any other? get the impostor
  92271. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  92272. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  92273. if (!mainImpostor || !collidingImpostor) {
  92274. contact = contact.next;
  92275. continue;
  92276. }
  92277. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  92278. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  92279. contact = contact.next;
  92280. }
  92281. };
  92282. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92283. var mass = impostor.physicsBody.mass;
  92284. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  92285. };
  92286. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92287. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  92288. this.applyImpulse(impostor, force, contactPoint);
  92289. };
  92290. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92291. var _this = this;
  92292. //parent-child relationship. Does this impostor has a parent impostor?
  92293. if (impostor.parent) {
  92294. if (impostor.physicsBody) {
  92295. this.removePhysicsBody(impostor);
  92296. //TODO is that needed?
  92297. impostor.forceUpdate();
  92298. }
  92299. return;
  92300. }
  92301. if (impostor.isBodyInitRequired()) {
  92302. var bodyConfig = {
  92303. name: impostor.uniqueId,
  92304. //Oimo must have mass, also for static objects.
  92305. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  92306. size: [],
  92307. type: [],
  92308. pos: [],
  92309. posShape: [],
  92310. rot: [],
  92311. rotShape: [],
  92312. move: impostor.getParam("mass") !== 0,
  92313. density: impostor.getParam("mass"),
  92314. friction: impostor.getParam("friction"),
  92315. restitution: impostor.getParam("restitution"),
  92316. //Supporting older versions of Oimo
  92317. world: this.world
  92318. };
  92319. var impostors = [impostor];
  92320. var addToArray = function (parent) {
  92321. if (!parent.getChildMeshes)
  92322. return;
  92323. parent.getChildMeshes().forEach(function (m) {
  92324. if (m.physicsImpostor) {
  92325. impostors.push(m.physicsImpostor);
  92326. //m.physicsImpostor._init();
  92327. }
  92328. });
  92329. };
  92330. addToArray(impostor.object);
  92331. var checkWithEpsilon_1 = function (value) {
  92332. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  92333. };
  92334. var globalQuaternion_1 = new BABYLON.Quaternion();
  92335. impostors.forEach(function (i) {
  92336. if (!i.object.rotationQuaternion) {
  92337. return;
  92338. }
  92339. //get the correct bounding box
  92340. var oldQuaternion = i.object.rotationQuaternion;
  92341. globalQuaternion_1 = oldQuaternion.clone();
  92342. var rot = oldQuaternion.toEulerAngles();
  92343. var extendSize = i.getObjectExtendSize();
  92344. var radToDeg = 57.295779513082320876;
  92345. if (i === impostor) {
  92346. var center = impostor.getObjectCenter();
  92347. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  92348. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  92349. //Can also use Array.prototype.push.apply
  92350. bodyConfig.pos.push(center.x);
  92351. bodyConfig.pos.push(center.y);
  92352. bodyConfig.pos.push(center.z);
  92353. bodyConfig.posShape.push(0, 0, 0);
  92354. //tmp solution
  92355. bodyConfig.rot.push(0);
  92356. bodyConfig.rot.push(0);
  92357. bodyConfig.rot.push(0);
  92358. bodyConfig.rotShape.push(0, 0, 0);
  92359. }
  92360. else {
  92361. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  92362. bodyConfig.posShape.push(localPosition.x);
  92363. bodyConfig.posShape.push(localPosition.y);
  92364. bodyConfig.posShape.push(localPosition.z);
  92365. bodyConfig.pos.push(0, 0, 0);
  92366. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  92367. bodyConfig.rot.push(0);
  92368. bodyConfig.rot.push(0);
  92369. bodyConfig.rot.push(0);
  92370. bodyConfig.rotShape.push(rot.x * radToDeg);
  92371. bodyConfig.rotShape.push(rot.y * radToDeg);
  92372. bodyConfig.rotShape.push(rot.z * radToDeg);
  92373. }
  92374. // register mesh
  92375. switch (i.type) {
  92376. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92377. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  92378. case BABYLON.PhysicsImpostor.SphereImpostor:
  92379. var radiusX = extendSize.x;
  92380. var radiusY = extendSize.y;
  92381. var radiusZ = extendSize.z;
  92382. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  92383. bodyConfig.type.push('sphere');
  92384. //due to the way oimo works with compounds, add 3 times
  92385. bodyConfig.size.push(size);
  92386. bodyConfig.size.push(size);
  92387. bodyConfig.size.push(size);
  92388. break;
  92389. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92390. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  92391. var sizeY = checkWithEpsilon_1(extendSize.y);
  92392. bodyConfig.type.push('cylinder');
  92393. bodyConfig.size.push(sizeX);
  92394. bodyConfig.size.push(sizeY);
  92395. //due to the way oimo works with compounds, add one more value.
  92396. bodyConfig.size.push(sizeY);
  92397. break;
  92398. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92399. case BABYLON.PhysicsImpostor.BoxImpostor:
  92400. default:
  92401. var sizeX = checkWithEpsilon_1(extendSize.x);
  92402. var sizeY = checkWithEpsilon_1(extendSize.y);
  92403. var sizeZ = checkWithEpsilon_1(extendSize.z);
  92404. bodyConfig.type.push('box');
  92405. //if (i === impostor) {
  92406. bodyConfig.size.push(sizeX);
  92407. bodyConfig.size.push(sizeY);
  92408. bodyConfig.size.push(sizeZ);
  92409. //} else {
  92410. // bodyConfig.size.push(0,0,0);
  92411. //}
  92412. break;
  92413. }
  92414. //actually not needed, but hey...
  92415. i.object.rotationQuaternion = oldQuaternion;
  92416. });
  92417. impostor.physicsBody = this.world.add(bodyConfig);
  92418. // set the quaternion, ignoring the previously defined (euler) rotation
  92419. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  92420. // update with delta 0, so the body will reveive the new rotation.
  92421. impostor.physicsBody.updatePosition(0);
  92422. }
  92423. else {
  92424. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  92425. }
  92426. impostor.setDeltaPosition(this._tmpPositionVector);
  92427. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  92428. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  92429. };
  92430. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92431. //impostor.physicsBody.dispose();
  92432. //Same as : (older oimo versions)
  92433. this.world.removeRigidBody(impostor.physicsBody);
  92434. };
  92435. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92436. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92437. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92438. if (!mainBody || !connectedBody) {
  92439. return;
  92440. }
  92441. var jointData = impostorJoint.joint.jointData;
  92442. var options = jointData.nativeParams || {};
  92443. var type;
  92444. var nativeJointData = {
  92445. body1: mainBody,
  92446. body2: connectedBody,
  92447. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  92448. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  92449. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  92450. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  92451. min: options.min,
  92452. max: options.max,
  92453. collision: options.collision || jointData.collision,
  92454. spring: options.spring,
  92455. //supporting older version of Oimo
  92456. world: this.world
  92457. };
  92458. switch (impostorJoint.joint.type) {
  92459. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92460. type = "jointBall";
  92461. break;
  92462. case BABYLON.PhysicsJoint.SpringJoint:
  92463. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  92464. var springData = jointData;
  92465. nativeJointData.min = springData.length || nativeJointData.min;
  92466. //Max should also be set, just make sure it is at least min
  92467. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  92468. case BABYLON.PhysicsJoint.DistanceJoint:
  92469. type = "jointDistance";
  92470. nativeJointData.max = jointData.maxDistance;
  92471. break;
  92472. case BABYLON.PhysicsJoint.PrismaticJoint:
  92473. type = "jointPrisme";
  92474. break;
  92475. case BABYLON.PhysicsJoint.SliderJoint:
  92476. type = "jointSlide";
  92477. break;
  92478. case BABYLON.PhysicsJoint.WheelJoint:
  92479. type = "jointWheel";
  92480. break;
  92481. case BABYLON.PhysicsJoint.HingeJoint:
  92482. default:
  92483. type = "jointHinge";
  92484. break;
  92485. }
  92486. nativeJointData.type = type;
  92487. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  92488. };
  92489. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92490. //Bug in Oimo prevents us from disposing a joint in the playground
  92491. //joint.joint.physicsJoint.dispose();
  92492. //So we will bruteforce it!
  92493. try {
  92494. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  92495. }
  92496. catch (e) {
  92497. BABYLON.Tools.Warn(e);
  92498. }
  92499. };
  92500. OimoJSPlugin.prototype.isSupported = function () {
  92501. return this.BJSOIMO !== undefined;
  92502. };
  92503. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92504. if (!impostor.physicsBody.sleeping) {
  92505. //TODO check that
  92506. /*if (impostor.physicsBody.shapes.next) {
  92507. var parentShape = this._getLastShape(impostor.physicsBody);
  92508. impostor.object.position.copyFrom(parentShape.position);
  92509. console.log(parentShape.position);
  92510. } else {*/
  92511. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  92512. //}
  92513. if (impostor.object.rotationQuaternion) {
  92514. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  92515. }
  92516. }
  92517. };
  92518. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92519. var body = impostor.physicsBody;
  92520. body.position.copy(newPosition);
  92521. body.orientation.copy(newRotation);
  92522. body.syncShapes();
  92523. body.awake();
  92524. };
  92525. /*private _getLastShape(body: any): any {
  92526. var lastShape = body.shapes;
  92527. while (lastShape.next) {
  92528. lastShape = lastShape.next;
  92529. }
  92530. return lastShape;
  92531. }*/
  92532. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92533. impostor.physicsBody.linearVelocity.copy(velocity);
  92534. };
  92535. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92536. impostor.physicsBody.angularVelocity.copy(velocity);
  92537. };
  92538. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92539. var v = impostor.physicsBody.linearVelocity;
  92540. if (!v) {
  92541. return null;
  92542. }
  92543. return new BABYLON.Vector3(v.x, v.y, v.z);
  92544. };
  92545. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92546. var v = impostor.physicsBody.angularVelocity;
  92547. if (!v) {
  92548. return null;
  92549. }
  92550. return new BABYLON.Vector3(v.x, v.y, v.z);
  92551. };
  92552. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92553. var staticBody = mass === 0;
  92554. //this will actually set the body's density and not its mass.
  92555. //But this is how oimo treats the mass variable.
  92556. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  92557. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  92558. };
  92559. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  92560. return impostor.physicsBody.shapes.density;
  92561. };
  92562. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  92563. return impostor.physicsBody.shapes.friction;
  92564. };
  92565. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92566. impostor.physicsBody.shapes.friction = friction;
  92567. };
  92568. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92569. return impostor.physicsBody.shapes.restitution;
  92570. };
  92571. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92572. impostor.physicsBody.shapes.restitution = restitution;
  92573. };
  92574. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  92575. impostor.physicsBody.sleep();
  92576. };
  92577. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  92578. impostor.physicsBody.awake();
  92579. };
  92580. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92581. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  92582. if (minDistance !== void 0) {
  92583. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  92584. }
  92585. };
  92586. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92587. //TODO separate rotational and transational motors.
  92588. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92589. if (motor) {
  92590. motor.setMotor(speed, maxForce);
  92591. }
  92592. };
  92593. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  92594. //TODO separate rotational and transational motors.
  92595. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92596. if (motor) {
  92597. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  92598. }
  92599. };
  92600. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92601. var body = impostor.physicsBody;
  92602. mesh.position.x = body.position.x;
  92603. mesh.position.y = body.position.y;
  92604. mesh.position.z = body.position.z;
  92605. if (mesh.rotationQuaternion) {
  92606. mesh.rotationQuaternion.x = body.orientation.x;
  92607. mesh.rotationQuaternion.y = body.orientation.y;
  92608. mesh.rotationQuaternion.z = body.orientation.z;
  92609. mesh.rotationQuaternion.w = body.orientation.s;
  92610. }
  92611. };
  92612. OimoJSPlugin.prototype.getRadius = function (impostor) {
  92613. return impostor.physicsBody.shapes.radius;
  92614. };
  92615. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92616. var shape = impostor.physicsBody.shapes;
  92617. result.x = shape.halfWidth * 2;
  92618. result.y = shape.halfHeight * 2;
  92619. result.z = shape.halfDepth * 2;
  92620. };
  92621. OimoJSPlugin.prototype.dispose = function () {
  92622. this.world.clear();
  92623. };
  92624. return OimoJSPlugin;
  92625. }());
  92626. BABYLON.OimoJSPlugin = OimoJSPlugin;
  92627. })(BABYLON || (BABYLON = {}));
  92628. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  92629. var BABYLON;
  92630. (function (BABYLON) {
  92631. /**
  92632. * Gets the current physics engine
  92633. * @returns a IPhysicsEngine or null if none attached
  92634. */
  92635. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  92636. return this._physicsEngine;
  92637. };
  92638. /**
  92639. * Enables physics to the current scene
  92640. * @param gravity defines the scene's gravity for the physics engine
  92641. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  92642. * @return a boolean indicating if the physics engine was initialized
  92643. */
  92644. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  92645. if (gravity === void 0) { gravity = null; }
  92646. if (this._physicsEngine) {
  92647. return true;
  92648. }
  92649. // Register the component to the scene
  92650. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  92651. if (!component) {
  92652. component = new PhysicsEngineSceneComponent(this);
  92653. this._addComponent(component);
  92654. }
  92655. try {
  92656. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  92657. return true;
  92658. }
  92659. catch (e) {
  92660. BABYLON.Tools.Error(e.message);
  92661. return false;
  92662. }
  92663. };
  92664. /**
  92665. * Disables and disposes the physics engine associated with the scene
  92666. */
  92667. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  92668. if (!this._physicsEngine) {
  92669. return;
  92670. }
  92671. this._physicsEngine.dispose();
  92672. this._physicsEngine = null;
  92673. };
  92674. /**
  92675. * Gets a boolean indicating if there is an active physics engine
  92676. * @returns a boolean indicating if there is an active physics engine
  92677. */
  92678. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  92679. return this._physicsEngine !== undefined;
  92680. };
  92681. /**
  92682. * Deletes a physics compound impostor
  92683. * @param compound defines the compound to delete
  92684. */
  92685. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  92686. var mesh = compound.parts[0].mesh;
  92687. if (mesh.physicsImpostor) {
  92688. mesh.physicsImpostor.dispose( /*true*/);
  92689. mesh.physicsImpostor = null;
  92690. }
  92691. };
  92692. /** @hidden */
  92693. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  92694. if (this._physicsEngine) {
  92695. this.onBeforePhysicsObservable.notifyObservers(this);
  92696. this._physicsEngine._step(step / 1000);
  92697. this.onAfterPhysicsObservable.notifyObservers(this);
  92698. }
  92699. };
  92700. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  92701. get: function () {
  92702. return this._physicsImpostor;
  92703. },
  92704. set: function (value) {
  92705. var _this = this;
  92706. if (this._physicsImpostor === value) {
  92707. return;
  92708. }
  92709. if (this._disposePhysicsObserver) {
  92710. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  92711. }
  92712. this._physicsImpostor = value;
  92713. if (value) {
  92714. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  92715. // Physics
  92716. if (_this.physicsImpostor) {
  92717. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  92718. _this.physicsImpostor = null;
  92719. }
  92720. });
  92721. }
  92722. },
  92723. enumerable: true,
  92724. configurable: true
  92725. });
  92726. /**
  92727. * Gets the current physics impostor
  92728. * @see http://doc.babylonjs.com/features/physics_engine
  92729. * @returns a physics impostor or null
  92730. */
  92731. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  92732. return this.physicsImpostor;
  92733. };
  92734. /**
  92735. * Apply a physic impulse to the mesh
  92736. * @param force defines the force to apply
  92737. * @param contactPoint defines where to apply the force
  92738. * @returns the current mesh
  92739. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92740. */
  92741. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  92742. if (!this.physicsImpostor) {
  92743. return this;
  92744. }
  92745. this.physicsImpostor.applyImpulse(force, contactPoint);
  92746. return this;
  92747. };
  92748. /**
  92749. * Creates a physic joint between two meshes
  92750. * @param otherMesh defines the other mesh to use
  92751. * @param pivot1 defines the pivot to use on this mesh
  92752. * @param pivot2 defines the pivot to use on the other mesh
  92753. * @param options defines additional options (can be plugin dependent)
  92754. * @returns the current mesh
  92755. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  92756. */
  92757. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  92758. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  92759. return this;
  92760. }
  92761. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  92762. mainPivot: pivot1,
  92763. connectedPivot: pivot2,
  92764. nativeParams: options
  92765. });
  92766. return this;
  92767. };
  92768. /**
  92769. * Defines the physics engine scene component responsible to manage a physics engine
  92770. */
  92771. var PhysicsEngineSceneComponent = /** @class */ (function () {
  92772. /**
  92773. * Creates a new instance of the component for the given scene
  92774. * @param scene Defines the scene to register the component in
  92775. */
  92776. function PhysicsEngineSceneComponent(scene) {
  92777. var _this = this;
  92778. /**
  92779. * The component name helpful to identify the component in the list of scene components.
  92780. */
  92781. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  92782. this.scene = scene;
  92783. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  92784. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  92785. // Replace the function used to get the deterministic frame time
  92786. this.scene.getDeterministicFrameTime = function () {
  92787. if (_this.scene._physicsEngine) {
  92788. return _this.scene._physicsEngine.getTimeStep() * 1000;
  92789. }
  92790. return 1000.0 / 60.0;
  92791. };
  92792. }
  92793. /**
  92794. * Registers the component in a given scene
  92795. */
  92796. PhysicsEngineSceneComponent.prototype.register = function () {
  92797. };
  92798. /**
  92799. * Rebuilds the elements related to this component in case of
  92800. * context lost for instance.
  92801. */
  92802. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  92803. // Nothing to do for this component
  92804. };
  92805. /**
  92806. * Disposes the component and the associated ressources
  92807. */
  92808. PhysicsEngineSceneComponent.prototype.dispose = function () {
  92809. this.scene.onBeforePhysicsObservable.clear();
  92810. this.scene.onAfterPhysicsObservable.clear();
  92811. if (this.scene._physicsEngine) {
  92812. this.scene.disablePhysicsEngine();
  92813. }
  92814. };
  92815. return PhysicsEngineSceneComponent;
  92816. }());
  92817. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  92818. })(BABYLON || (BABYLON = {}));
  92819. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  92820. var BABYLON;
  92821. (function (BABYLON) {
  92822. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  92823. // All values and structures referenced from:
  92824. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  92825. var DDS_MAGIC = 0x20534444;
  92826. var
  92827. //DDSD_CAPS = 0x1,
  92828. //DDSD_HEIGHT = 0x2,
  92829. //DDSD_WIDTH = 0x4,
  92830. //DDSD_PITCH = 0x8,
  92831. //DDSD_PIXELFORMAT = 0x1000,
  92832. DDSD_MIPMAPCOUNT = 0x20000;
  92833. //DDSD_LINEARSIZE = 0x80000,
  92834. //DDSD_DEPTH = 0x800000;
  92835. // var DDSCAPS_COMPLEX = 0x8,
  92836. // DDSCAPS_MIPMAP = 0x400000,
  92837. // DDSCAPS_TEXTURE = 0x1000;
  92838. var DDSCAPS2_CUBEMAP = 0x200;
  92839. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  92840. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  92841. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  92842. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  92843. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  92844. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  92845. // DDSCAPS2_VOLUME = 0x200000;
  92846. var
  92847. //DDPF_ALPHAPIXELS = 0x1,
  92848. //DDPF_ALPHA = 0x2,
  92849. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  92850. //DDPF_YUV = 0x200,
  92851. DDPF_LUMINANCE = 0x20000;
  92852. function FourCCToInt32(value) {
  92853. return value.charCodeAt(0) +
  92854. (value.charCodeAt(1) << 8) +
  92855. (value.charCodeAt(2) << 16) +
  92856. (value.charCodeAt(3) << 24);
  92857. }
  92858. function Int32ToFourCC(value) {
  92859. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  92860. }
  92861. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  92862. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  92863. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  92864. var FOURCC_DX10 = FourCCToInt32("DX10");
  92865. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  92866. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  92867. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  92868. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  92869. var headerLengthInt = 31; // The header length in 32 bit ints
  92870. // Offsets into the header array
  92871. var off_magic = 0;
  92872. var off_size = 1;
  92873. var off_flags = 2;
  92874. var off_height = 3;
  92875. var off_width = 4;
  92876. var off_mipmapCount = 7;
  92877. var off_pfFlags = 20;
  92878. var off_pfFourCC = 21;
  92879. var off_RGBbpp = 22;
  92880. var off_RMask = 23;
  92881. var off_GMask = 24;
  92882. var off_BMask = 25;
  92883. var off_AMask = 26;
  92884. // var off_caps1 = 27;
  92885. var off_caps2 = 28;
  92886. // var off_caps3 = 29;
  92887. // var off_caps4 = 30;
  92888. var off_dxgiFormat = 32;
  92889. ;
  92890. var DDSTools = /** @class */ (function () {
  92891. function DDSTools() {
  92892. }
  92893. DDSTools.GetDDSInfo = function (arrayBuffer) {
  92894. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  92895. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  92896. var mipmapCount = 1;
  92897. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  92898. mipmapCount = Math.max(1, header[off_mipmapCount]);
  92899. }
  92900. var fourCC = header[off_pfFourCC];
  92901. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  92902. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92903. switch (fourCC) {
  92904. case FOURCC_D3DFMT_R16G16B16A16F:
  92905. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92906. break;
  92907. case FOURCC_D3DFMT_R32G32B32A32F:
  92908. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92909. break;
  92910. case FOURCC_DX10:
  92911. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  92912. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92913. break;
  92914. }
  92915. }
  92916. return {
  92917. width: header[off_width],
  92918. height: header[off_height],
  92919. mipmapCount: mipmapCount,
  92920. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  92921. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  92922. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  92923. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  92924. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  92925. dxgiFormat: dxgiFormat,
  92926. textureType: textureType
  92927. };
  92928. };
  92929. DDSTools._ToHalfFloat = function (value) {
  92930. if (!DDSTools._FloatView) {
  92931. DDSTools._FloatView = new Float32Array(1);
  92932. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  92933. }
  92934. DDSTools._FloatView[0] = value;
  92935. var x = DDSTools._Int32View[0];
  92936. var bits = (x >> 16) & 0x8000; /* Get the sign */
  92937. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  92938. var e = (x >> 23) & 0xff; /* Using int is faster here */
  92939. /* If zero, or denormal, or exponent underflows too much for a denormal
  92940. * half, return signed zero. */
  92941. if (e < 103) {
  92942. return bits;
  92943. }
  92944. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  92945. if (e > 142) {
  92946. bits |= 0x7c00;
  92947. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  92948. * not Inf, so make sure we set one mantissa bit too. */
  92949. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  92950. return bits;
  92951. }
  92952. /* If exponent underflows but not too much, return a denormal */
  92953. if (e < 113) {
  92954. m |= 0x0800;
  92955. /* Extra rounding may overflow and set mantissa to 0 and exponent
  92956. * to 1, which is OK. */
  92957. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  92958. return bits;
  92959. }
  92960. bits |= ((e - 112) << 10) | (m >> 1);
  92961. bits += m & 1;
  92962. return bits;
  92963. };
  92964. DDSTools._FromHalfFloat = function (value) {
  92965. var s = (value & 0x8000) >> 15;
  92966. var e = (value & 0x7C00) >> 10;
  92967. var f = value & 0x03FF;
  92968. if (e === 0) {
  92969. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  92970. }
  92971. else if (e == 0x1F) {
  92972. return f ? NaN : ((s ? -1 : 1) * Infinity);
  92973. }
  92974. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  92975. };
  92976. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92977. var destArray = new Float32Array(dataLength);
  92978. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92979. var index = 0;
  92980. for (var y = 0; y < height; y++) {
  92981. for (var x = 0; x < width; x++) {
  92982. var srcPos = (x + y * width) * 4;
  92983. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  92984. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  92985. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  92986. if (DDSTools.StoreLODInAlphaChannel) {
  92987. destArray[index + 3] = lod;
  92988. }
  92989. else {
  92990. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  92991. }
  92992. index += 4;
  92993. }
  92994. }
  92995. return destArray;
  92996. };
  92997. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92998. if (DDSTools.StoreLODInAlphaChannel) {
  92999. var destArray = new Uint16Array(dataLength);
  93000. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93001. var index = 0;
  93002. for (var y = 0; y < height; y++) {
  93003. for (var x = 0; x < width; x++) {
  93004. var srcPos = (x + y * width) * 4;
  93005. destArray[index] = srcData[srcPos];
  93006. destArray[index + 1] = srcData[srcPos + 1];
  93007. destArray[index + 2] = srcData[srcPos + 2];
  93008. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93009. index += 4;
  93010. }
  93011. }
  93012. return destArray;
  93013. }
  93014. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93015. };
  93016. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93017. if (DDSTools.StoreLODInAlphaChannel) {
  93018. var destArray = new Float32Array(dataLength);
  93019. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93020. var index = 0;
  93021. for (var y = 0; y < height; y++) {
  93022. for (var x = 0; x < width; x++) {
  93023. var srcPos = (x + y * width) * 4;
  93024. destArray[index] = srcData[srcPos];
  93025. destArray[index + 1] = srcData[srcPos + 1];
  93026. destArray[index + 2] = srcData[srcPos + 2];
  93027. destArray[index + 3] = lod;
  93028. index += 4;
  93029. }
  93030. }
  93031. return destArray;
  93032. }
  93033. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93034. };
  93035. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93036. var destArray = new Uint8Array(dataLength);
  93037. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93038. var index = 0;
  93039. for (var y = 0; y < height; y++) {
  93040. for (var x = 0; x < width; x++) {
  93041. var srcPos = (x + y * width) * 4;
  93042. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93043. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93044. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93045. if (DDSTools.StoreLODInAlphaChannel) {
  93046. destArray[index + 3] = lod;
  93047. }
  93048. else {
  93049. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93050. }
  93051. index += 4;
  93052. }
  93053. }
  93054. return destArray;
  93055. };
  93056. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93057. var destArray = new Uint8Array(dataLength);
  93058. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93059. var index = 0;
  93060. for (var y = 0; y < height; y++) {
  93061. for (var x = 0; x < width; x++) {
  93062. var srcPos = (x + y * width) * 4;
  93063. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93064. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93065. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93066. if (DDSTools.StoreLODInAlphaChannel) {
  93067. destArray[index + 3] = lod;
  93068. }
  93069. else {
  93070. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93071. }
  93072. index += 4;
  93073. }
  93074. }
  93075. return destArray;
  93076. };
  93077. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93078. var byteArray = new Uint8Array(dataLength);
  93079. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93080. var index = 0;
  93081. for (var y = 0; y < height; y++) {
  93082. for (var x = 0; x < width; x++) {
  93083. var srcPos = (x + y * width) * 4;
  93084. byteArray[index] = srcData[srcPos + rOffset];
  93085. byteArray[index + 1] = srcData[srcPos + gOffset];
  93086. byteArray[index + 2] = srcData[srcPos + bOffset];
  93087. byteArray[index + 3] = srcData[srcPos + aOffset];
  93088. index += 4;
  93089. }
  93090. }
  93091. return byteArray;
  93092. };
  93093. DDSTools._ExtractLongWordOrder = function (value) {
  93094. if (value === 0 || value === 255 || value === -16777216) {
  93095. return 0;
  93096. }
  93097. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93098. };
  93099. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93100. var byteArray = new Uint8Array(dataLength);
  93101. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93102. var index = 0;
  93103. for (var y = 0; y < height; y++) {
  93104. for (var x = 0; x < width; x++) {
  93105. var srcPos = (x + y * width) * 3;
  93106. byteArray[index] = srcData[srcPos + rOffset];
  93107. byteArray[index + 1] = srcData[srcPos + gOffset];
  93108. byteArray[index + 2] = srcData[srcPos + bOffset];
  93109. index += 3;
  93110. }
  93111. }
  93112. return byteArray;
  93113. };
  93114. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93115. var byteArray = new Uint8Array(dataLength);
  93116. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93117. var index = 0;
  93118. for (var y = 0; y < height; y++) {
  93119. for (var x = 0; x < width; x++) {
  93120. var srcPos = (x + y * width);
  93121. byteArray[index] = srcData[srcPos];
  93122. index++;
  93123. }
  93124. }
  93125. return byteArray;
  93126. };
  93127. /**
  93128. * Uploads DDS Levels to a Babylon Texture
  93129. * @hidden
  93130. */
  93131. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93132. if (lodIndex === void 0) { lodIndex = -1; }
  93133. var sphericalPolynomialFaces = null;
  93134. if (info.sphericalPolynomial) {
  93135. sphericalPolynomialFaces = new Array();
  93136. }
  93137. var ext = engine.getCaps().s3tc;
  93138. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93139. var fourCC, width, height, dataLength = 0, dataOffset;
  93140. var byteArray, mipmapCount, mip;
  93141. var internalCompressedFormat = 0;
  93142. var blockBytes = 1;
  93143. if (header[off_magic] !== DDS_MAGIC) {
  93144. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93145. return;
  93146. }
  93147. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  93148. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  93149. return;
  93150. }
  93151. if (info.isCompressed && !ext) {
  93152. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  93153. return;
  93154. }
  93155. var bpp = header[off_RGBbpp];
  93156. dataOffset = header[off_size] + 4;
  93157. var computeFormats = false;
  93158. if (info.isFourCC) {
  93159. fourCC = header[off_pfFourCC];
  93160. switch (fourCC) {
  93161. case FOURCC_DXT1:
  93162. blockBytes = 8;
  93163. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  93164. break;
  93165. case FOURCC_DXT3:
  93166. blockBytes = 16;
  93167. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  93168. break;
  93169. case FOURCC_DXT5:
  93170. blockBytes = 16;
  93171. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  93172. break;
  93173. case FOURCC_D3DFMT_R16G16B16A16F:
  93174. computeFormats = true;
  93175. break;
  93176. case FOURCC_D3DFMT_R32G32B32A32F:
  93177. computeFormats = true;
  93178. break;
  93179. case FOURCC_DX10:
  93180. // There is an additionnal header so dataOffset need to be changed
  93181. dataOffset += 5 * 4; // 5 uints
  93182. var supported = false;
  93183. switch (info.dxgiFormat) {
  93184. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  93185. computeFormats = true;
  93186. supported = true;
  93187. break;
  93188. case DXGI_FORMAT_B8G8R8X8_UNORM:
  93189. info.isRGB = true;
  93190. info.isFourCC = false;
  93191. bpp = 32;
  93192. supported = true;
  93193. break;
  93194. }
  93195. if (supported) {
  93196. break;
  93197. }
  93198. default:
  93199. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  93200. return;
  93201. }
  93202. }
  93203. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  93204. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  93205. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  93206. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  93207. if (computeFormats) {
  93208. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  93209. }
  93210. mipmapCount = 1;
  93211. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  93212. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93213. }
  93214. for (var face = 0; face < faces; face++) {
  93215. width = header[off_width];
  93216. height = header[off_height];
  93217. for (mip = 0; mip < mipmapCount; ++mip) {
  93218. if (lodIndex === -1 || lodIndex === mip) {
  93219. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  93220. var i = (lodIndex === -1) ? mip : 0;
  93221. if (!info.isCompressed && info.isFourCC) {
  93222. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93223. dataLength = width * height * 4;
  93224. var floatArray = null;
  93225. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  93226. if (bpp === 128) {
  93227. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93228. if (sphericalPolynomialFaces && i == 0) {
  93229. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93230. }
  93231. }
  93232. else if (bpp === 64) {
  93233. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93234. if (sphericalPolynomialFaces && i == 0) {
  93235. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93236. }
  93237. }
  93238. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93239. }
  93240. else {
  93241. if (bpp === 128) {
  93242. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93243. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93244. if (sphericalPolynomialFaces && i == 0) {
  93245. sphericalPolynomialFaces.push(floatArray);
  93246. }
  93247. }
  93248. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  93249. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93250. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93251. if (sphericalPolynomialFaces && i == 0) {
  93252. sphericalPolynomialFaces.push(floatArray);
  93253. }
  93254. }
  93255. else { // 64
  93256. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93257. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93258. if (sphericalPolynomialFaces && i == 0) {
  93259. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93260. }
  93261. }
  93262. }
  93263. if (floatArray) {
  93264. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  93265. }
  93266. }
  93267. else if (info.isRGB) {
  93268. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93269. if (bpp === 24) {
  93270. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  93271. dataLength = width * height * 3;
  93272. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  93273. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93274. }
  93275. else { // 32
  93276. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93277. dataLength = width * height * 4;
  93278. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  93279. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93280. }
  93281. }
  93282. else if (info.isLuminance) {
  93283. var unpackAlignment = engine._getUnpackAlignement();
  93284. var unpaddedRowSize = width;
  93285. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  93286. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  93287. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  93288. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  93289. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93290. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93291. }
  93292. else {
  93293. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  93294. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  93295. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93296. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  93297. }
  93298. }
  93299. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  93300. width *= 0.5;
  93301. height *= 0.5;
  93302. width = Math.max(1.0, width);
  93303. height = Math.max(1.0, height);
  93304. }
  93305. if (currentFace !== undefined) {
  93306. // Loading a single face
  93307. break;
  93308. }
  93309. }
  93310. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  93311. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  93312. size: header[off_width],
  93313. right: sphericalPolynomialFaces[0],
  93314. left: sphericalPolynomialFaces[1],
  93315. up: sphericalPolynomialFaces[2],
  93316. down: sphericalPolynomialFaces[3],
  93317. front: sphericalPolynomialFaces[4],
  93318. back: sphericalPolynomialFaces[5],
  93319. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  93320. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  93321. gammaSpace: false,
  93322. });
  93323. }
  93324. else {
  93325. info.sphericalPolynomial = undefined;
  93326. }
  93327. };
  93328. DDSTools.StoreLODInAlphaChannel = false;
  93329. return DDSTools;
  93330. }());
  93331. BABYLON.DDSTools = DDSTools;
  93332. })(BABYLON || (BABYLON = {}));
  93333. //# sourceMappingURL=babylon.dds.js.map
  93334. var BABYLON;
  93335. (function (BABYLON) {
  93336. /**
  93337. * Implementation of the DDS Texture Loader.
  93338. */
  93339. var DDSTextureLoader = /** @class */ (function () {
  93340. function DDSTextureLoader() {
  93341. /**
  93342. * Defines wether the loader supports cascade loading the different faces.
  93343. */
  93344. this.supportCascades = true;
  93345. }
  93346. /**
  93347. * This returns if the loader support the current file information.
  93348. * @param extension defines the file extension of the file being loaded
  93349. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93350. * @param fallback defines the fallback internal texture if any
  93351. * @param isBase64 defines whether the texture is encoded as a base64
  93352. * @param isBuffer defines whether the texture data are stored as a buffer
  93353. * @returns true if the loader can load the specified file
  93354. */
  93355. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93356. return extension.indexOf(".dds") === 0;
  93357. };
  93358. /**
  93359. * Transform the url before loading if required.
  93360. * @param rootUrl the url of the texture
  93361. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93362. * @returns the transformed texture
  93363. */
  93364. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93365. return rootUrl;
  93366. };
  93367. /**
  93368. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93369. * @param rootUrl the url of the texture
  93370. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93371. * @returns the fallback texture
  93372. */
  93373. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93374. return null;
  93375. };
  93376. /**
  93377. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93378. * @param data contains the texture data
  93379. * @param texture defines the BabylonJS internal texture
  93380. * @param createPolynomials will be true if polynomials have been requested
  93381. * @param onLoad defines the callback to trigger once the texture is ready
  93382. * @param onError defines the callback to trigger in case of error
  93383. */
  93384. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  93385. var engine = texture.getEngine();
  93386. var info;
  93387. var loadMipmap = false;
  93388. if (Array.isArray(imgs)) {
  93389. for (var index = 0; index < imgs.length; index++) {
  93390. var data_1 = imgs[index];
  93391. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  93392. texture.width = info.width;
  93393. texture.height = info.height;
  93394. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93395. engine._unpackFlipY(info.isCompressed);
  93396. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  93397. if (!info.isFourCC && info.mipmapCount === 1) {
  93398. engine.generateMipMapsForCubemap(texture);
  93399. }
  93400. }
  93401. }
  93402. else {
  93403. var data = imgs;
  93404. info = BABYLON.DDSTools.GetDDSInfo(data);
  93405. texture.width = info.width;
  93406. texture.height = info.height;
  93407. if (createPolynomials) {
  93408. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  93409. }
  93410. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93411. engine._unpackFlipY(info.isCompressed);
  93412. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  93413. if (!info.isFourCC && info.mipmapCount === 1) {
  93414. engine.generateMipMapsForCubemap(texture);
  93415. }
  93416. }
  93417. engine._setCubeMapTextureParams(loadMipmap);
  93418. texture.isReady = true;
  93419. if (onLoad) {
  93420. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  93421. }
  93422. };
  93423. /**
  93424. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93425. * @param data contains the texture data
  93426. * @param texture defines the BabylonJS internal texture
  93427. * @param callback defines the method to call once ready to upload
  93428. */
  93429. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  93430. var info = BABYLON.DDSTools.GetDDSInfo(data);
  93431. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  93432. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  93433. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  93434. });
  93435. };
  93436. return DDSTextureLoader;
  93437. }());
  93438. // Register the loader.
  93439. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  93440. })(BABYLON || (BABYLON = {}));
  93441. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  93442. var BABYLON;
  93443. (function (BABYLON) {
  93444. /*
  93445. * Based on jsTGALoader - Javascript loader for TGA file
  93446. * By Vincent Thibault
  93447. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  93448. */
  93449. var TGATools = /** @class */ (function () {
  93450. function TGATools() {
  93451. }
  93452. TGATools.GetTGAHeader = function (data) {
  93453. var offset = 0;
  93454. var header = {
  93455. id_length: data[offset++],
  93456. colormap_type: data[offset++],
  93457. image_type: data[offset++],
  93458. colormap_index: data[offset++] | data[offset++] << 8,
  93459. colormap_length: data[offset++] | data[offset++] << 8,
  93460. colormap_size: data[offset++],
  93461. origin: [
  93462. data[offset++] | data[offset++] << 8,
  93463. data[offset++] | data[offset++] << 8
  93464. ],
  93465. width: data[offset++] | data[offset++] << 8,
  93466. height: data[offset++] | data[offset++] << 8,
  93467. pixel_size: data[offset++],
  93468. flags: data[offset++]
  93469. };
  93470. return header;
  93471. };
  93472. /**
  93473. * Uploads TGA content to a Babylon Texture
  93474. * @hidden
  93475. */
  93476. TGATools.UploadContent = function (texture, data) {
  93477. // Not enough data to contain header ?
  93478. if (data.length < 19) {
  93479. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  93480. return;
  93481. }
  93482. // Read Header
  93483. var offset = 18;
  93484. var header = TGATools.GetTGAHeader(data);
  93485. // Assume it's a valid Targa file.
  93486. if (header.id_length + offset > data.length) {
  93487. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  93488. return;
  93489. }
  93490. // Skip not needed data
  93491. offset += header.id_length;
  93492. var use_rle = false;
  93493. var use_pal = false;
  93494. var use_grey = false;
  93495. // Get some informations.
  93496. switch (header.image_type) {
  93497. case TGATools._TYPE_RLE_INDEXED:
  93498. use_rle = true;
  93499. case TGATools._TYPE_INDEXED:
  93500. use_pal = true;
  93501. break;
  93502. case TGATools._TYPE_RLE_RGB:
  93503. use_rle = true;
  93504. case TGATools._TYPE_RGB:
  93505. // use_rgb = true;
  93506. break;
  93507. case TGATools._TYPE_RLE_GREY:
  93508. use_rle = true;
  93509. case TGATools._TYPE_GREY:
  93510. use_grey = true;
  93511. break;
  93512. }
  93513. var pixel_data;
  93514. // var numAlphaBits = header.flags & 0xf;
  93515. var pixel_size = header.pixel_size >> 3;
  93516. var pixel_total = header.width * header.height * pixel_size;
  93517. // Read palettes
  93518. var palettes;
  93519. if (use_pal) {
  93520. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  93521. }
  93522. // Read LRE
  93523. if (use_rle) {
  93524. pixel_data = new Uint8Array(pixel_total);
  93525. var c, count, i;
  93526. var localOffset = 0;
  93527. var pixels = new Uint8Array(pixel_size);
  93528. while (offset < pixel_total && localOffset < pixel_total) {
  93529. c = data[offset++];
  93530. count = (c & 0x7f) + 1;
  93531. // RLE pixels
  93532. if (c & 0x80) {
  93533. // Bind pixel tmp array
  93534. for (i = 0; i < pixel_size; ++i) {
  93535. pixels[i] = data[offset++];
  93536. }
  93537. // Copy pixel array
  93538. for (i = 0; i < count; ++i) {
  93539. pixel_data.set(pixels, localOffset + i * pixel_size);
  93540. }
  93541. localOffset += pixel_size * count;
  93542. }
  93543. // Raw pixels
  93544. else {
  93545. count *= pixel_size;
  93546. for (i = 0; i < count; ++i) {
  93547. pixel_data[localOffset + i] = data[offset++];
  93548. }
  93549. localOffset += count;
  93550. }
  93551. }
  93552. }
  93553. // RAW Pixels
  93554. else {
  93555. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  93556. }
  93557. // Load to texture
  93558. var x_start, y_start, x_step, y_step, y_end, x_end;
  93559. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  93560. default:
  93561. case TGATools._ORIGIN_UL:
  93562. x_start = 0;
  93563. x_step = 1;
  93564. x_end = header.width;
  93565. y_start = 0;
  93566. y_step = 1;
  93567. y_end = header.height;
  93568. break;
  93569. case TGATools._ORIGIN_BL:
  93570. x_start = 0;
  93571. x_step = 1;
  93572. x_end = header.width;
  93573. y_start = header.height - 1;
  93574. y_step = -1;
  93575. y_end = -1;
  93576. break;
  93577. case TGATools._ORIGIN_UR:
  93578. x_start = header.width - 1;
  93579. x_step = -1;
  93580. x_end = -1;
  93581. y_start = 0;
  93582. y_step = 1;
  93583. y_end = header.height;
  93584. break;
  93585. case TGATools._ORIGIN_BR:
  93586. x_start = header.width - 1;
  93587. x_step = -1;
  93588. x_end = -1;
  93589. y_start = header.height - 1;
  93590. y_step = -1;
  93591. y_end = -1;
  93592. break;
  93593. }
  93594. // Load the specify method
  93595. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  93596. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  93597. var engine = texture.getEngine();
  93598. engine._uploadDataToTextureDirectly(texture, imageData);
  93599. };
  93600. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93601. var image = pixel_data, colormap = palettes;
  93602. var width = header.width, height = header.height;
  93603. var color, i = 0, x, y;
  93604. var imageData = new Uint8Array(width * height * 4);
  93605. for (y = y_start; y !== y_end; y += y_step) {
  93606. for (x = x_start; x !== x_end; x += x_step, i++) {
  93607. color = image[i];
  93608. imageData[(x + width * y) * 4 + 3] = 255;
  93609. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  93610. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  93611. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  93612. }
  93613. }
  93614. return imageData;
  93615. };
  93616. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93617. var image = pixel_data;
  93618. var width = header.width, height = header.height;
  93619. var color, i = 0, x, y;
  93620. var imageData = new Uint8Array(width * height * 4);
  93621. for (y = y_start; y !== y_end; y += y_step) {
  93622. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93623. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  93624. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  93625. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  93626. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  93627. imageData[(x + width * y) * 4 + 0] = r;
  93628. imageData[(x + width * y) * 4 + 1] = g;
  93629. imageData[(x + width * y) * 4 + 2] = b;
  93630. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  93631. }
  93632. }
  93633. return imageData;
  93634. };
  93635. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93636. var image = pixel_data;
  93637. var width = header.width, height = header.height;
  93638. var i = 0, x, y;
  93639. var imageData = new Uint8Array(width * height * 4);
  93640. for (y = y_start; y !== y_end; y += y_step) {
  93641. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  93642. imageData[(x + width * y) * 4 + 3] = 255;
  93643. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93644. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93645. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93646. }
  93647. }
  93648. return imageData;
  93649. };
  93650. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93651. var image = pixel_data;
  93652. var width = header.width, height = header.height;
  93653. var i = 0, x, y;
  93654. var imageData = new Uint8Array(width * height * 4);
  93655. for (y = y_start; y !== y_end; y += y_step) {
  93656. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  93657. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93658. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93659. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93660. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  93661. }
  93662. }
  93663. return imageData;
  93664. };
  93665. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93666. var image = pixel_data;
  93667. var width = header.width, height = header.height;
  93668. var color, i = 0, x, y;
  93669. var imageData = new Uint8Array(width * height * 4);
  93670. for (y = y_start; y !== y_end; y += y_step) {
  93671. for (x = x_start; x !== x_end; x += x_step, i++) {
  93672. color = image[i];
  93673. imageData[(x + width * y) * 4 + 0] = color;
  93674. imageData[(x + width * y) * 4 + 1] = color;
  93675. imageData[(x + width * y) * 4 + 2] = color;
  93676. imageData[(x + width * y) * 4 + 3] = 255;
  93677. }
  93678. }
  93679. return imageData;
  93680. };
  93681. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93682. var image = pixel_data;
  93683. var width = header.width, height = header.height;
  93684. var i = 0, x, y;
  93685. var imageData = new Uint8Array(width * height * 4);
  93686. for (y = y_start; y !== y_end; y += y_step) {
  93687. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93688. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  93689. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  93690. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93691. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  93692. }
  93693. }
  93694. return imageData;
  93695. };
  93696. //private static _TYPE_NO_DATA = 0;
  93697. TGATools._TYPE_INDEXED = 1;
  93698. TGATools._TYPE_RGB = 2;
  93699. TGATools._TYPE_GREY = 3;
  93700. TGATools._TYPE_RLE_INDEXED = 9;
  93701. TGATools._TYPE_RLE_RGB = 10;
  93702. TGATools._TYPE_RLE_GREY = 11;
  93703. TGATools._ORIGIN_MASK = 0x30;
  93704. TGATools._ORIGIN_SHIFT = 0x04;
  93705. TGATools._ORIGIN_BL = 0x00;
  93706. TGATools._ORIGIN_BR = 0x01;
  93707. TGATools._ORIGIN_UL = 0x02;
  93708. TGATools._ORIGIN_UR = 0x03;
  93709. return TGATools;
  93710. }());
  93711. BABYLON.TGATools = TGATools;
  93712. })(BABYLON || (BABYLON = {}));
  93713. //# sourceMappingURL=babylon.tga.js.map
  93714. var BABYLON;
  93715. (function (BABYLON) {
  93716. /**
  93717. * Implementation of the TGA Texture Loader.
  93718. */
  93719. var TGATextureLoader = /** @class */ (function () {
  93720. function TGATextureLoader() {
  93721. /**
  93722. * Defines wether the loader supports cascade loading the different faces.
  93723. */
  93724. this.supportCascades = false;
  93725. }
  93726. /**
  93727. * This returns if the loader support the current file information.
  93728. * @param extension defines the file extension of the file being loaded
  93729. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93730. * @param fallback defines the fallback internal texture if any
  93731. * @param isBase64 defines whether the texture is encoded as a base64
  93732. * @param isBuffer defines whether the texture data are stored as a buffer
  93733. * @returns true if the loader can load the specified file
  93734. */
  93735. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93736. return extension.indexOf(".tga") === 0;
  93737. };
  93738. /**
  93739. * Transform the url before loading if required.
  93740. * @param rootUrl the url of the texture
  93741. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93742. * @returns the transformed texture
  93743. */
  93744. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93745. return rootUrl;
  93746. };
  93747. /**
  93748. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93749. * @param rootUrl the url of the texture
  93750. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93751. * @returns the fallback texture
  93752. */
  93753. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93754. return null;
  93755. };
  93756. /**
  93757. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93758. * @param data contains the texture data
  93759. * @param texture defines the BabylonJS internal texture
  93760. * @param createPolynomials will be true if polynomials have been requested
  93761. * @param onLoad defines the callback to trigger once the texture is ready
  93762. * @param onError defines the callback to trigger in case of error
  93763. */
  93764. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93765. throw ".env not supported in Cube.";
  93766. };
  93767. /**
  93768. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93769. * @param data contains the texture data
  93770. * @param texture defines the BabylonJS internal texture
  93771. * @param callback defines the method to call once ready to upload
  93772. */
  93773. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  93774. var uintData = new Uint8Array(data);
  93775. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  93776. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  93777. BABYLON.TGATools.UploadContent(texture, uintData);
  93778. });
  93779. };
  93780. return TGATextureLoader;
  93781. }());
  93782. // Register the loader.
  93783. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  93784. })(BABYLON || (BABYLON = {}));
  93785. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  93786. var BABYLON;
  93787. (function (BABYLON) {
  93788. /**
  93789. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  93790. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  93791. */
  93792. var KhronosTextureContainer = /** @class */ (function () {
  93793. /**
  93794. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  93795. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  93796. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  93797. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  93798. */
  93799. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  93800. this.arrayBuffer = arrayBuffer;
  93801. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  93802. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  93803. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  93804. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  93805. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  93806. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  93807. BABYLON.Tools.Error("texture missing KTX identifier");
  93808. return;
  93809. }
  93810. // load the reset of the header in native 32 bit int
  93811. var header = new Int32Array(this.arrayBuffer, 12, 13);
  93812. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  93813. var oppositeEndianess = header[0] === 0x01020304;
  93814. // read all the header elements in order they exist in the file, without modification (sans endainness)
  93815. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  93816. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  93817. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  93818. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  93819. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  93820. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  93821. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  93822. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  93823. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  93824. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  93825. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  93826. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  93827. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  93828. if (this.glType !== 0) {
  93829. BABYLON.Tools.Error("only compressed formats currently supported");
  93830. return;
  93831. }
  93832. else {
  93833. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  93834. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  93835. }
  93836. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  93837. BABYLON.Tools.Error("only 2D textures currently supported");
  93838. return;
  93839. }
  93840. if (this.numberOfArrayElements !== 0) {
  93841. BABYLON.Tools.Error("texture arrays not currently supported");
  93842. return;
  93843. }
  93844. if (this.numberOfFaces !== facesExpected) {
  93845. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  93846. return;
  93847. }
  93848. // we now have a completely validated file, so could use existence of loadType as success
  93849. // would need to make this more elaborate & adjust checks above to support more than one load type
  93850. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  93851. }
  93852. // not as fast hardware based, but will probably never need to use
  93853. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  93854. return ((val & 0xFF) << 24)
  93855. | ((val & 0xFF00) << 8)
  93856. | ((val >> 8) & 0xFF00)
  93857. | ((val >> 24) & 0xFF);
  93858. };
  93859. /**
  93860. * Uploads KTX content to a Babylon Texture.
  93861. * It is assumed that the texture has already been created & is currently bound
  93862. * @hidden
  93863. */
  93864. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  93865. switch (this.loadType) {
  93866. case KhronosTextureContainer.COMPRESSED_2D:
  93867. this._upload2DCompressedLevels(texture, loadMipmaps);
  93868. break;
  93869. case KhronosTextureContainer.TEX_2D:
  93870. case KhronosTextureContainer.COMPRESSED_3D:
  93871. case KhronosTextureContainer.TEX_3D:
  93872. }
  93873. };
  93874. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  93875. // initialize width & height for level 1
  93876. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  93877. var width = this.pixelWidth;
  93878. var height = this.pixelHeight;
  93879. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  93880. for (var level = 0; level < mipmapCount; level++) {
  93881. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  93882. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  93883. for (var face = 0; face < this.numberOfFaces; face++) {
  93884. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  93885. var engine = texture.getEngine();
  93886. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  93887. dataOffset += imageSize; // add size of the image for the next face/mipmap
  93888. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  93889. }
  93890. width = Math.max(1.0, width * 0.5);
  93891. height = Math.max(1.0, height * 0.5);
  93892. }
  93893. };
  93894. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  93895. // load types
  93896. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  93897. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  93898. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  93899. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  93900. return KhronosTextureContainer;
  93901. }());
  93902. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  93903. })(BABYLON || (BABYLON = {}));
  93904. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  93905. var BABYLON;
  93906. (function (BABYLON) {
  93907. /**
  93908. * Implementation of the KTX Texture Loader.
  93909. */
  93910. var KTXTextureLoader = /** @class */ (function () {
  93911. function KTXTextureLoader() {
  93912. /**
  93913. * Defines wether the loader supports cascade loading the different faces.
  93914. */
  93915. this.supportCascades = false;
  93916. }
  93917. /**
  93918. * This returns if the loader support the current file information.
  93919. * @param extension defines the file extension of the file being loaded
  93920. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93921. * @param fallback defines the fallback internal texture if any
  93922. * @param isBase64 defines whether the texture is encoded as a base64
  93923. * @param isBuffer defines whether the texture data are stored as a buffer
  93924. * @returns true if the loader can load the specified file
  93925. */
  93926. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93927. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  93928. return true;
  93929. }
  93930. return false;
  93931. };
  93932. /**
  93933. * Transform the url before loading if required.
  93934. * @param rootUrl the url of the texture
  93935. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93936. * @returns the transformed texture
  93937. */
  93938. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93939. var lastDot = rootUrl.lastIndexOf('.');
  93940. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  93941. };
  93942. /**
  93943. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93944. * @param rootUrl the url of the texture
  93945. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93946. * @returns the fallback texture
  93947. */
  93948. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93949. // remove the format appended to the rootUrl in the original createCubeTexture call.
  93950. var exp = new RegExp("" + textureFormatInUse + "$");
  93951. return rootUrl.replace(exp, "");
  93952. };
  93953. /**
  93954. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93955. * @param data contains the texture data
  93956. * @param texture defines the BabylonJS internal texture
  93957. * @param createPolynomials will be true if polynomials have been requested
  93958. * @param onLoad defines the callback to trigger once the texture is ready
  93959. * @param onError defines the callback to trigger in case of error
  93960. */
  93961. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93962. if (Array.isArray(data)) {
  93963. return;
  93964. }
  93965. var engine = texture.getEngine();
  93966. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  93967. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  93968. engine._unpackFlipY(true);
  93969. ktx.uploadLevels(texture, texture.generateMipMaps);
  93970. texture.width = ktx.pixelWidth;
  93971. texture.height = ktx.pixelHeight;
  93972. engine._setCubeMapTextureParams(loadMipmap);
  93973. texture.isReady = true;
  93974. };
  93975. /**
  93976. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93977. * @param data contains the texture data
  93978. * @param texture defines the BabylonJS internal texture
  93979. * @param callback defines the method to call once ready to upload
  93980. */
  93981. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  93982. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  93983. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  93984. ktx.uploadLevels(texture, texture.generateMipMaps);
  93985. });
  93986. };
  93987. return KTXTextureLoader;
  93988. }());
  93989. // Register the loader.
  93990. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  93991. })(BABYLON || (BABYLON = {}));
  93992. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  93993. var BABYLON;
  93994. (function (BABYLON) {
  93995. /**
  93996. * Sets of helpers addressing the serialization and deserialization of environment texture
  93997. * stored in a BabylonJS env file.
  93998. * Those files are usually stored as .env files.
  93999. */
  94000. var EnvironmentTextureTools = /** @class */ (function () {
  94001. function EnvironmentTextureTools() {
  94002. }
  94003. /**
  94004. * Gets the environment info from an env file.
  94005. * @param data The array buffer containing the .env bytes.
  94006. * @returns the environment file info (the json header) if successfully parsed.
  94007. */
  94008. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94009. var dataView = new DataView(data);
  94010. var pos = 0;
  94011. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94012. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94013. BABYLON.Tools.Error('Not a babylon environment map');
  94014. return null;
  94015. }
  94016. }
  94017. // Read json manifest - collect characters up to null terminator
  94018. var manifestString = '';
  94019. var charCode = 0x00;
  94020. while ((charCode = dataView.getUint8(pos++))) {
  94021. manifestString += String.fromCharCode(charCode);
  94022. }
  94023. var manifest = JSON.parse(manifestString);
  94024. if (manifest.specular) {
  94025. // Extend the header with the position of the payload.
  94026. manifest.specular.specularDataPosition = pos;
  94027. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94028. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94029. }
  94030. return manifest;
  94031. };
  94032. /**
  94033. * Creates an environment texture from a loaded cube texture.
  94034. * @param texture defines the cube texture to convert in env file
  94035. * @return a promise containing the environment data if succesfull.
  94036. */
  94037. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94038. var _this = this;
  94039. var internalTexture = texture.getInternalTexture();
  94040. if (!internalTexture) {
  94041. return Promise.reject("The cube texture is invalid.");
  94042. }
  94043. if (!texture._prefiltered) {
  94044. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94045. }
  94046. var engine = internalTexture.getEngine();
  94047. if (engine && engine.premultipliedAlpha) {
  94048. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94049. }
  94050. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94051. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94052. }
  94053. var canvas = engine.getRenderingCanvas();
  94054. if (!canvas) {
  94055. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94056. }
  94057. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94058. if (!engine.getCaps().textureFloatRender) {
  94059. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94060. if (!engine.getCaps().textureHalfFloatRender) {
  94061. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94062. }
  94063. }
  94064. var cubeWidth = internalTexture.width;
  94065. var hostingScene = new BABYLON.Scene(engine);
  94066. var specularTextures = {};
  94067. var promises = [];
  94068. // Read and collect all mipmaps data from the cube.
  94069. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94070. mipmapsCount = Math.round(mipmapsCount);
  94071. var _loop_1 = function (i) {
  94072. var faceWidth = Math.pow(2, mipmapsCount - i);
  94073. var _loop_2 = function (face) {
  94074. var data = texture.readPixels(face, i);
  94075. // Creates a temp texture with the face data.
  94076. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94077. // And rgbdEncode them.
  94078. var promise = new Promise(function (resolve, reject) {
  94079. 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);
  94080. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94081. rgbdPostProcess.onApply = function (effect) {
  94082. effect._bindTexture("textureSampler", tempTexture);
  94083. };
  94084. // As the process needs to happen on the main canvas, keep track of the current size
  94085. var currentW = engine.getRenderWidth();
  94086. var currentH = engine.getRenderHeight();
  94087. // Set the desired size for the texture
  94088. engine.setSize(faceWidth, faceWidth);
  94089. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94090. // Reading datas from WebGL
  94091. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94092. var fileReader = new FileReader();
  94093. fileReader.onload = function (event) {
  94094. var arrayBuffer = event.target.result;
  94095. specularTextures[i * 6 + face] = arrayBuffer;
  94096. resolve();
  94097. };
  94098. fileReader.readAsArrayBuffer(blob);
  94099. });
  94100. // Reapply the previous canvas size
  94101. engine.setSize(currentW, currentH);
  94102. });
  94103. });
  94104. promises.push(promise);
  94105. };
  94106. // All faces of the cube.
  94107. for (var face = 0; face < 6; face++) {
  94108. _loop_2(face);
  94109. }
  94110. };
  94111. for (var i = 0; i <= mipmapsCount; i++) {
  94112. _loop_1(i);
  94113. }
  94114. // Once all the textures haves been collected as RGBD stored in PNGs
  94115. return Promise.all(promises).then(function () {
  94116. // We can delete the hosting scene keeping track of all the creation objects
  94117. hostingScene.dispose();
  94118. // Creates the json header for the env texture
  94119. var info = {
  94120. version: 1,
  94121. width: cubeWidth,
  94122. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94123. specular: {
  94124. mipmaps: [],
  94125. lodGenerationScale: texture.lodGenerationScale
  94126. }
  94127. };
  94128. // Sets the specular image data information
  94129. var position = 0;
  94130. for (var i = 0; i <= mipmapsCount; i++) {
  94131. for (var face = 0; face < 6; face++) {
  94132. var byteLength = specularTextures[i * 6 + face].byteLength;
  94133. info.specular.mipmaps.push({
  94134. length: byteLength,
  94135. position: position
  94136. });
  94137. position += byteLength;
  94138. }
  94139. }
  94140. // Encode the JSON as an array buffer
  94141. var infoString = JSON.stringify(info);
  94142. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94143. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94144. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94145. infoView[i] = infoString.charCodeAt(i);
  94146. }
  94147. // Ends up with a null terminator for easier parsing
  94148. infoView[infoString.length] = 0x00;
  94149. // Computes the final required size and creates the storage
  94150. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  94151. var finalBuffer = new ArrayBuffer(totalSize);
  94152. var finalBufferView = new Uint8Array(finalBuffer);
  94153. var dataView = new DataView(finalBuffer);
  94154. // Copy the magic bytes identifying the file in
  94155. var pos = 0;
  94156. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94157. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  94158. }
  94159. // Add the json info
  94160. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  94161. pos += infoBuffer.byteLength;
  94162. // Finally inserts the texture data
  94163. for (var i = 0; i <= mipmapsCount; i++) {
  94164. for (var face = 0; face < 6; face++) {
  94165. var dataBuffer = specularTextures[i * 6 + face];
  94166. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  94167. pos += dataBuffer.byteLength;
  94168. }
  94169. }
  94170. // Voila
  94171. return finalBuffer;
  94172. });
  94173. };
  94174. /**
  94175. * Creates a JSON representation of the spherical data.
  94176. * @param texture defines the texture containing the polynomials
  94177. * @return the JSON representation of the spherical info
  94178. */
  94179. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  94180. var polynmials = texture.sphericalPolynomial;
  94181. if (polynmials == null) {
  94182. return null;
  94183. }
  94184. return {
  94185. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  94186. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  94187. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  94188. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  94189. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  94190. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  94191. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  94192. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  94193. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  94194. };
  94195. };
  94196. /**
  94197. * Uploads the texture info contained in the env file to the GPU.
  94198. * @param texture defines the internal texture to upload to
  94199. * @param arrayBuffer defines the buffer cotaining the data to load
  94200. * @param info defines the texture info retrieved through the GetEnvInfo method
  94201. * @returns a promise
  94202. */
  94203. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  94204. if (info.version !== 1) {
  94205. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  94206. }
  94207. var specularInfo = info.specular;
  94208. if (!specularInfo) {
  94209. // Nothing else parsed so far
  94210. return Promise.resolve();
  94211. }
  94212. // Double checks the enclosed info
  94213. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  94214. mipmapsCount = Math.round(mipmapsCount) + 1;
  94215. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  94216. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  94217. }
  94218. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  94219. var imageData = new Array(mipmapsCount);
  94220. for (var i = 0; i < mipmapsCount; i++) {
  94221. imageData[i] = new Array(6);
  94222. for (var face = 0; face < 6; face++) {
  94223. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  94224. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  94225. }
  94226. }
  94227. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  94228. };
  94229. /**
  94230. * Uploads the levels of image data to the GPU.
  94231. * @param texture defines the internal texture to upload to
  94232. * @param imageData defines the array buffer views of image data [mipmap][face]
  94233. * @returns a promise
  94234. */
  94235. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  94236. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  94237. throw new Error("Texture size must be a power of two");
  94238. }
  94239. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  94240. // Gets everything ready.
  94241. var engine = texture.getEngine();
  94242. var expandTexture = false;
  94243. var generateNonLODTextures = false;
  94244. var rgbdPostProcess = null;
  94245. var cubeRtt = null;
  94246. var lodTextures = null;
  94247. var caps = engine.getCaps();
  94248. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94249. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94250. texture.generateMipMaps = true;
  94251. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  94252. // Add extra process if texture lod is not supported
  94253. if (!caps.textureLOD) {
  94254. expandTexture = false;
  94255. generateNonLODTextures = true;
  94256. lodTextures = {};
  94257. }
  94258. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  94259. else if (engine.webGLVersion < 2) {
  94260. expandTexture = false;
  94261. }
  94262. // If half float available we can uncompress the texture
  94263. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  94264. expandTexture = true;
  94265. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94266. }
  94267. // If full float available we can uncompress the texture
  94268. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  94269. expandTexture = true;
  94270. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94271. }
  94272. // Expand the texture if possible
  94273. if (expandTexture) {
  94274. // Simply run through the decode PP
  94275. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  94276. texture._isRGBD = false;
  94277. texture.invertY = false;
  94278. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  94279. generateDepthBuffer: false,
  94280. generateMipMaps: true,
  94281. generateStencilBuffer: false,
  94282. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  94283. type: texture.type,
  94284. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  94285. });
  94286. }
  94287. else {
  94288. texture._isRGBD = true;
  94289. texture.invertY = true;
  94290. // In case of missing support, applies the same patch than DDS files.
  94291. if (generateNonLODTextures) {
  94292. var mipSlices = 3;
  94293. var scale = texture._lodGenerationScale;
  94294. var offset = texture._lodGenerationOffset;
  94295. for (var i = 0; i < mipSlices; i++) {
  94296. //compute LOD from even spacing in smoothness (matching shader calculation)
  94297. var smoothness = i / (mipSlices - 1);
  94298. var roughness = 1 - smoothness;
  94299. var minLODIndex = offset; // roughness = 0
  94300. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  94301. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  94302. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  94303. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  94304. glTextureFromLod.isCube = true;
  94305. glTextureFromLod.invertY = true;
  94306. glTextureFromLod.generateMipMaps = false;
  94307. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  94308. // Wrap in a base texture for easy binding.
  94309. var lodTexture = new BABYLON.BaseTexture(null);
  94310. lodTexture.isCube = true;
  94311. lodTexture._texture = glTextureFromLod;
  94312. lodTextures[mipmapIndex] = lodTexture;
  94313. switch (i) {
  94314. case 0:
  94315. texture._lodTextureLow = lodTexture;
  94316. break;
  94317. case 1:
  94318. texture._lodTextureMid = lodTexture;
  94319. break;
  94320. case 2:
  94321. texture._lodTextureHigh = lodTexture;
  94322. break;
  94323. }
  94324. }
  94325. }
  94326. }
  94327. var promises = [];
  94328. var _loop_3 = function (i) {
  94329. var _loop_4 = function (face) {
  94330. // Constructs an image element from image data
  94331. var bytes = imageData[i][face];
  94332. var blob = new Blob([bytes], { type: 'image/png' });
  94333. var url = URL.createObjectURL(blob);
  94334. var image = new Image();
  94335. image.src = url;
  94336. // Enqueue promise to upload to the texture.
  94337. var promise = new Promise(function (resolve, reject) {
  94338. image.onload = function () {
  94339. if (expandTexture) {
  94340. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  94341. reject(message);
  94342. }, image);
  94343. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94344. // Uncompress the data to a RTT
  94345. rgbdPostProcess.onApply = function (effect) {
  94346. effect._bindTexture("textureSampler", tempTexture_1);
  94347. effect.setFloat2("scale", 1, 1);
  94348. };
  94349. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  94350. // Cleanup
  94351. engine.restoreDefaultFramebuffer();
  94352. tempTexture_1.dispose();
  94353. window.URL.revokeObjectURL(url);
  94354. resolve();
  94355. });
  94356. }
  94357. else {
  94358. engine._uploadImageToTexture(texture, image, face, i);
  94359. // Upload the face to the non lod texture support
  94360. if (generateNonLODTextures) {
  94361. var lodTexture = lodTextures[i];
  94362. if (lodTexture) {
  94363. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  94364. }
  94365. }
  94366. resolve();
  94367. }
  94368. };
  94369. image.onerror = function (error) {
  94370. reject(error);
  94371. };
  94372. });
  94373. promises.push(promise);
  94374. };
  94375. // All faces
  94376. for (var face = 0; face < 6; face++) {
  94377. _loop_4(face);
  94378. }
  94379. };
  94380. // All mipmaps up to provided number of images
  94381. for (var i = 0; i < imageData.length; i++) {
  94382. _loop_3(i);
  94383. }
  94384. // Fill remaining mipmaps with black textures.
  94385. if (imageData.length < mipmapsCount) {
  94386. var data = void 0;
  94387. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  94388. var dataLength = size * size * 4;
  94389. switch (texture.type) {
  94390. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  94391. data = new Uint8Array(dataLength);
  94392. break;
  94393. }
  94394. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  94395. data = new Uint16Array(dataLength);
  94396. break;
  94397. }
  94398. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  94399. data = new Float32Array(dataLength);
  94400. break;
  94401. }
  94402. }
  94403. for (var i = imageData.length; i < mipmapsCount; i++) {
  94404. for (var face = 0; face < 6; face++) {
  94405. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  94406. }
  94407. }
  94408. }
  94409. // Once all done, finishes the cleanup and return
  94410. return Promise.all(promises).then(function () {
  94411. // Release temp RTT.
  94412. if (cubeRtt) {
  94413. engine._releaseFramebufferObjects(cubeRtt);
  94414. cubeRtt._swapAndDie(texture);
  94415. }
  94416. // Release temp Post Process.
  94417. if (rgbdPostProcess) {
  94418. rgbdPostProcess.dispose();
  94419. }
  94420. // Flag internal texture as ready in case they are in use.
  94421. if (generateNonLODTextures) {
  94422. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  94423. texture._lodTextureHigh._texture.isReady = true;
  94424. }
  94425. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  94426. texture._lodTextureMid._texture.isReady = true;
  94427. }
  94428. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  94429. texture._lodTextureLow._texture.isReady = true;
  94430. }
  94431. }
  94432. });
  94433. };
  94434. /**
  94435. * Uploads spherical polynomials information to the texture.
  94436. * @param texture defines the texture we are trying to upload the information to
  94437. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  94438. */
  94439. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  94440. if (info.version !== 1) {
  94441. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  94442. }
  94443. var irradianceInfo = info.irradiance;
  94444. if (!irradianceInfo) {
  94445. return;
  94446. }
  94447. var sp = new BABYLON.SphericalPolynomial();
  94448. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  94449. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  94450. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  94451. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  94452. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  94453. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  94454. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  94455. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  94456. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  94457. texture._sphericalPolynomial = sp;
  94458. };
  94459. /**
  94460. * Magic number identifying the env file.
  94461. */
  94462. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  94463. return EnvironmentTextureTools;
  94464. }());
  94465. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  94466. })(BABYLON || (BABYLON = {}));
  94467. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  94468. var BABYLON;
  94469. (function (BABYLON) {
  94470. /**
  94471. * Implementation of the ENV Texture Loader.
  94472. */
  94473. var ENVTextureLoader = /** @class */ (function () {
  94474. function ENVTextureLoader() {
  94475. /**
  94476. * Defines wether the loader supports cascade loading the different faces.
  94477. */
  94478. this.supportCascades = false;
  94479. }
  94480. /**
  94481. * This returns if the loader support the current file information.
  94482. * @param extension defines the file extension of the file being loaded
  94483. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94484. * @param fallback defines the fallback internal texture if any
  94485. * @param isBase64 defines whether the texture is encoded as a base64
  94486. * @param isBuffer defines whether the texture data are stored as a buffer
  94487. * @returns true if the loader can load the specified file
  94488. */
  94489. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94490. return extension.indexOf(".env") === 0;
  94491. };
  94492. /**
  94493. * Transform the url before loading if required.
  94494. * @param rootUrl the url of the texture
  94495. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94496. * @returns the transformed texture
  94497. */
  94498. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94499. return rootUrl;
  94500. };
  94501. /**
  94502. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94503. * @param rootUrl the url of the texture
  94504. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94505. * @returns the fallback texture
  94506. */
  94507. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94508. return null;
  94509. };
  94510. /**
  94511. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94512. * @param data contains the texture data
  94513. * @param texture defines the BabylonJS internal texture
  94514. * @param createPolynomials will be true if polynomials have been requested
  94515. * @param onLoad defines the callback to trigger once the texture is ready
  94516. * @param onError defines the callback to trigger in case of error
  94517. */
  94518. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94519. if (Array.isArray(data)) {
  94520. return;
  94521. }
  94522. data = data;
  94523. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  94524. if (info) {
  94525. texture.width = info.width;
  94526. texture.height = info.width;
  94527. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  94528. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  94529. texture.isReady = true;
  94530. if (onLoad) {
  94531. onLoad();
  94532. }
  94533. });
  94534. }
  94535. else if (onError) {
  94536. onError("Can not parse the environment file", null);
  94537. }
  94538. };
  94539. /**
  94540. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94541. * @param data contains the texture data
  94542. * @param texture defines the BabylonJS internal texture
  94543. * @param callback defines the method to call once ready to upload
  94544. */
  94545. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  94546. throw ".env not supported in 2d.";
  94547. };
  94548. return ENVTextureLoader;
  94549. }());
  94550. // Register the loader.
  94551. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  94552. })(BABYLON || (BABYLON = {}));
  94553. //# sourceMappingURL=babylon.envTextureLoader.js.map
  94554. var BABYLON;
  94555. (function (BABYLON) {
  94556. /**
  94557. * Renders a layer on top of an existing scene
  94558. */
  94559. var UtilityLayerRenderer = /** @class */ (function () {
  94560. /**
  94561. * Instantiates a UtilityLayerRenderer
  94562. * @param originalScene the original scene that will be rendered on top of
  94563. */
  94564. function UtilityLayerRenderer(
  94565. /** the original scene that will be rendered on top of */
  94566. originalScene) {
  94567. var _this = this;
  94568. this.originalScene = originalScene;
  94569. this._pointerCaptures = {};
  94570. this._lastPointerEvents = {};
  94571. /**
  94572. * If the utility layer should automatically be rendered on top of existing scene
  94573. */
  94574. this.shouldRender = true;
  94575. /**
  94576. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  94577. */
  94578. this.onlyCheckPointerDownEvents = true;
  94579. /**
  94580. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  94581. */
  94582. this.processAllEvents = false;
  94583. /**
  94584. * Observable raised when the pointer move from the utility layer scene to the main scene
  94585. */
  94586. this.onPointerOutObservable = new BABYLON.Observable();
  94587. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  94588. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  94589. this.utilityLayerScene._allowPostProcessClearColor = false;
  94590. originalScene.getEngine().scenes.pop();
  94591. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  94592. this.utilityLayerScene.detachControl();
  94593. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  94594. if (!_this.processAllEvents) {
  94595. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  94596. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  94597. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  94598. return;
  94599. }
  94600. }
  94601. var pointerEvent = (prePointerInfo.event);
  94602. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  94603. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94604. return;
  94605. }
  94606. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  94607. if (!prePointerInfo.ray && utilityScenePick) {
  94608. prePointerInfo.ray = utilityScenePick.ray;
  94609. }
  94610. // always fire the prepointer oversvable
  94611. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  94612. // allow every non pointer down event to flow to the utility layer
  94613. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  94614. if (!prePointerInfo.skipOnPointerObservable) {
  94615. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94616. }
  94617. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  94618. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94619. }
  94620. return;
  94621. }
  94622. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  94623. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  94624. if (utilityScenePick && utilityScenePick.hit) {
  94625. if (!prePointerInfo.skipOnPointerObservable) {
  94626. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94627. }
  94628. prePointerInfo.skipOnPointerObservable = true;
  94629. }
  94630. }
  94631. else {
  94632. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  94633. var pointerEvent_1 = (prePointerInfo.event);
  94634. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  94635. if (originalScenePick && utilityScenePick) {
  94636. // No pick in utility scene
  94637. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  94638. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94639. // We touched an utility mesh present in the main scene
  94640. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94641. prePointerInfo.skipOnPointerObservable = true;
  94642. }
  94643. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94644. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  94645. }
  94646. }
  94647. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  94648. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  94649. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  94650. // If a previous utility layer set this, do not unset this
  94651. if (!prePointerInfo.skipOnPointerObservable) {
  94652. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  94653. }
  94654. }
  94655. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  94656. // We have a pick in both scenes but main is closer than utility
  94657. // We touched an utility mesh present in the main scene
  94658. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94659. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94660. prePointerInfo.skipOnPointerObservable = true;
  94661. }
  94662. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  94663. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  94664. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  94665. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  94666. }
  94667. }
  94668. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  94669. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  94670. }
  94671. }
  94672. }
  94673. });
  94674. // Render directly on top of existing scene without clearing
  94675. this.utilityLayerScene.autoClear = false;
  94676. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  94677. if (_this.shouldRender) {
  94678. _this.render();
  94679. }
  94680. });
  94681. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  94682. _this.dispose();
  94683. });
  94684. this._updateCamera();
  94685. }
  94686. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  94687. /**
  94688. * 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)
  94689. */
  94690. get: function () {
  94691. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  94692. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94693. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94694. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94695. });
  94696. }
  94697. return UtilityLayerRenderer._DefaultUtilityLayer;
  94698. },
  94699. enumerable: true,
  94700. configurable: true
  94701. });
  94702. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  94703. /**
  94704. * 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)
  94705. */
  94706. get: function () {
  94707. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  94708. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94709. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  94710. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94711. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94712. });
  94713. }
  94714. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  94715. },
  94716. enumerable: true,
  94717. configurable: true
  94718. });
  94719. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  94720. if (!prePointerInfo.skipOnPointerObservable) {
  94721. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  94722. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  94723. }
  94724. };
  94725. /**
  94726. * Renders the utility layers scene on top of the original scene
  94727. */
  94728. UtilityLayerRenderer.prototype.render = function () {
  94729. this._updateCamera();
  94730. if (this.utilityLayerScene.activeCamera) {
  94731. // Set the camera's scene to utility layers scene
  94732. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  94733. var camera = this.utilityLayerScene.activeCamera;
  94734. camera._scene = this.utilityLayerScene;
  94735. if (camera.leftCamera) {
  94736. camera.leftCamera._scene = this.utilityLayerScene;
  94737. }
  94738. if (camera.rightCamera) {
  94739. camera.rightCamera._scene = this.utilityLayerScene;
  94740. }
  94741. this.utilityLayerScene.render(false);
  94742. // Reset camera's scene back to original
  94743. camera._scene = oldScene;
  94744. if (camera.leftCamera) {
  94745. camera.leftCamera._scene = oldScene;
  94746. }
  94747. if (camera.rightCamera) {
  94748. camera.rightCamera._scene = oldScene;
  94749. }
  94750. }
  94751. };
  94752. /**
  94753. * Disposes of the renderer
  94754. */
  94755. UtilityLayerRenderer.prototype.dispose = function () {
  94756. this.onPointerOutObservable.clear();
  94757. if (this._afterRenderObserver) {
  94758. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  94759. }
  94760. if (this._sceneDisposeObserver) {
  94761. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94762. }
  94763. if (this._originalPointerObserver) {
  94764. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  94765. }
  94766. this.utilityLayerScene.dispose();
  94767. };
  94768. UtilityLayerRenderer.prototype._updateCamera = function () {
  94769. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  94770. };
  94771. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94772. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94773. return UtilityLayerRenderer;
  94774. }());
  94775. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  94776. })(BABYLON || (BABYLON = {}));
  94777. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  94778. //# sourceMappingURL=babylon.behavior.js.map
  94779. var BABYLON;
  94780. (function (BABYLON) {
  94781. /**
  94782. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  94783. */
  94784. var PointerDragBehavior = /** @class */ (function () {
  94785. /**
  94786. * Creates a pointer drag behavior that can be attached to a mesh
  94787. * @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)
  94788. */
  94789. function PointerDragBehavior(options) {
  94790. /**
  94791. * 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)
  94792. */
  94793. this.maxDragAngle = 0;
  94794. /**
  94795. * @hidden
  94796. */
  94797. this._useAlternatePickedPointAboveMaxDragAngle = false;
  94798. /**
  94799. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  94800. */
  94801. this.currentDraggingPointerID = -1;
  94802. /**
  94803. * If the behavior is currently in a dragging state
  94804. */
  94805. this.dragging = false;
  94806. /**
  94807. * 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)
  94808. */
  94809. this.dragDeltaRatio = 0.2;
  94810. /**
  94811. * If the drag plane orientation should be updated during the dragging (Default: true)
  94812. */
  94813. this.updateDragPlane = true;
  94814. // Debug mode will display drag planes to help visualize behavior
  94815. this._debugMode = false;
  94816. this._moving = false;
  94817. /**
  94818. * Fires each time the attached mesh is dragged with the pointer
  94819. * * delta between last drag position and current drag position in world space
  94820. * * dragDistance along the drag axis
  94821. * * dragPlaneNormal normal of the current drag plane used during the drag
  94822. * * dragPlanePoint in world space where the drag intersects the drag plane
  94823. */
  94824. this.onDragObservable = new BABYLON.Observable();
  94825. /**
  94826. * Fires each time a drag begins (eg. mouse down on mesh)
  94827. */
  94828. this.onDragStartObservable = new BABYLON.Observable();
  94829. /**
  94830. * Fires each time a drag ends (eg. mouse release after drag)
  94831. */
  94832. this.onDragEndObservable = new BABYLON.Observable();
  94833. /**
  94834. * If the attached mesh should be moved when dragged
  94835. */
  94836. this.moveAttached = true;
  94837. /**
  94838. * If the drag behavior will react to drag events (Default: true)
  94839. */
  94840. this.enabled = true;
  94841. /**
  94842. * If camera controls should be detached during the drag
  94843. */
  94844. this.detachCameraControls = true;
  94845. /**
  94846. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  94847. */
  94848. this.useObjectOrienationForDragging = true;
  94849. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94850. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  94851. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  94852. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  94853. this._attachedElement = null;
  94854. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94855. this._lastPointerRay = {};
  94856. this._dragDelta = new BABYLON.Vector3();
  94857. // Variables to avoid instantiation in the below method
  94858. this._pointA = new BABYLON.Vector3(0, 0, 0);
  94859. this._pointB = new BABYLON.Vector3(0, 0, 0);
  94860. this._pointC = new BABYLON.Vector3(0, 0, 0);
  94861. this._lineA = new BABYLON.Vector3(0, 0, 0);
  94862. this._lineB = new BABYLON.Vector3(0, 0, 0);
  94863. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  94864. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  94865. this._options = options ? options : {};
  94866. var optionCount = 0;
  94867. if (this._options.dragAxis) {
  94868. optionCount++;
  94869. }
  94870. if (this._options.dragPlaneNormal) {
  94871. optionCount++;
  94872. }
  94873. if (optionCount > 1) {
  94874. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  94875. }
  94876. }
  94877. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  94878. /**
  94879. * The name of the behavior
  94880. */
  94881. get: function () {
  94882. return "PointerDrag";
  94883. },
  94884. enumerable: true,
  94885. configurable: true
  94886. });
  94887. /**
  94888. * Initializes the behavior
  94889. */
  94890. PointerDragBehavior.prototype.init = function () { };
  94891. /**
  94892. * Attaches the drag behavior the passed in mesh
  94893. * @param ownerNode The mesh that will be dragged around once attached
  94894. */
  94895. PointerDragBehavior.prototype.attach = function (ownerNode) {
  94896. var _this = this;
  94897. this._scene = ownerNode.getScene();
  94898. this._attachedNode = ownerNode;
  94899. // Initialize drag plane to not interfere with existing scene
  94900. if (!PointerDragBehavior._planeScene) {
  94901. if (this._debugMode) {
  94902. PointerDragBehavior._planeScene = this._scene;
  94903. }
  94904. else {
  94905. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  94906. PointerDragBehavior._planeScene.detachControl();
  94907. this._scene.getEngine().scenes.pop();
  94908. this._scene.onDisposeObservable.addOnce(function () {
  94909. PointerDragBehavior._planeScene.dispose();
  94910. PointerDragBehavior._planeScene = null;
  94911. });
  94912. }
  94913. }
  94914. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  94915. // State of the drag
  94916. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  94917. var pickPredicate = function (m) {
  94918. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  94919. };
  94920. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  94921. if (!_this.enabled) {
  94922. return;
  94923. }
  94924. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94925. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  94926. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  94927. }
  94928. }
  94929. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  94930. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  94931. _this.releaseDrag();
  94932. }
  94933. }
  94934. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  94935. var pointerId = pointerInfo.event.pointerId;
  94936. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  94937. if (!_this._lastPointerRay[pointerId]) {
  94938. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94939. }
  94940. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  94941. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  94942. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  94943. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  94944. _this._moveDrag(pointerInfo.pickInfo.ray);
  94945. }
  94946. }
  94947. }
  94948. });
  94949. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  94950. if (_this._moving && _this.moveAttached) {
  94951. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  94952. // Slowly move mesh to avoid jitter
  94953. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  94954. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  94955. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  94956. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  94957. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  94958. }
  94959. });
  94960. };
  94961. PointerDragBehavior.prototype.releaseDrag = function () {
  94962. this.dragging = false;
  94963. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  94964. this.currentDraggingPointerID = -1;
  94965. this._moving = false;
  94966. // Reattach camera controls
  94967. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  94968. this._scene.activeCamera.attachControl(this._attachedElement, true);
  94969. }
  94970. };
  94971. /**
  94972. * Simulates the start of a pointer drag event on the behavior
  94973. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  94974. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  94975. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  94976. */
  94977. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  94978. if (pointerId === void 0) { pointerId = 1; }
  94979. this._startDrag(pointerId, fromRay, startPickedPoint);
  94980. if (this._lastPointerRay[pointerId]) {
  94981. // if there was a last pointer ray drag the object there
  94982. this._moveDrag(this._lastPointerRay[pointerId]);
  94983. }
  94984. };
  94985. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  94986. if (pointerId === void 0) { pointerId = 1; }
  94987. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  94988. return;
  94989. }
  94990. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  94991. // Create start ray from the camera to the object
  94992. if (fromRay) {
  94993. this._startDragRay.direction.copyFrom(fromRay.direction);
  94994. this._startDragRay.origin.copyFrom(fromRay.origin);
  94995. }
  94996. else {
  94997. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  94998. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  94999. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95000. }
  95001. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95002. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95003. if (pickedPoint) {
  95004. this.dragging = true;
  95005. this.currentDraggingPointerID = pointerId;
  95006. this.lastDragPosition.copyFrom(pickedPoint);
  95007. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95008. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95009. // Detatch camera controls
  95010. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95011. if (this._scene.activeCamera.inputs.attachedElement) {
  95012. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95013. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95014. }
  95015. else {
  95016. this._attachedElement = null;
  95017. }
  95018. }
  95019. }
  95020. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95021. };
  95022. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95023. this._moving = true;
  95024. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95025. if (pickedPoint) {
  95026. if (this.updateDragPlane) {
  95027. this._updateDragPlanePosition(ray, pickedPoint);
  95028. }
  95029. var dragLength = 0;
  95030. // depending on the drag mode option drag accordingly
  95031. if (this._options.dragAxis) {
  95032. // Convert local drag axis to world
  95033. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95034. // Project delta drag from the drag plane onto the drag axis
  95035. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95036. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95037. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95038. }
  95039. else {
  95040. dragLength = this._dragDelta.length();
  95041. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95042. }
  95043. this._targetPosition.addInPlace(this._dragDelta);
  95044. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95045. this.lastDragPosition.copyFrom(pickedPoint);
  95046. }
  95047. };
  95048. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95049. var _this = this;
  95050. if (!ray) {
  95051. return null;
  95052. }
  95053. // Calculate angle between plane normal and ray
  95054. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95055. // Correct if ray is casted from oposite side
  95056. if (angle > Math.PI / 2) {
  95057. angle = Math.PI - angle;
  95058. }
  95059. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95060. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95061. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95062. // Invert ray direction along the towards object axis
  95063. this._tmpVector.copyFrom(ray.direction);
  95064. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95065. this._alternatePickedPoint.normalize();
  95066. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95067. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95068. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95069. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95070. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95071. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95072. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95073. return this._alternatePickedPoint;
  95074. }
  95075. else {
  95076. return null;
  95077. }
  95078. }
  95079. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95080. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95081. return pickResult.pickedPoint;
  95082. }
  95083. else {
  95084. return null;
  95085. }
  95086. };
  95087. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95088. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95089. this._pointA.copyFrom(dragPlanePosition);
  95090. if (this._options.dragAxis) {
  95091. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95092. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95093. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95094. ray.origin.subtractToRef(this._pointA, this._pointC);
  95095. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95096. // Get perpendicular line from direction to camera and drag axis
  95097. this._pointB.subtractToRef(this._pointA, this._lineA);
  95098. this._pointC.subtractToRef(this._pointA, this._lineB);
  95099. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95100. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95101. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95102. this._lookAt.normalize();
  95103. this._dragPlane.position.copyFrom(this._pointA);
  95104. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95105. this._dragPlane.lookAt(this._lookAt);
  95106. }
  95107. else if (this._options.dragPlaneNormal) {
  95108. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95109. this._dragPlane.position.copyFrom(this._pointA);
  95110. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95111. this._dragPlane.lookAt(this._lookAt);
  95112. }
  95113. else {
  95114. this._dragPlane.position.copyFrom(this._pointA);
  95115. this._dragPlane.lookAt(ray.origin);
  95116. }
  95117. this._dragPlane.computeWorldMatrix(true);
  95118. };
  95119. /**
  95120. * Detaches the behavior from the mesh
  95121. */
  95122. PointerDragBehavior.prototype.detach = function () {
  95123. if (this._pointerObserver) {
  95124. this._scene.onPointerObservable.remove(this._pointerObserver);
  95125. }
  95126. if (this._beforeRenderObserver) {
  95127. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95128. }
  95129. };
  95130. return PointerDragBehavior;
  95131. }());
  95132. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95133. })(BABYLON || (BABYLON = {}));
  95134. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95135. var BABYLON;
  95136. (function (BABYLON) {
  95137. /**
  95138. * A behavior that when attached to a mesh will allow the mesh to be scaled
  95139. */
  95140. var MultiPointerScaleBehavior = /** @class */ (function () {
  95141. function MultiPointerScaleBehavior() {
  95142. this._startDistance = 0;
  95143. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  95144. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  95145. this._sceneRenderObserver = null;
  95146. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  95147. this._dragBehaviorA.moveAttached = false;
  95148. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  95149. this._dragBehaviorB.moveAttached = false;
  95150. }
  95151. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  95152. /**
  95153. * The name of the behavior
  95154. */
  95155. get: function () {
  95156. return "MultiPointerScale";
  95157. },
  95158. enumerable: true,
  95159. configurable: true
  95160. });
  95161. /**
  95162. * Initializes the behavior
  95163. */
  95164. MultiPointerScaleBehavior.prototype.init = function () { };
  95165. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  95166. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  95167. };
  95168. /**
  95169. * Attaches the scale behavior the passed in mesh
  95170. * @param ownerNode The mesh that will be scaled around once attached
  95171. */
  95172. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  95173. var _this = this;
  95174. this._ownerNode = ownerNode;
  95175. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  95176. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  95177. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95178. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95179. _this._dragBehaviorA.releaseDrag();
  95180. }
  95181. else {
  95182. _this._initialScale.copyFrom(ownerNode.scaling);
  95183. _this._startDistance = _this._getCurrentDistance();
  95184. }
  95185. }
  95186. });
  95187. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  95188. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95189. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  95190. _this._dragBehaviorB.releaseDrag();
  95191. }
  95192. else {
  95193. _this._initialScale.copyFrom(ownerNode.scaling);
  95194. _this._startDistance = _this._getCurrentDistance();
  95195. }
  95196. }
  95197. });
  95198. // Once both drag behaviors are active scale based on the distance between the two pointers
  95199. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95200. behavior.onDragObservable.add(function () {
  95201. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95202. var ratio = _this._getCurrentDistance() / _this._startDistance;
  95203. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  95204. }
  95205. });
  95206. });
  95207. ownerNode.addBehavior(this._dragBehaviorA);
  95208. ownerNode.addBehavior(this._dragBehaviorB);
  95209. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95210. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95211. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95212. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  95213. if (change.length() > 0.01) {
  95214. ownerNode.scaling.addInPlace(change);
  95215. }
  95216. }
  95217. });
  95218. };
  95219. /**
  95220. * Detaches the behavior from the mesh
  95221. */
  95222. MultiPointerScaleBehavior.prototype.detach = function () {
  95223. var _this = this;
  95224. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95225. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95226. behavior.onDragStartObservable.clear();
  95227. behavior.onDragObservable.clear();
  95228. _this._ownerNode.removeBehavior(behavior);
  95229. });
  95230. };
  95231. return MultiPointerScaleBehavior;
  95232. }());
  95233. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  95234. })(BABYLON || (BABYLON = {}));
  95235. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  95236. var BABYLON;
  95237. (function (BABYLON) {
  95238. /**
  95239. * 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
  95240. */
  95241. var SixDofDragBehavior = /** @class */ (function () {
  95242. function SixDofDragBehavior() {
  95243. this._sceneRenderObserver = null;
  95244. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95245. this._moving = false;
  95246. this._startingOrientation = new BABYLON.Quaternion();
  95247. /**
  95248. * 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)
  95249. */
  95250. this.zDragFactor = 3;
  95251. /**
  95252. * If the behavior is currently in a dragging state
  95253. */
  95254. this.dragging = false;
  95255. /**
  95256. * 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)
  95257. */
  95258. this.dragDeltaRatio = 0.2;
  95259. /**
  95260. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95261. */
  95262. this.currentDraggingPointerID = -1;
  95263. /**
  95264. * If camera controls should be detached during the drag
  95265. */
  95266. this.detachCameraControls = true;
  95267. /**
  95268. * Fires each time a drag starts
  95269. */
  95270. this.onDragStartObservable = new BABYLON.Observable();
  95271. /**
  95272. * Fires each time a drag ends (eg. mouse release after drag)
  95273. */
  95274. this.onDragEndObservable = new BABYLON.Observable();
  95275. }
  95276. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  95277. /**
  95278. * The name of the behavior
  95279. */
  95280. get: function () {
  95281. return "SixDofDrag";
  95282. },
  95283. enumerable: true,
  95284. configurable: true
  95285. });
  95286. /**
  95287. * Initializes the behavior
  95288. */
  95289. SixDofDragBehavior.prototype.init = function () { };
  95290. /**
  95291. * Attaches the scale behavior the passed in mesh
  95292. * @param ownerNode The mesh that will be scaled around once attached
  95293. */
  95294. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  95295. var _this = this;
  95296. this._ownerNode = ownerNode;
  95297. this._scene = this._ownerNode.getScene();
  95298. if (!SixDofDragBehavior._virtualScene) {
  95299. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  95300. this._scene.getEngine().scenes.pop();
  95301. }
  95302. var pickedMesh = null;
  95303. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  95304. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  95305. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95306. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  95307. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95308. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  95309. var pickPredicate = function (m) {
  95310. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  95311. };
  95312. var attachedElement = null;
  95313. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95314. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95315. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95316. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95317. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95318. }
  95319. pickedMesh = _this._ownerNode;
  95320. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95321. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95322. // Set position and orientation of the controller
  95323. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95324. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95325. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  95326. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95327. pickedMesh.computeWorldMatrix();
  95328. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  95329. if (!pickedMesh.rotationQuaternion) {
  95330. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  95331. }
  95332. var oldParent = pickedMesh.parent;
  95333. pickedMesh.setParent(null);
  95334. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  95335. pickedMesh.setParent(oldParent);
  95336. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95337. // Update state
  95338. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95339. _this.dragging = true;
  95340. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  95341. // Detatch camera controls
  95342. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95343. if (_this._scene.activeCamera.inputs.attachedElement) {
  95344. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  95345. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  95346. }
  95347. else {
  95348. attachedElement = null;
  95349. }
  95350. }
  95351. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95352. _this.onDragStartObservable.notifyObservers({});
  95353. }
  95354. }
  95355. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95356. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95357. _this.dragging = false;
  95358. _this._moving = false;
  95359. _this.currentDraggingPointerID = -1;
  95360. pickedMesh = null;
  95361. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95362. // Reattach camera controls
  95363. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95364. _this._scene.activeCamera.attachControl(attachedElement, true);
  95365. }
  95366. _this.onDragEndObservable.notifyObservers({});
  95367. }
  95368. }
  95369. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95370. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  95371. var zDragFactor = _this.zDragFactor;
  95372. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95373. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95374. zDragFactor = 0;
  95375. }
  95376. // Calculate controller drag distance in controller space
  95377. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  95378. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95379. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  95380. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95381. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  95382. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  95383. if (_this._virtualDragMesh.position.z < 0) {
  95384. _this._virtualDragMesh.position.z = 0;
  95385. }
  95386. // Update the controller position
  95387. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95388. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95389. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95390. // Move the virtualObjectsPosition into the picked mesh's space if needed
  95391. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95392. if (pickedMesh.parent) {
  95393. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  95394. }
  95395. if (!_this._moving) {
  95396. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  95397. }
  95398. _this._moving = true;
  95399. }
  95400. }
  95401. });
  95402. var tmpQuaternion = new BABYLON.Quaternion();
  95403. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95404. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95405. if (_this.dragging && _this._moving && pickedMesh) {
  95406. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95407. // Slowly move mesh to avoid jitter
  95408. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  95409. // Get change in rotation
  95410. tmpQuaternion.copyFrom(_this._startingOrientation);
  95411. tmpQuaternion.x = -tmpQuaternion.x;
  95412. tmpQuaternion.y = -tmpQuaternion.y;
  95413. tmpQuaternion.z = -tmpQuaternion.z;
  95414. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  95415. // Convert change in rotation to only y axis rotation
  95416. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  95417. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  95418. // Slowly move mesh to avoid jitter
  95419. var oldParent = pickedMesh.parent;
  95420. pickedMesh.setParent(null);
  95421. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  95422. pickedMesh.setParent(oldParent);
  95423. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95424. }
  95425. });
  95426. };
  95427. /**
  95428. * Detaches the behavior from the mesh
  95429. */
  95430. SixDofDragBehavior.prototype.detach = function () {
  95431. if (this._scene) {
  95432. this._scene.onPointerObservable.remove(this._pointerObserver);
  95433. }
  95434. if (this._ownerNode) {
  95435. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95436. }
  95437. if (this._virtualOriginMesh) {
  95438. this._virtualOriginMesh.dispose();
  95439. }
  95440. if (this._virtualDragMesh) {
  95441. this._virtualDragMesh.dispose();
  95442. }
  95443. this.onDragEndObservable.clear();
  95444. this.onDragStartObservable.clear();
  95445. };
  95446. return SixDofDragBehavior;
  95447. }());
  95448. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  95449. })(BABYLON || (BABYLON = {}));
  95450. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  95451. var BABYLON;
  95452. (function (BABYLON) {
  95453. /**
  95454. * @hidden
  95455. */
  95456. var FaceDirectionInfo = /** @class */ (function () {
  95457. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  95458. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  95459. if (diff === void 0) { diff = 0; }
  95460. if (ignore === void 0) { ignore = false; }
  95461. this.direction = direction;
  95462. this.rotatedDirection = rotatedDirection;
  95463. this.diff = diff;
  95464. this.ignore = ignore;
  95465. }
  95466. return FaceDirectionInfo;
  95467. }());
  95468. /**
  95469. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  95470. */
  95471. var AttachToBoxBehavior = /** @class */ (function () {
  95472. /**
  95473. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  95474. * @param ui The transform node that should be attched to the mesh
  95475. */
  95476. function AttachToBoxBehavior(ui) {
  95477. this.ui = ui;
  95478. /**
  95479. * The name of the behavior
  95480. */
  95481. this.name = "AttachToBoxBehavior";
  95482. /**
  95483. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  95484. */
  95485. this.distanceAwayFromFace = 0.15;
  95486. /**
  95487. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  95488. */
  95489. this.distanceAwayFromBottomOfFace = 0.15;
  95490. 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))];
  95491. this._tmpMatrix = new BABYLON.Matrix();
  95492. this._tmpVector = new BABYLON.Vector3();
  95493. this._zeroVector = BABYLON.Vector3.Zero();
  95494. this._lookAtTmpMatrix = new BABYLON.Matrix();
  95495. /* Does nothing */
  95496. }
  95497. /**
  95498. * Initializes the behavior
  95499. */
  95500. AttachToBoxBehavior.prototype.init = function () {
  95501. /* Does nothing */
  95502. };
  95503. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  95504. var _this = this;
  95505. // Go over each face and calculate the angle between the face's normal and targetDirection
  95506. this._faceVectors.forEach(function (v) {
  95507. if (!_this._target.rotationQuaternion) {
  95508. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  95509. }
  95510. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  95511. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  95512. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  95513. });
  95514. // Return the face information of the one with the normal closeset to target direction
  95515. return this._faceVectors.reduce(function (min, p) {
  95516. if (min.ignore) {
  95517. return p;
  95518. }
  95519. else if (p.ignore) {
  95520. return min;
  95521. }
  95522. else {
  95523. return min.diff < p.diff ? min : p;
  95524. }
  95525. }, this._faceVectors[0]);
  95526. };
  95527. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  95528. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  95529. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  95530. this._lookAtTmpMatrix.invert();
  95531. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  95532. };
  95533. /**
  95534. * Attaches the AttachToBoxBehavior to the passed in mesh
  95535. * @param target The mesh that the specified node will be attached to
  95536. */
  95537. AttachToBoxBehavior.prototype.attach = function (target) {
  95538. var _this = this;
  95539. this._target = target;
  95540. this._scene = this._target.getScene();
  95541. // Every frame, update the app bars position
  95542. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95543. if (!_this._scene.activeCamera) {
  95544. return;
  95545. }
  95546. // Find the face closest to the cameras position
  95547. var cameraPos = _this._scene.activeCamera.position;
  95548. if (_this._scene.activeCamera.devicePosition) {
  95549. cameraPos = _this._scene.activeCamera.devicePosition;
  95550. }
  95551. var facing = _this._closestFace(cameraPos.subtract(target.position));
  95552. if (_this._scene.activeCamera.leftCamera) {
  95553. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95554. }
  95555. else {
  95556. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95557. }
  95558. // Get camera up direction
  95559. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  95560. // Ignore faces to not select a parrelel face for the up vector of the UI
  95561. _this._faceVectors.forEach(function (v) {
  95562. if (facing.direction.x && v.direction.x) {
  95563. v.ignore = true;
  95564. }
  95565. if (facing.direction.y && v.direction.y) {
  95566. v.ignore = true;
  95567. }
  95568. if (facing.direction.z && v.direction.z) {
  95569. v.ignore = true;
  95570. }
  95571. });
  95572. var facingUp = _this._closestFace(_this._tmpVector);
  95573. // Unignore faces
  95574. _this._faceVectors.forEach(function (v) {
  95575. v.ignore = false;
  95576. });
  95577. // Position the app bar on that face
  95578. _this.ui.position.copyFrom(target.position);
  95579. if (facing.direction.x) {
  95580. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95581. _this.ui.position.addInPlace(_this._tmpVector);
  95582. }
  95583. if (facing.direction.y) {
  95584. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95585. _this.ui.position.addInPlace(_this._tmpVector);
  95586. }
  95587. if (facing.direction.z) {
  95588. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95589. _this.ui.position.addInPlace(_this._tmpVector);
  95590. }
  95591. // Rotate to be oriented properly to the camera
  95592. if (!_this.ui.rotationQuaternion) {
  95593. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  95594. }
  95595. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  95596. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  95597. // Place ui the correct distance from the bottom of the mesh
  95598. if (facingUp.direction.x) {
  95599. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  95600. }
  95601. if (facingUp.direction.y) {
  95602. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  95603. }
  95604. if (facingUp.direction.z) {
  95605. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  95606. }
  95607. _this.ui.position.addInPlace(_this._tmpVector);
  95608. });
  95609. };
  95610. /**
  95611. * Detaches the behavior from the mesh
  95612. */
  95613. AttachToBoxBehavior.prototype.detach = function () {
  95614. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  95615. };
  95616. return AttachToBoxBehavior;
  95617. }());
  95618. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  95619. })(BABYLON || (BABYLON = {}));
  95620. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  95621. var BABYLON;
  95622. (function (BABYLON) {
  95623. /**
  95624. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  95625. */
  95626. var FadeInOutBehavior = /** @class */ (function () {
  95627. /**
  95628. * Instatiates the FadeInOutBehavior
  95629. */
  95630. function FadeInOutBehavior() {
  95631. var _this = this;
  95632. /**
  95633. * Time in milliseconds to delay before fading in (Default: 0)
  95634. */
  95635. this.delay = 0;
  95636. /**
  95637. * Time in milliseconds for the mesh to fade in (Default: 300)
  95638. */
  95639. this.fadeInTime = 300;
  95640. this._millisecondsPerFrame = 1000 / 60;
  95641. this._hovered = false;
  95642. this._hoverValue = 0;
  95643. this._ownerNode = null;
  95644. this._update = function () {
  95645. if (_this._ownerNode) {
  95646. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  95647. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  95648. if (_this._ownerNode.visibility > 1) {
  95649. _this._setAllVisibility(_this._ownerNode, 1);
  95650. _this._hoverValue = _this.fadeInTime + _this.delay;
  95651. return;
  95652. }
  95653. else if (_this._ownerNode.visibility < 0) {
  95654. _this._setAllVisibility(_this._ownerNode, 0);
  95655. if (_this._hoverValue < 0) {
  95656. _this._hoverValue = 0;
  95657. return;
  95658. }
  95659. }
  95660. setTimeout(_this._update, _this._millisecondsPerFrame);
  95661. }
  95662. };
  95663. }
  95664. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  95665. /**
  95666. * The name of the behavior
  95667. */
  95668. get: function () {
  95669. return "FadeInOut";
  95670. },
  95671. enumerable: true,
  95672. configurable: true
  95673. });
  95674. /**
  95675. * Initializes the behavior
  95676. */
  95677. FadeInOutBehavior.prototype.init = function () {
  95678. };
  95679. /**
  95680. * Attaches the fade behavior on the passed in mesh
  95681. * @param ownerNode The mesh that will be faded in/out once attached
  95682. */
  95683. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  95684. this._ownerNode = ownerNode;
  95685. this._setAllVisibility(this._ownerNode, 0);
  95686. };
  95687. /**
  95688. * Detaches the behavior from the mesh
  95689. */
  95690. FadeInOutBehavior.prototype.detach = function () {
  95691. this._ownerNode = null;
  95692. };
  95693. /**
  95694. * Triggers the mesh to begin fading in or out
  95695. * @param value if the object should fade in or out (true to fade in)
  95696. */
  95697. FadeInOutBehavior.prototype.fadeIn = function (value) {
  95698. this._hovered = value;
  95699. this._update();
  95700. };
  95701. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  95702. var _this = this;
  95703. mesh.visibility = value;
  95704. mesh.getChildMeshes().forEach(function (c) {
  95705. _this._setAllVisibility(c, value);
  95706. });
  95707. };
  95708. return FadeInOutBehavior;
  95709. }());
  95710. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  95711. })(BABYLON || (BABYLON = {}));
  95712. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  95713. var BABYLON;
  95714. (function (BABYLON) {
  95715. /**
  95716. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  95717. */
  95718. var Gizmo = /** @class */ (function () {
  95719. /**
  95720. * Creates a gizmo
  95721. * @param gizmoLayer The utility layer the gizmo will be added to
  95722. */
  95723. function Gizmo(
  95724. /** The utility layer the gizmo will be added to */
  95725. gizmoLayer) {
  95726. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95727. var _this = this;
  95728. this.gizmoLayer = gizmoLayer;
  95729. /**
  95730. * Ratio for the scale of the gizmo (Default: 1)
  95731. */
  95732. this.scaleRatio = 1;
  95733. this._tmpMatrix = new BABYLON.Matrix();
  95734. /**
  95735. * If a custom mesh has been set (Default: false)
  95736. */
  95737. this._customMeshSet = false;
  95738. /**
  95739. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  95740. */
  95741. this.updateGizmoRotationToMatchAttachedMesh = true;
  95742. /**
  95743. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  95744. */
  95745. this.updateGizmoPositionToMatchAttachedMesh = true;
  95746. /**
  95747. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  95748. */
  95749. this._updateScale = true;
  95750. this._interactionsEnabled = true;
  95751. this._tempVector = new BABYLON.Vector3();
  95752. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  95753. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  95754. _this._update();
  95755. });
  95756. this.attachedMesh = null;
  95757. }
  95758. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  95759. /**
  95760. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  95761. * * When set, interactions will be enabled
  95762. */
  95763. get: function () {
  95764. return this._attachedMesh;
  95765. },
  95766. set: function (value) {
  95767. this._attachedMesh = value;
  95768. this._rootMesh.setEnabled(value ? true : false);
  95769. this._attachedMeshChanged(value);
  95770. },
  95771. enumerable: true,
  95772. configurable: true
  95773. });
  95774. /**
  95775. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  95776. * @param mesh The mesh to replace the default mesh of the gizmo
  95777. */
  95778. Gizmo.prototype.setCustomMesh = function (mesh) {
  95779. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  95780. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  95781. }
  95782. this._rootMesh.getChildMeshes().forEach(function (c) {
  95783. c.dispose();
  95784. });
  95785. mesh.parent = this._rootMesh;
  95786. this._customMeshSet = true;
  95787. };
  95788. Gizmo.prototype._attachedMeshChanged = function (value) {
  95789. };
  95790. /**
  95791. * @hidden
  95792. * Updates the gizmo to match the attached mesh's position/rotation
  95793. */
  95794. Gizmo.prototype._update = function () {
  95795. if (this.attachedMesh) {
  95796. if (this.updateGizmoRotationToMatchAttachedMesh) {
  95797. if (!this._rootMesh.rotationQuaternion) {
  95798. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  95799. }
  95800. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  95801. this._tempVector.copyFrom(this.attachedMesh.scaling);
  95802. if (this.attachedMesh.scaling.x < 0) {
  95803. this.attachedMesh.scaling.x *= -1;
  95804. }
  95805. if (this.attachedMesh.scaling.y < 0) {
  95806. this.attachedMesh.scaling.y *= -1;
  95807. }
  95808. if (this.attachedMesh.scaling.z < 0) {
  95809. this.attachedMesh.scaling.z *= -1;
  95810. }
  95811. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  95812. this.attachedMesh.scaling.copyFrom(this._tempVector);
  95813. this.attachedMesh.computeWorldMatrix();
  95814. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  95815. }
  95816. else if (this._rootMesh.rotationQuaternion) {
  95817. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  95818. }
  95819. if (this.updateGizmoPositionToMatchAttachedMesh) {
  95820. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  95821. }
  95822. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  95823. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  95824. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  95825. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  95826. }
  95827. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  95828. var dist = this._tempVector.length() * this.scaleRatio;
  95829. this._rootMesh.scaling.set(dist, dist, dist);
  95830. }
  95831. }
  95832. };
  95833. /**
  95834. * Disposes of the gizmo
  95835. */
  95836. Gizmo.prototype.dispose = function () {
  95837. this._rootMesh.dispose();
  95838. if (this._beforeRenderObserver) {
  95839. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95840. }
  95841. };
  95842. return Gizmo;
  95843. }());
  95844. BABYLON.Gizmo = Gizmo;
  95845. })(BABYLON || (BABYLON = {}));
  95846. //# sourceMappingURL=babylon.gizmo.js.map
  95847. var BABYLON;
  95848. (function (BABYLON) {
  95849. /**
  95850. * Single axis drag gizmo
  95851. */
  95852. var AxisDragGizmo = /** @class */ (function (_super) {
  95853. __extends(AxisDragGizmo, _super);
  95854. /**
  95855. * Creates an AxisDragGizmo
  95856. * @param gizmoLayer The utility layer the gizmo will be added to
  95857. * @param dragAxis The axis which the gizmo will be able to drag on
  95858. * @param color The color of the gizmo
  95859. */
  95860. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  95861. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95862. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95863. var _this = _super.call(this, gizmoLayer) || this;
  95864. _this._pointerObserver = null;
  95865. /**
  95866. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95867. */
  95868. _this.snapDistance = 0;
  95869. /**
  95870. * Event that fires each time the gizmo snaps to a new location.
  95871. * * snapDistance is the the change in distance
  95872. */
  95873. _this.onSnapObservable = new BABYLON.Observable();
  95874. // Create Material
  95875. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95876. coloredMaterial.disableLighting = true;
  95877. coloredMaterial.emissiveColor = color;
  95878. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95879. hoverMaterial.disableLighting = true;
  95880. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95881. // Build mesh on root node
  95882. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95883. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  95884. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  95885. arrowTail.color = coloredMaterial.emissiveColor;
  95886. arrow.addChild(arrowMesh);
  95887. arrow.addChild(arrowTail);
  95888. // Position arrow pointing in its drag axis
  95889. arrowMesh.scaling.scaleInPlace(0.05);
  95890. arrowMesh.material = coloredMaterial;
  95891. arrowMesh.rotation.x = Math.PI / 2;
  95892. arrowMesh.position.z += 0.3;
  95893. arrowTail.scaling.scaleInPlace(0.26);
  95894. arrowTail.rotation.x = Math.PI / 2;
  95895. arrowTail.material = coloredMaterial;
  95896. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  95897. arrow.scaling.scaleInPlace(1 / 3);
  95898. _this._rootMesh.addChild(arrow);
  95899. var currentSnapDragDistance = 0;
  95900. var tmpVector = new BABYLON.Vector3();
  95901. var tmpSnapEvent = { snapDistance: 0 };
  95902. // Add drag behavior to handle events when the gizmo is dragged
  95903. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95904. _this.dragBehavior.moveAttached = false;
  95905. _this._rootMesh.addBehavior(_this.dragBehavior);
  95906. var localDelta = new BABYLON.Vector3();
  95907. var tmpMatrix = new BABYLON.Matrix();
  95908. _this.dragBehavior.onDragObservable.add(function (event) {
  95909. if (_this.attachedMesh) {
  95910. // Convert delta to local translation if it has a parent
  95911. if (_this.attachedMesh.parent) {
  95912. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  95913. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  95914. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  95915. }
  95916. else {
  95917. localDelta.copyFrom(event.delta);
  95918. }
  95919. // Snapping logic
  95920. if (_this.snapDistance == 0) {
  95921. _this.attachedMesh.position.addInPlace(localDelta);
  95922. }
  95923. else {
  95924. currentSnapDragDistance += event.dragDistance;
  95925. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  95926. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  95927. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  95928. localDelta.normalizeToRef(tmpVector);
  95929. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  95930. _this.attachedMesh.position.addInPlace(tmpVector);
  95931. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  95932. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  95933. }
  95934. }
  95935. }
  95936. });
  95937. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95938. if (_this._customMeshSet) {
  95939. return;
  95940. }
  95941. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  95942. var material = isHovered ? hoverMaterial : coloredMaterial;
  95943. _this._rootMesh.getChildMeshes().forEach(function (m) {
  95944. m.material = material;
  95945. if (m.color) {
  95946. m.color = material.emissiveColor;
  95947. }
  95948. });
  95949. });
  95950. return _this;
  95951. }
  95952. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  95953. if (this.dragBehavior) {
  95954. this.dragBehavior.enabled = value ? true : false;
  95955. }
  95956. };
  95957. /**
  95958. * Disposes of the gizmo
  95959. */
  95960. AxisDragGizmo.prototype.dispose = function () {
  95961. this.onSnapObservable.clear();
  95962. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95963. this.dragBehavior.detach();
  95964. _super.prototype.dispose.call(this);
  95965. };
  95966. return AxisDragGizmo;
  95967. }(BABYLON.Gizmo));
  95968. BABYLON.AxisDragGizmo = AxisDragGizmo;
  95969. })(BABYLON || (BABYLON = {}));
  95970. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  95971. var BABYLON;
  95972. (function (BABYLON) {
  95973. /**
  95974. * Single axis scale gizmo
  95975. */
  95976. var AxisScaleGizmo = /** @class */ (function (_super) {
  95977. __extends(AxisScaleGizmo, _super);
  95978. /**
  95979. * Creates an AxisScaleGizmo
  95980. * @param gizmoLayer The utility layer the gizmo will be added to
  95981. * @param dragAxis The axis which the gizmo will be able to scale on
  95982. * @param color The color of the gizmo
  95983. */
  95984. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  95985. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95986. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95987. var _this = _super.call(this, gizmoLayer) || this;
  95988. _this._pointerObserver = null;
  95989. /**
  95990. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95991. */
  95992. _this.snapDistance = 0;
  95993. /**
  95994. * Event that fires each time the gizmo snaps to a new location.
  95995. * * snapDistance is the the change in distance
  95996. */
  95997. _this.onSnapObservable = new BABYLON.Observable();
  95998. /**
  95999. * If the scaling operation should be done on all axis (default: false)
  96000. */
  96001. _this.uniformScaling = false;
  96002. // Create Material
  96003. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96004. _this._coloredMaterial.disableLighting = true;
  96005. _this._coloredMaterial.emissiveColor = color;
  96006. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96007. hoverMaterial.disableLighting = true;
  96008. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96009. // Build mesh on root node
  96010. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96011. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96012. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96013. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96014. arrow.addChild(arrowMesh);
  96015. arrow.addChild(arrowTail);
  96016. // Position arrow pointing in its drag axis
  96017. arrowMesh.scaling.scaleInPlace(0.1);
  96018. arrowMesh.material = _this._coloredMaterial;
  96019. arrowMesh.rotation.x = Math.PI / 2;
  96020. arrowMesh.position.z += 0.3;
  96021. arrowTail.scaling.scaleInPlace(0.26);
  96022. arrowTail.rotation.x = Math.PI / 2;
  96023. arrowTail.material = _this._coloredMaterial;
  96024. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96025. _this._rootMesh.addChild(arrow);
  96026. arrow.scaling.scaleInPlace(1 / 3);
  96027. // Add drag behavior to handle events when the gizmo is dragged
  96028. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96029. _this.dragBehavior.moveAttached = false;
  96030. _this._rootMesh.addBehavior(_this.dragBehavior);
  96031. var currentSnapDragDistance = 0;
  96032. var tmpVector = new BABYLON.Vector3();
  96033. var tmpSnapEvent = { snapDistance: 0 };
  96034. _this.dragBehavior.onDragObservable.add(function (event) {
  96035. if (_this.attachedMesh) {
  96036. // Snapping logic
  96037. var snapped = false;
  96038. var dragSteps = 0;
  96039. if (_this.uniformScaling) {
  96040. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96041. if (tmpVector.y < 0) {
  96042. tmpVector.scaleInPlace(-1);
  96043. }
  96044. }
  96045. else {
  96046. tmpVector.copyFrom(dragAxis);
  96047. }
  96048. if (_this.snapDistance == 0) {
  96049. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96050. }
  96051. else {
  96052. currentSnapDragDistance += event.dragDistance;
  96053. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96054. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96055. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96056. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96057. snapped = true;
  96058. }
  96059. else {
  96060. tmpVector.scaleInPlace(0);
  96061. }
  96062. }
  96063. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96064. if (snapped) {
  96065. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96066. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96067. }
  96068. }
  96069. });
  96070. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96071. if (_this._customMeshSet) {
  96072. return;
  96073. }
  96074. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96075. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96076. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96077. m.material = material;
  96078. if (m.color) {
  96079. m.color = material.emissiveColor;
  96080. }
  96081. });
  96082. });
  96083. return _this;
  96084. }
  96085. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96086. if (this.dragBehavior) {
  96087. this.dragBehavior.enabled = value ? true : false;
  96088. }
  96089. };
  96090. /**
  96091. * Disposes of the gizmo
  96092. */
  96093. AxisScaleGizmo.prototype.dispose = function () {
  96094. this.onSnapObservable.clear();
  96095. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96096. this.dragBehavior.detach();
  96097. _super.prototype.dispose.call(this);
  96098. };
  96099. /**
  96100. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96101. * @param mesh The mesh to replace the default mesh of the gizmo
  96102. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96103. */
  96104. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96105. var _this = this;
  96106. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96107. _super.prototype.setCustomMesh.call(this, mesh);
  96108. if (useGizmoMaterial) {
  96109. this._rootMesh.getChildMeshes().forEach(function (m) {
  96110. m.material = _this._coloredMaterial;
  96111. if (m.color) {
  96112. m.color = _this._coloredMaterial.emissiveColor;
  96113. }
  96114. });
  96115. this._customMeshSet = false;
  96116. }
  96117. };
  96118. return AxisScaleGizmo;
  96119. }(BABYLON.Gizmo));
  96120. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96121. })(BABYLON || (BABYLON = {}));
  96122. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96123. var BABYLON;
  96124. (function (BABYLON) {
  96125. /**
  96126. * Single plane rotation gizmo
  96127. */
  96128. var PlaneRotationGizmo = /** @class */ (function (_super) {
  96129. __extends(PlaneRotationGizmo, _super);
  96130. /**
  96131. * Creates a PlaneRotationGizmo
  96132. * @param gizmoLayer The utility layer the gizmo will be added to
  96133. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  96134. * @param color The color of the gizmo
  96135. */
  96136. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  96137. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96138. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96139. var _this = _super.call(this, gizmoLayer) || this;
  96140. _this._pointerObserver = null;
  96141. /**
  96142. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  96143. */
  96144. _this.snapDistance = 0;
  96145. /**
  96146. * Event that fires each time the gizmo snaps to a new location.
  96147. * * snapDistance is the the change in distance
  96148. */
  96149. _this.onSnapObservable = new BABYLON.Observable();
  96150. // Create Material
  96151. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96152. coloredMaterial.disableLighting = true;
  96153. coloredMaterial.emissiveColor = color;
  96154. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96155. hoverMaterial.disableLighting = true;
  96156. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96157. // Build mesh on root node
  96158. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96159. // Create circle out of lines
  96160. var tessellation = 20;
  96161. var radius = 0.8;
  96162. var points = new Array();
  96163. for (var i = 0; i < tessellation; i++) {
  96164. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  96165. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  96166. }
  96167. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  96168. rotationMesh.color = coloredMaterial.emissiveColor;
  96169. // Position arrow pointing in its drag axis
  96170. rotationMesh.scaling.scaleInPlace(0.26);
  96171. rotationMesh.material = coloredMaterial;
  96172. rotationMesh.rotation.x = Math.PI / 2;
  96173. parentMesh.addChild(rotationMesh);
  96174. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  96175. _this._rootMesh.addChild(parentMesh);
  96176. parentMesh.scaling.scaleInPlace(1 / 3);
  96177. // Add drag behavior to handle events when the gizmo is dragged
  96178. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  96179. _this.dragBehavior.moveAttached = false;
  96180. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  96181. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  96182. _this._rootMesh.addBehavior(_this.dragBehavior);
  96183. var lastDragPosition = new BABYLON.Vector3();
  96184. _this.dragBehavior.onDragStartObservable.add(function (e) {
  96185. if (_this.attachedMesh) {
  96186. lastDragPosition.copyFrom(e.dragPlanePoint);
  96187. }
  96188. });
  96189. var rotationMatrix = new BABYLON.Matrix();
  96190. var planeNormalTowardsCamera = new BABYLON.Vector3();
  96191. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  96192. var tmpSnapEvent = { snapDistance: 0 };
  96193. var currentSnapDragDistance = 0;
  96194. var tmpMatrix = new BABYLON.Matrix();
  96195. var tmpVector = new BABYLON.Vector3();
  96196. var amountToRotate = new BABYLON.Quaternion();
  96197. _this.dragBehavior.onDragObservable.add(function (event) {
  96198. if (_this.attachedMesh) {
  96199. if (!_this.attachedMesh.rotationQuaternion) {
  96200. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96201. }
  96202. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  96203. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  96204. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  96205. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  96206. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  96207. var angle = Math.atan2(cross.length(), dot);
  96208. planeNormalTowardsCamera.copyFrom(planeNormal);
  96209. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  96210. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96211. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  96212. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  96213. }
  96214. // Flip up vector depending on which side the camera is on
  96215. if (gizmoLayer.utilityLayerScene.activeCamera) {
  96216. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  96217. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  96218. planeNormalTowardsCamera.scaleInPlace(-1);
  96219. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  96220. }
  96221. }
  96222. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  96223. if (halfCircleSide)
  96224. angle = -angle;
  96225. // Snapping logic
  96226. var snapped = false;
  96227. if (_this.snapDistance != 0) {
  96228. currentSnapDragDistance += angle;
  96229. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96230. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96231. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96232. angle = _this.snapDistance * dragSteps;
  96233. snapped = true;
  96234. }
  96235. else {
  96236. angle = 0;
  96237. }
  96238. }
  96239. // If the mesh has a parent, convert needed world rotation to local rotation
  96240. tmpMatrix.reset();
  96241. if (_this.attachedMesh.parent) {
  96242. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96243. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  96244. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  96245. }
  96246. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  96247. var quaternionCoefficient = Math.sin(angle / 2);
  96248. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  96249. // 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
  96250. if (tmpMatrix.determinant() > 0) {
  96251. amountToRotate.toEulerAnglesToRef(tmpVector);
  96252. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  96253. }
  96254. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96255. // Rotate selected mesh quaternion over fixed axis
  96256. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  96257. }
  96258. else {
  96259. // Rotate selected mesh quaternion over rotated axis
  96260. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  96261. }
  96262. lastDragPosition.copyFrom(event.dragPlanePoint);
  96263. if (snapped) {
  96264. tmpSnapEvent.snapDistance = angle;
  96265. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96266. }
  96267. }
  96268. });
  96269. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96270. if (_this._customMeshSet) {
  96271. return;
  96272. }
  96273. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96274. var material = isHovered ? hoverMaterial : coloredMaterial;
  96275. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96276. m.material = material;
  96277. if (m.color) {
  96278. m.color = material.emissiveColor;
  96279. }
  96280. });
  96281. });
  96282. return _this;
  96283. }
  96284. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  96285. if (this.dragBehavior) {
  96286. this.dragBehavior.enabled = value ? true : false;
  96287. }
  96288. };
  96289. /**
  96290. * Disposes of the gizmo
  96291. */
  96292. PlaneRotationGizmo.prototype.dispose = function () {
  96293. this.onSnapObservable.clear();
  96294. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96295. this.dragBehavior.detach();
  96296. _super.prototype.dispose.call(this);
  96297. };
  96298. return PlaneRotationGizmo;
  96299. }(BABYLON.Gizmo));
  96300. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  96301. })(BABYLON || (BABYLON = {}));
  96302. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  96303. var BABYLON;
  96304. (function (BABYLON) {
  96305. /**
  96306. * Gizmo that enables dragging a mesh along 3 axis
  96307. */
  96308. var PositionGizmo = /** @class */ (function (_super) {
  96309. __extends(PositionGizmo, _super);
  96310. /**
  96311. * Creates a PositionGizmo
  96312. * @param gizmoLayer The utility layer the gizmo will be added to
  96313. */
  96314. function PositionGizmo(gizmoLayer) {
  96315. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96316. var _this = _super.call(this, gizmoLayer) || this;
  96317. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96318. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96319. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96320. _this.attachedMesh = null;
  96321. return _this;
  96322. }
  96323. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  96324. set: function (mesh) {
  96325. if (this.xGizmo) {
  96326. this.xGizmo.attachedMesh = mesh;
  96327. this.yGizmo.attachedMesh = mesh;
  96328. this.zGizmo.attachedMesh = mesh;
  96329. }
  96330. },
  96331. enumerable: true,
  96332. configurable: true
  96333. });
  96334. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96335. get: function () {
  96336. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96337. },
  96338. set: function (value) {
  96339. if (this.xGizmo) {
  96340. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96341. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96342. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96343. }
  96344. },
  96345. enumerable: true,
  96346. configurable: true
  96347. });
  96348. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  96349. get: function () {
  96350. return this.xGizmo.snapDistance;
  96351. },
  96352. /**
  96353. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96354. */
  96355. set: function (value) {
  96356. if (this.xGizmo) {
  96357. this.xGizmo.snapDistance = value;
  96358. this.yGizmo.snapDistance = value;
  96359. this.zGizmo.snapDistance = value;
  96360. }
  96361. },
  96362. enumerable: true,
  96363. configurable: true
  96364. });
  96365. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  96366. get: function () {
  96367. return this.xGizmo.scaleRatio;
  96368. },
  96369. /**
  96370. * Ratio for the scale of the gizmo (Default: 1)
  96371. */
  96372. set: function (value) {
  96373. if (this.xGizmo) {
  96374. this.xGizmo.scaleRatio = value;
  96375. this.yGizmo.scaleRatio = value;
  96376. this.zGizmo.scaleRatio = value;
  96377. }
  96378. },
  96379. enumerable: true,
  96380. configurable: true
  96381. });
  96382. /**
  96383. * Disposes of the gizmo
  96384. */
  96385. PositionGizmo.prototype.dispose = function () {
  96386. this.xGizmo.dispose();
  96387. this.yGizmo.dispose();
  96388. this.zGizmo.dispose();
  96389. };
  96390. /**
  96391. * CustomMeshes are not supported by this gizmo
  96392. * @param mesh The mesh to replace the default mesh of the gizmo
  96393. */
  96394. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  96395. 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)");
  96396. };
  96397. return PositionGizmo;
  96398. }(BABYLON.Gizmo));
  96399. BABYLON.PositionGizmo = PositionGizmo;
  96400. })(BABYLON || (BABYLON = {}));
  96401. //# sourceMappingURL=babylon.positionGizmo.js.map
  96402. var BABYLON;
  96403. (function (BABYLON) {
  96404. /**
  96405. * Gizmo that enables rotating a mesh along 3 axis
  96406. */
  96407. var RotationGizmo = /** @class */ (function (_super) {
  96408. __extends(RotationGizmo, _super);
  96409. /**
  96410. * Creates a RotationGizmo
  96411. * @param gizmoLayer The utility layer the gizmo will be added to
  96412. */
  96413. function RotationGizmo(gizmoLayer) {
  96414. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96415. var _this = _super.call(this, gizmoLayer) || this;
  96416. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96417. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96418. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96419. _this.attachedMesh = null;
  96420. return _this;
  96421. }
  96422. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  96423. set: function (mesh) {
  96424. if (this.xGizmo) {
  96425. this.xGizmo.attachedMesh = mesh;
  96426. this.yGizmo.attachedMesh = mesh;
  96427. this.zGizmo.attachedMesh = mesh;
  96428. }
  96429. },
  96430. enumerable: true,
  96431. configurable: true
  96432. });
  96433. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96434. get: function () {
  96435. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96436. },
  96437. set: function (value) {
  96438. if (this.xGizmo) {
  96439. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96440. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96441. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96442. }
  96443. },
  96444. enumerable: true,
  96445. configurable: true
  96446. });
  96447. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  96448. get: function () {
  96449. return this.xGizmo.snapDistance;
  96450. },
  96451. /**
  96452. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96453. */
  96454. set: function (value) {
  96455. if (this.xGizmo) {
  96456. this.xGizmo.snapDistance = value;
  96457. this.yGizmo.snapDistance = value;
  96458. this.zGizmo.snapDistance = value;
  96459. }
  96460. },
  96461. enumerable: true,
  96462. configurable: true
  96463. });
  96464. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  96465. get: function () {
  96466. return this.xGizmo.scaleRatio;
  96467. },
  96468. /**
  96469. * Ratio for the scale of the gizmo (Default: 1)
  96470. */
  96471. set: function (value) {
  96472. if (this.xGizmo) {
  96473. this.xGizmo.scaleRatio = value;
  96474. this.yGizmo.scaleRatio = value;
  96475. this.zGizmo.scaleRatio = value;
  96476. }
  96477. },
  96478. enumerable: true,
  96479. configurable: true
  96480. });
  96481. /**
  96482. * Disposes of the gizmo
  96483. */
  96484. RotationGizmo.prototype.dispose = function () {
  96485. this.xGizmo.dispose();
  96486. this.yGizmo.dispose();
  96487. this.zGizmo.dispose();
  96488. };
  96489. /**
  96490. * CustomMeshes are not supported by this gizmo
  96491. * @param mesh The mesh to replace the default mesh of the gizmo
  96492. */
  96493. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  96494. 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)");
  96495. };
  96496. return RotationGizmo;
  96497. }(BABYLON.Gizmo));
  96498. BABYLON.RotationGizmo = RotationGizmo;
  96499. })(BABYLON || (BABYLON = {}));
  96500. //# sourceMappingURL=babylon.rotationGizmo.js.map
  96501. var BABYLON;
  96502. (function (BABYLON) {
  96503. /**
  96504. * Gizmo that enables scaling a mesh along 3 axis
  96505. */
  96506. var ScaleGizmo = /** @class */ (function (_super) {
  96507. __extends(ScaleGizmo, _super);
  96508. /**
  96509. * Creates a ScaleGizmo
  96510. * @param gizmoLayer The utility layer the gizmo will be added to
  96511. */
  96512. function ScaleGizmo(gizmoLayer) {
  96513. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96514. var _this = _super.call(this, gizmoLayer) || this;
  96515. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96516. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96517. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96518. // Create uniform scale gizmo
  96519. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  96520. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  96521. _this.uniformScaleGizmo.uniformScaling = true;
  96522. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  96523. octahedron.scaling.scaleInPlace(0.007);
  96524. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  96525. _this.attachedMesh = null;
  96526. return _this;
  96527. }
  96528. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  96529. set: function (mesh) {
  96530. if (this.xGizmo) {
  96531. this.xGizmo.attachedMesh = mesh;
  96532. this.yGizmo.attachedMesh = mesh;
  96533. this.zGizmo.attachedMesh = mesh;
  96534. this.uniformScaleGizmo.attachedMesh = mesh;
  96535. }
  96536. },
  96537. enumerable: true,
  96538. configurable: true
  96539. });
  96540. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96541. get: function () {
  96542. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96543. },
  96544. set: function (value) {
  96545. if (this.xGizmo) {
  96546. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96547. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96548. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96549. }
  96550. },
  96551. enumerable: true,
  96552. configurable: true
  96553. });
  96554. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  96555. get: function () {
  96556. return this.xGizmo.snapDistance;
  96557. },
  96558. /**
  96559. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96560. */
  96561. set: function (value) {
  96562. if (this.xGizmo) {
  96563. this.xGizmo.snapDistance = value;
  96564. this.yGizmo.snapDistance = value;
  96565. this.zGizmo.snapDistance = value;
  96566. this.uniformScaleGizmo.snapDistance = value;
  96567. }
  96568. },
  96569. enumerable: true,
  96570. configurable: true
  96571. });
  96572. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  96573. get: function () {
  96574. return this.xGizmo.scaleRatio;
  96575. },
  96576. /**
  96577. * Ratio for the scale of the gizmo (Default: 1)
  96578. */
  96579. set: function (value) {
  96580. if (this.xGizmo) {
  96581. this.xGizmo.scaleRatio = value;
  96582. this.yGizmo.scaleRatio = value;
  96583. this.zGizmo.scaleRatio = value;
  96584. this.uniformScaleGizmo.scaleRatio = value;
  96585. }
  96586. },
  96587. enumerable: true,
  96588. configurable: true
  96589. });
  96590. /**
  96591. * Disposes of the gizmo
  96592. */
  96593. ScaleGizmo.prototype.dispose = function () {
  96594. this.xGizmo.dispose();
  96595. this.yGizmo.dispose();
  96596. this.zGizmo.dispose();
  96597. this.uniformScaleGizmo.dispose();
  96598. };
  96599. return ScaleGizmo;
  96600. }(BABYLON.Gizmo));
  96601. BABYLON.ScaleGizmo = ScaleGizmo;
  96602. })(BABYLON || (BABYLON = {}));
  96603. //# sourceMappingURL=babylon.scaleGizmo.js.map
  96604. var BABYLON;
  96605. (function (BABYLON) {
  96606. /**
  96607. * Bounding box gizmo
  96608. */
  96609. var BoundingBoxGizmo = /** @class */ (function (_super) {
  96610. __extends(BoundingBoxGizmo, _super);
  96611. /**
  96612. * Creates an BoundingBoxGizmo
  96613. * @param gizmoLayer The utility layer the gizmo will be added to
  96614. * @param color The color of the gizmo
  96615. */
  96616. function BoundingBoxGizmo(color, gizmoLayer) {
  96617. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96618. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  96619. var _this = _super.call(this, gizmoLayer) || this;
  96620. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  96621. _this._renderObserver = null;
  96622. _this._pointerObserver = null;
  96623. _this._scaleDragSpeed = 0.2;
  96624. _this._tmpQuaternion = new BABYLON.Quaternion();
  96625. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96626. _this._tmpRotationMatrix = new BABYLON.Matrix();
  96627. /**
  96628. * 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)
  96629. */
  96630. _this.ignoreChildren = false;
  96631. /**
  96632. * 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)
  96633. */
  96634. _this.includeChildPredicate = null;
  96635. /**
  96636. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  96637. */
  96638. _this.rotationSphereSize = 0.1;
  96639. /**
  96640. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  96641. */
  96642. _this.scaleBoxSize = 0.1;
  96643. /**
  96644. * 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)
  96645. */
  96646. _this.fixedDragMeshScreenSize = false;
  96647. /**
  96648. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  96649. */
  96650. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  96651. /**
  96652. * Fired when a rotation sphere or scale box is dragged
  96653. */
  96654. _this.onDragStartObservable = new BABYLON.Observable();
  96655. /**
  96656. * Fired when a scale box is dragged
  96657. */
  96658. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  96659. /**
  96660. * Fired when a scale box drag is ended
  96661. */
  96662. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  96663. /**
  96664. * Fired when a rotation sphere is dragged
  96665. */
  96666. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  96667. /**
  96668. * Fired when a rotation sphere drag is ended
  96669. */
  96670. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  96671. /**
  96672. * 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)
  96673. */
  96674. _this.scalePivot = null;
  96675. _this._existingMeshScale = new BABYLON.Vector3();
  96676. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  96677. _this._updateScale = false;
  96678. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  96679. // Create Materials
  96680. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96681. coloredMaterial.disableLighting = true;
  96682. coloredMaterial.emissiveColor = color;
  96683. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96684. hoverColoredMaterial.disableLighting = true;
  96685. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96686. // Build bounding box out of lines
  96687. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96688. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  96689. var lines = [];
  96690. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  96691. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96692. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96693. 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));
  96694. 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));
  96695. 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));
  96696. 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));
  96697. 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));
  96698. 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));
  96699. 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));
  96700. 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));
  96701. 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));
  96702. lines.forEach(function (l) {
  96703. l.color = color;
  96704. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  96705. l.isPickable = false;
  96706. _this._lineBoundingBox.addChild(l);
  96707. });
  96708. _this._rootMesh.addChild(_this._lineBoundingBox);
  96709. // Create rotation spheres
  96710. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96711. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  96712. var _loop_1 = function (i_1) {
  96713. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  96714. sphere.rotationQuaternion = new BABYLON.Quaternion();
  96715. sphere.material = coloredMaterial;
  96716. // Drag behavior
  96717. _dragBehavior = new BABYLON.PointerDragBehavior({});
  96718. _dragBehavior.moveAttached = false;
  96719. _dragBehavior.updateDragPlane = false;
  96720. sphere.addBehavior(_dragBehavior);
  96721. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  96722. var totalTurnAmountOfDrag = 0;
  96723. _dragBehavior.onDragStartObservable.add(function (event) {
  96724. startingTurnDirection.copyFrom(sphere.forward);
  96725. totalTurnAmountOfDrag = 0;
  96726. });
  96727. _dragBehavior.onDragObservable.add(function (event) {
  96728. _this.onRotationSphereDragObservable.notifyObservers({});
  96729. if (_this.attachedMesh) {
  96730. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96731. var worldDragDirection = startingTurnDirection;
  96732. // Project the world right on to the drag plane
  96733. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  96734. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  96735. // project drag delta on to the resulting drag axis and rotate based on that
  96736. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  96737. // Make rotation relative to size of mesh.
  96738. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96739. // Rotate based on axis
  96740. if (!_this.attachedMesh.rotationQuaternion) {
  96741. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96742. }
  96743. if (!_this._anchorMesh.rotationQuaternion) {
  96744. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  96745. }
  96746. // Do not allow the object to turn more than a full circle
  96747. totalTurnAmountOfDrag += projectDist;
  96748. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  96749. if (i_1 >= 8) {
  96750. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  96751. }
  96752. else if (i_1 >= 4) {
  96753. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  96754. }
  96755. else {
  96756. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  96757. }
  96758. // Rotate around center of bounding box
  96759. _this._anchorMesh.addChild(_this.attachedMesh);
  96760. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  96761. _this._anchorMesh.removeChild(_this.attachedMesh);
  96762. }
  96763. _this.updateBoundingBox();
  96764. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96765. }
  96766. });
  96767. // Selection/deselection
  96768. _dragBehavior.onDragStartObservable.add(function () {
  96769. _this.onDragStartObservable.notifyObservers({});
  96770. _this._selectNode(sphere);
  96771. });
  96772. _dragBehavior.onDragEndObservable.add(function () {
  96773. _this.onRotationSphereDragEndObservable.notifyObservers({});
  96774. _this._selectNode(null);
  96775. });
  96776. this_1._rotateSpheresParent.addChild(sphere);
  96777. };
  96778. var this_1 = this, _dragBehavior;
  96779. for (var i_1 = 0; i_1 < 12; i_1++) {
  96780. _loop_1(i_1);
  96781. }
  96782. _this._rootMesh.addChild(_this._rotateSpheresParent);
  96783. // Create scale cubes
  96784. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96785. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  96786. for (var i = 0; i < 2; i++) {
  96787. for (var j = 0; j < 2; j++) {
  96788. var _loop_2 = function () {
  96789. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  96790. box.material = coloredMaterial;
  96791. // Dragging logic
  96792. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  96793. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96794. _dragBehavior.moveAttached = false;
  96795. box.addBehavior(_dragBehavior);
  96796. _dragBehavior.onDragObservable.add(function (event) {
  96797. _this.onScaleBoxDragObservable.notifyObservers({});
  96798. if (_this.attachedMesh) {
  96799. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96800. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96801. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  96802. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  96803. _this.updateBoundingBox();
  96804. if (_this.scalePivot) {
  96805. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  96806. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  96807. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  96808. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96809. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96810. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  96811. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96812. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  96813. }
  96814. else {
  96815. // Scale from the position of the opposite corner
  96816. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  96817. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96818. }
  96819. _this._anchorMesh.addChild(_this.attachedMesh);
  96820. _this._anchorMesh.scaling.addInPlace(deltaScale);
  96821. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  96822. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  96823. }
  96824. _this._anchorMesh.removeChild(_this.attachedMesh);
  96825. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96826. }
  96827. });
  96828. // Selection/deselection
  96829. _dragBehavior.onDragStartObservable.add(function () {
  96830. _this.onDragStartObservable.notifyObservers({});
  96831. _this._selectNode(box);
  96832. });
  96833. _dragBehavior.onDragEndObservable.add(function () {
  96834. _this.onScaleBoxDragEndObservable.notifyObservers({});
  96835. _this._selectNode(null);
  96836. });
  96837. this_2._scaleBoxesParent.addChild(box);
  96838. };
  96839. var this_2 = this, _dragBehavior;
  96840. for (var k = 0; k < 2; k++) {
  96841. _loop_2();
  96842. }
  96843. }
  96844. }
  96845. _this._rootMesh.addChild(_this._scaleBoxesParent);
  96846. // Hover color change
  96847. var pointerIds = new Array();
  96848. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96849. if (!pointerIds[pointerInfo.event.pointerId]) {
  96850. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  96851. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  96852. pointerIds[pointerInfo.event.pointerId] = mesh;
  96853. mesh.material = hoverColoredMaterial;
  96854. }
  96855. });
  96856. }
  96857. else {
  96858. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  96859. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  96860. delete pointerIds[pointerInfo.event.pointerId];
  96861. }
  96862. }
  96863. });
  96864. // Update bounding box positions
  96865. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  96866. // Only update the bouding box if scaling has changed
  96867. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  96868. _this.updateBoundingBox();
  96869. }
  96870. });
  96871. _this.updateBoundingBox();
  96872. return _this;
  96873. }
  96874. /** @hidden */
  96875. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  96876. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  96877. // Save old pivot and set pivot to 0,0,0
  96878. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  96879. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  96880. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  96881. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  96882. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96883. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96884. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96885. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  96886. }
  96887. }
  96888. BoundingBoxGizmo._PivotCached++;
  96889. };
  96890. /** @hidden */
  96891. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  96892. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  96893. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  96894. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96895. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96896. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96897. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  96898. }
  96899. this._PivotCached--;
  96900. };
  96901. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  96902. if (value) {
  96903. // Reset anchor mesh to match attached mesh's scale
  96904. // This is needed to avoid invalid box/sphere position on first drag
  96905. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  96906. this._anchorMesh.addChild(value);
  96907. this._anchorMesh.removeChild(value);
  96908. BoundingBoxGizmo._RestorePivotPoint(value);
  96909. this.updateBoundingBox();
  96910. }
  96911. };
  96912. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  96913. this._rotateSpheresParent.getChildMeshes()
  96914. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  96915. m.isVisible = (!selectedMesh || m == selectedMesh);
  96916. });
  96917. };
  96918. /**
  96919. * Updates the bounding box information for the Gizmo
  96920. */
  96921. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  96922. if (this.attachedMesh) {
  96923. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  96924. this._update();
  96925. // Rotate based on axis
  96926. if (!this.attachedMesh.rotationQuaternion) {
  96927. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  96928. }
  96929. if (!this._anchorMesh.rotationQuaternion) {
  96930. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  96931. }
  96932. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96933. // Store original position and reset mesh to origin before computing the bounding box
  96934. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96935. this._tmpVector.copyFrom(this.attachedMesh.position);
  96936. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  96937. this.attachedMesh.position.set(0, 0, 0);
  96938. // Update bounding dimensions/positions
  96939. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  96940. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  96941. // Update gizmo to match bounding box scaling and rotation
  96942. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  96943. 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);
  96944. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  96945. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  96946. this._lineBoundingBox.computeWorldMatrix();
  96947. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  96948. // restore position/rotation values
  96949. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  96950. this.attachedMesh.position.copyFrom(this._tmpVector);
  96951. }
  96952. // Update rotation sphere locations
  96953. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  96954. for (var i = 0; i < 3; i++) {
  96955. for (var j = 0; j < 2; j++) {
  96956. for (var k = 0; k < 2; k++) {
  96957. var index = ((i * 4) + (j * 2)) + k;
  96958. if (i == 0) {
  96959. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96960. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96961. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96962. }
  96963. if (i == 1) {
  96964. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  96965. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96966. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96967. }
  96968. if (i == 2) {
  96969. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  96970. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96971. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96972. }
  96973. if (this.fixedDragMeshScreenSize) {
  96974. this._rootMesh.computeWorldMatrix();
  96975. this._rotateSpheresParent.computeWorldMatrix();
  96976. rotateSpheres[index].computeWorldMatrix();
  96977. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  96978. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  96979. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  96980. }
  96981. else {
  96982. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  96983. }
  96984. }
  96985. }
  96986. }
  96987. // Update scale box locations
  96988. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  96989. for (var i = 0; i < 2; i++) {
  96990. for (var j = 0; j < 2; j++) {
  96991. for (var k = 0; k < 2; k++) {
  96992. var index = ((i * 4) + (j * 2)) + k;
  96993. if (scaleBoxes[index]) {
  96994. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96995. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96996. if (this.fixedDragMeshScreenSize) {
  96997. this._rootMesh.computeWorldMatrix();
  96998. this._scaleBoxesParent.computeWorldMatrix();
  96999. scaleBoxes[index].computeWorldMatrix();
  97000. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97001. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97002. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97003. }
  97004. else {
  97005. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97006. }
  97007. }
  97008. }
  97009. }
  97010. }
  97011. if (this.attachedMesh) {
  97012. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97013. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97014. }
  97015. };
  97016. /**
  97017. * Enables rotation on the specified axis and disables rotation on the others
  97018. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97019. */
  97020. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97021. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97022. if (i < 4) {
  97023. m.setEnabled(axis.indexOf("x") != -1);
  97024. }
  97025. else if (i < 8) {
  97026. m.setEnabled(axis.indexOf("y") != -1);
  97027. }
  97028. else {
  97029. m.setEnabled(axis.indexOf("z") != -1);
  97030. }
  97031. });
  97032. };
  97033. /**
  97034. * Disposes of the gizmo
  97035. */
  97036. BoundingBoxGizmo.prototype.dispose = function () {
  97037. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97038. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97039. this._lineBoundingBox.dispose();
  97040. this._rotateSpheresParent.dispose();
  97041. this._scaleBoxesParent.dispose();
  97042. _super.prototype.dispose.call(this);
  97043. };
  97044. /**
  97045. * 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)
  97046. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97047. * @returns the bounding box mesh with the passed in mesh as a child
  97048. */
  97049. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97050. var makeNotPickable = function (root) {
  97051. root.isPickable = false;
  97052. root.getChildMeshes().forEach(function (c) {
  97053. makeNotPickable(c);
  97054. });
  97055. };
  97056. makeNotPickable(mesh);
  97057. // Reset position to get boudning box from origin with no rotation
  97058. if (!mesh.rotationQuaternion) {
  97059. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97060. }
  97061. var oldPos = mesh.position.clone();
  97062. var oldRot = mesh.rotationQuaternion.clone();
  97063. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97064. mesh.position.set(0, 0, 0);
  97065. // Update bounding dimensions/positions
  97066. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97067. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97068. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97069. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97070. // Restore original positions
  97071. mesh.addChild(box);
  97072. mesh.rotationQuaternion.copyFrom(oldRot);
  97073. mesh.position.copyFrom(oldPos);
  97074. // Reverse parenting
  97075. mesh.removeChild(box);
  97076. box.addChild(mesh);
  97077. box.visibility = 0;
  97078. return box;
  97079. };
  97080. /**
  97081. * CustomMeshes are not supported by this gizmo
  97082. * @param mesh The mesh to replace the default mesh of the gizmo
  97083. */
  97084. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97085. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97086. };
  97087. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97088. // store/remove pivot point should only be applied during their outermost calls
  97089. BoundingBoxGizmo._PivotCached = 0;
  97090. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97091. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97092. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97093. return BoundingBoxGizmo;
  97094. }(BABYLON.Gizmo));
  97095. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97096. })(BABYLON || (BABYLON = {}));
  97097. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97098. var BABYLON;
  97099. (function (BABYLON) {
  97100. /**
  97101. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97102. */
  97103. var GizmoManager = /** @class */ (function () {
  97104. /**
  97105. * Instatiates a gizmo manager
  97106. * @param scene the scene to overlay the gizmos on top of
  97107. */
  97108. function GizmoManager(scene) {
  97109. var _this = this;
  97110. this.scene = scene;
  97111. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97112. this._pointerObserver = null;
  97113. this._attachedMesh = null;
  97114. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97115. /**
  97116. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97117. */
  97118. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97119. /**
  97120. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97121. */
  97122. this.attachableMeshes = null;
  97123. /**
  97124. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  97125. */
  97126. this.usePointerToAttachGizmos = true;
  97127. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  97128. // Instatiate/dispose gizmos based on pointer actions
  97129. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  97130. if (!_this.usePointerToAttachGizmos) {
  97131. return;
  97132. }
  97133. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97134. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  97135. var node = pointerInfo.pickInfo.pickedMesh;
  97136. if (_this.attachableMeshes == null) {
  97137. // Attach to the most parent node
  97138. while (node && node.parent != null) {
  97139. node = node.parent;
  97140. }
  97141. }
  97142. else {
  97143. // Attach to the parent node that is an attachableMesh
  97144. var found = false;
  97145. _this.attachableMeshes.forEach(function (mesh) {
  97146. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  97147. node = mesh;
  97148. found = true;
  97149. }
  97150. });
  97151. if (!found) {
  97152. node = null;
  97153. }
  97154. }
  97155. if (node instanceof BABYLON.AbstractMesh) {
  97156. _this.attachToMesh(node);
  97157. }
  97158. else {
  97159. _this.attachToMesh(null);
  97160. }
  97161. }
  97162. else {
  97163. _this.attachToMesh(null);
  97164. }
  97165. }
  97166. });
  97167. }
  97168. /**
  97169. * Attaches a set of gizmos to the specified mesh
  97170. * @param mesh The mesh the gizmo's should be attached to
  97171. */
  97172. GizmoManager.prototype.attachToMesh = function (mesh) {
  97173. if (this._attachedMesh) {
  97174. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97175. }
  97176. this._attachedMesh = mesh;
  97177. for (var key in this.gizmos) {
  97178. var gizmo = (this.gizmos[key]);
  97179. if (gizmo && this._gizmosEnabled[key]) {
  97180. gizmo.attachedMesh = mesh;
  97181. }
  97182. }
  97183. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  97184. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97185. }
  97186. };
  97187. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  97188. get: function () {
  97189. return this._gizmosEnabled.positionGizmo;
  97190. },
  97191. /**
  97192. * If the position gizmo is enabled
  97193. */
  97194. set: function (value) {
  97195. if (value) {
  97196. if (!this.gizmos.positionGizmo) {
  97197. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  97198. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97199. }
  97200. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  97201. }
  97202. else if (this.gizmos.positionGizmo) {
  97203. this.gizmos.positionGizmo.attachedMesh = null;
  97204. }
  97205. this._gizmosEnabled.positionGizmo = value;
  97206. },
  97207. enumerable: true,
  97208. configurable: true
  97209. });
  97210. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  97211. get: function () {
  97212. return this._gizmosEnabled.rotationGizmo;
  97213. },
  97214. /**
  97215. * If the rotation gizmo is enabled
  97216. */
  97217. set: function (value) {
  97218. if (value) {
  97219. if (!this.gizmos.rotationGizmo) {
  97220. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  97221. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97222. }
  97223. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  97224. }
  97225. else if (this.gizmos.rotationGizmo) {
  97226. this.gizmos.rotationGizmo.attachedMesh = null;
  97227. }
  97228. this._gizmosEnabled.rotationGizmo = value;
  97229. },
  97230. enumerable: true,
  97231. configurable: true
  97232. });
  97233. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  97234. get: function () {
  97235. return this._gizmosEnabled.scaleGizmo;
  97236. },
  97237. /**
  97238. * If the scale gizmo is enabled
  97239. */
  97240. set: function (value) {
  97241. if (value) {
  97242. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  97243. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  97244. }
  97245. else if (this.gizmos.scaleGizmo) {
  97246. this.gizmos.scaleGizmo.attachedMesh = null;
  97247. }
  97248. this._gizmosEnabled.scaleGizmo = value;
  97249. },
  97250. enumerable: true,
  97251. configurable: true
  97252. });
  97253. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  97254. get: function () {
  97255. return this._gizmosEnabled.boundingBoxGizmo;
  97256. },
  97257. /**
  97258. * If the boundingBox gizmo is enabled
  97259. */
  97260. set: function (value) {
  97261. if (value) {
  97262. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  97263. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  97264. if (this._attachedMesh) {
  97265. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97266. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97267. }
  97268. }
  97269. else if (this.gizmos.boundingBoxGizmo) {
  97270. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  97271. }
  97272. this._gizmosEnabled.boundingBoxGizmo = value;
  97273. },
  97274. enumerable: true,
  97275. configurable: true
  97276. });
  97277. /**
  97278. * Disposes of the gizmo manager
  97279. */
  97280. GizmoManager.prototype.dispose = function () {
  97281. this.scene.onPointerObservable.remove(this._pointerObserver);
  97282. for (var key in this.gizmos) {
  97283. var gizmo = (this.gizmos[key]);
  97284. if (gizmo) {
  97285. gizmo.dispose();
  97286. }
  97287. }
  97288. this.boundingBoxDragBehavior.detach();
  97289. };
  97290. return GizmoManager;
  97291. }());
  97292. BABYLON.GizmoManager = GizmoManager;
  97293. })(BABYLON || (BABYLON = {}));
  97294. //# sourceMappingURL=babylon.gizmoManager.js.map
  97295. var BABYLON;
  97296. (function (BABYLON) {
  97297. /**
  97298. * Defines a target to use with MorphTargetManager
  97299. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97300. */
  97301. var MorphTarget = /** @class */ (function () {
  97302. /**
  97303. * Creates a new MorphTarget
  97304. * @param name defines the name of the target
  97305. * @param influence defines the influence to use
  97306. */
  97307. function MorphTarget(
  97308. /** defines the name of the target */
  97309. name, influence, scene) {
  97310. if (influence === void 0) { influence = 0; }
  97311. if (scene === void 0) { scene = null; }
  97312. this.name = name;
  97313. /**
  97314. * Gets or sets the list of animations
  97315. */
  97316. this.animations = new Array();
  97317. this._positions = null;
  97318. this._normals = null;
  97319. this._tangents = null;
  97320. /**
  97321. * Observable raised when the influence changes
  97322. */
  97323. this.onInfluenceChanged = new BABYLON.Observable();
  97324. this._animationPropertiesOverride = null;
  97325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97326. this.influence = influence;
  97327. }
  97328. Object.defineProperty(MorphTarget.prototype, "influence", {
  97329. /**
  97330. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  97331. */
  97332. get: function () {
  97333. return this._influence;
  97334. },
  97335. set: function (influence) {
  97336. if (this._influence === influence) {
  97337. return;
  97338. }
  97339. var previous = this._influence;
  97340. this._influence = influence;
  97341. if (this.onInfluenceChanged.hasObservers) {
  97342. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  97343. }
  97344. },
  97345. enumerable: true,
  97346. configurable: true
  97347. });
  97348. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  97349. /**
  97350. * Gets or sets the animation properties override
  97351. */
  97352. get: function () {
  97353. if (!this._animationPropertiesOverride && this._scene) {
  97354. return this._scene.animationPropertiesOverride;
  97355. }
  97356. return this._animationPropertiesOverride;
  97357. },
  97358. set: function (value) {
  97359. this._animationPropertiesOverride = value;
  97360. },
  97361. enumerable: true,
  97362. configurable: true
  97363. });
  97364. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  97365. /**
  97366. * Gets a boolean defining if the target contains position data
  97367. */
  97368. get: function () {
  97369. return !!this._positions;
  97370. },
  97371. enumerable: true,
  97372. configurable: true
  97373. });
  97374. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  97375. /**
  97376. * Gets a boolean defining if the target contains normal data
  97377. */
  97378. get: function () {
  97379. return !!this._normals;
  97380. },
  97381. enumerable: true,
  97382. configurable: true
  97383. });
  97384. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  97385. /**
  97386. * Gets a boolean defining if the target contains tangent data
  97387. */
  97388. get: function () {
  97389. return !!this._tangents;
  97390. },
  97391. enumerable: true,
  97392. configurable: true
  97393. });
  97394. /**
  97395. * Affects position data to this target
  97396. * @param data defines the position data to use
  97397. */
  97398. MorphTarget.prototype.setPositions = function (data) {
  97399. this._positions = data;
  97400. };
  97401. /**
  97402. * Gets the position data stored in this target
  97403. * @returns a FloatArray containing the position data (or null if not present)
  97404. */
  97405. MorphTarget.prototype.getPositions = function () {
  97406. return this._positions;
  97407. };
  97408. /**
  97409. * Affects normal data to this target
  97410. * @param data defines the normal data to use
  97411. */
  97412. MorphTarget.prototype.setNormals = function (data) {
  97413. this._normals = data;
  97414. };
  97415. /**
  97416. * Gets the normal data stored in this target
  97417. * @returns a FloatArray containing the normal data (or null if not present)
  97418. */
  97419. MorphTarget.prototype.getNormals = function () {
  97420. return this._normals;
  97421. };
  97422. /**
  97423. * Affects tangent data to this target
  97424. * @param data defines the tangent data to use
  97425. */
  97426. MorphTarget.prototype.setTangents = function (data) {
  97427. this._tangents = data;
  97428. };
  97429. /**
  97430. * Gets the tangent data stored in this target
  97431. * @returns a FloatArray containing the tangent data (or null if not present)
  97432. */
  97433. MorphTarget.prototype.getTangents = function () {
  97434. return this._tangents;
  97435. };
  97436. /**
  97437. * Serializes the current target into a Serialization object
  97438. * @returns the serialized object
  97439. */
  97440. MorphTarget.prototype.serialize = function () {
  97441. var serializationObject = {};
  97442. serializationObject.name = this.name;
  97443. serializationObject.influence = this.influence;
  97444. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  97445. if (this.hasNormals) {
  97446. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  97447. }
  97448. if (this.hasTangents) {
  97449. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  97450. }
  97451. // Animations
  97452. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  97453. return serializationObject;
  97454. };
  97455. // Statics
  97456. /**
  97457. * Creates a new target from serialized data
  97458. * @param serializationObject defines the serialized data to use
  97459. * @returns a new MorphTarget
  97460. */
  97461. MorphTarget.Parse = function (serializationObject) {
  97462. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  97463. result.setPositions(serializationObject.positions);
  97464. if (serializationObject.normals) {
  97465. result.setNormals(serializationObject.normals);
  97466. }
  97467. if (serializationObject.tangents) {
  97468. result.setTangents(serializationObject.tangents);
  97469. }
  97470. // Animations
  97471. if (serializationObject.animations) {
  97472. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  97473. var parsedAnimation = serializationObject.animations[animationIndex];
  97474. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  97475. }
  97476. }
  97477. return result;
  97478. };
  97479. /**
  97480. * Creates a MorphTarget from mesh data
  97481. * @param mesh defines the source mesh
  97482. * @param name defines the name to use for the new target
  97483. * @param influence defines the influence to attach to the target
  97484. * @returns a new MorphTarget
  97485. */
  97486. MorphTarget.FromMesh = function (mesh, name, influence) {
  97487. if (!name) {
  97488. name = mesh.name;
  97489. }
  97490. var result = new MorphTarget(name, influence, mesh.getScene());
  97491. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97493. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  97494. }
  97495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  97496. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  97497. }
  97498. return result;
  97499. };
  97500. return MorphTarget;
  97501. }());
  97502. BABYLON.MorphTarget = MorphTarget;
  97503. })(BABYLON || (BABYLON = {}));
  97504. //# sourceMappingURL=babylon.morphTarget.js.map
  97505. var BABYLON;
  97506. (function (BABYLON) {
  97507. /**
  97508. * This class is used to deform meshes using morphing between different targets
  97509. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97510. */
  97511. var MorphTargetManager = /** @class */ (function () {
  97512. /**
  97513. * Creates a new MorphTargetManager
  97514. * @param scene defines the current scene
  97515. */
  97516. function MorphTargetManager(scene) {
  97517. if (scene === void 0) { scene = null; }
  97518. this._targets = new Array();
  97519. this._targetObservable = new Array();
  97520. this._activeTargets = new BABYLON.SmartArray(16);
  97521. this._supportsNormals = false;
  97522. this._supportsTangents = false;
  97523. this._vertexCount = 0;
  97524. this._uniqueId = 0;
  97525. this._tempInfluences = new Array();
  97526. if (!scene) {
  97527. scene = BABYLON.Engine.LastCreatedScene;
  97528. }
  97529. this._scene = scene;
  97530. if (this._scene) {
  97531. this._scene.morphTargetManagers.push(this);
  97532. this._uniqueId = this._scene.getUniqueId();
  97533. }
  97534. }
  97535. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  97536. /**
  97537. * Gets the unique ID of this manager
  97538. */
  97539. get: function () {
  97540. return this._uniqueId;
  97541. },
  97542. enumerable: true,
  97543. configurable: true
  97544. });
  97545. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  97546. /**
  97547. * Gets the number of vertices handled by this manager
  97548. */
  97549. get: function () {
  97550. return this._vertexCount;
  97551. },
  97552. enumerable: true,
  97553. configurable: true
  97554. });
  97555. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  97556. /**
  97557. * Gets a boolean indicating if this manager supports morphing of normals
  97558. */
  97559. get: function () {
  97560. return this._supportsNormals;
  97561. },
  97562. enumerable: true,
  97563. configurable: true
  97564. });
  97565. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  97566. /**
  97567. * Gets a boolean indicating if this manager supports morphing of tangents
  97568. */
  97569. get: function () {
  97570. return this._supportsTangents;
  97571. },
  97572. enumerable: true,
  97573. configurable: true
  97574. });
  97575. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  97576. /**
  97577. * Gets the number of targets stored in this manager
  97578. */
  97579. get: function () {
  97580. return this._targets.length;
  97581. },
  97582. enumerable: true,
  97583. configurable: true
  97584. });
  97585. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  97586. /**
  97587. * Gets the number of influencers (ie. the number of targets with influences > 0)
  97588. */
  97589. get: function () {
  97590. return this._activeTargets.length;
  97591. },
  97592. enumerable: true,
  97593. configurable: true
  97594. });
  97595. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  97596. /**
  97597. * Gets the list of influences (one per target)
  97598. */
  97599. get: function () {
  97600. return this._influences;
  97601. },
  97602. enumerable: true,
  97603. configurable: true
  97604. });
  97605. /**
  97606. * Gets the active target at specified index. An active target is a target with an influence > 0
  97607. * @param index defines the index to check
  97608. * @returns the requested target
  97609. */
  97610. MorphTargetManager.prototype.getActiveTarget = function (index) {
  97611. return this._activeTargets.data[index];
  97612. };
  97613. /**
  97614. * Gets the target at specified index
  97615. * @param index defines the index to check
  97616. * @returns the requested target
  97617. */
  97618. MorphTargetManager.prototype.getTarget = function (index) {
  97619. return this._targets[index];
  97620. };
  97621. /**
  97622. * Add a new target to this manager
  97623. * @param target defines the target to add
  97624. */
  97625. MorphTargetManager.prototype.addTarget = function (target) {
  97626. var _this = this;
  97627. this._targets.push(target);
  97628. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  97629. _this._syncActiveTargets(needUpdate);
  97630. }));
  97631. this._syncActiveTargets(true);
  97632. };
  97633. /**
  97634. * Removes a target from the manager
  97635. * @param target defines the target to remove
  97636. */
  97637. MorphTargetManager.prototype.removeTarget = function (target) {
  97638. var index = this._targets.indexOf(target);
  97639. if (index >= 0) {
  97640. this._targets.splice(index, 1);
  97641. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  97642. this._syncActiveTargets(true);
  97643. }
  97644. };
  97645. /**
  97646. * Serializes the current manager into a Serialization object
  97647. * @returns the serialized object
  97648. */
  97649. MorphTargetManager.prototype.serialize = function () {
  97650. var serializationObject = {};
  97651. serializationObject.id = this.uniqueId;
  97652. serializationObject.targets = [];
  97653. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97654. var target = _a[_i];
  97655. serializationObject.targets.push(target.serialize());
  97656. }
  97657. return serializationObject;
  97658. };
  97659. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  97660. var influenceCount = 0;
  97661. this._activeTargets.reset();
  97662. this._supportsNormals = true;
  97663. this._supportsTangents = true;
  97664. this._vertexCount = 0;
  97665. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97666. var target = _a[_i];
  97667. this._activeTargets.push(target);
  97668. this._tempInfluences[influenceCount++] = target.influence;
  97669. var positions = target.getPositions();
  97670. if (positions) {
  97671. this._supportsNormals = this._supportsNormals && target.hasNormals;
  97672. this._supportsTangents = this._supportsTangents && target.hasTangents;
  97673. var vertexCount = positions.length / 3;
  97674. if (this._vertexCount === 0) {
  97675. this._vertexCount = vertexCount;
  97676. }
  97677. else if (this._vertexCount !== vertexCount) {
  97678. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  97679. return;
  97680. }
  97681. }
  97682. }
  97683. if (!this._influences || this._influences.length !== influenceCount) {
  97684. this._influences = new Float32Array(influenceCount);
  97685. }
  97686. for (var index = 0; index < influenceCount; index++) {
  97687. this._influences[index] = this._tempInfluences[index];
  97688. }
  97689. if (needUpdate) {
  97690. this.synchronize();
  97691. }
  97692. };
  97693. /**
  97694. * Syncrhonize the targets with all the meshes using this morph target manager
  97695. */
  97696. MorphTargetManager.prototype.synchronize = function () {
  97697. if (!this._scene) {
  97698. return;
  97699. }
  97700. // Flag meshes as dirty to resync with the active targets
  97701. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  97702. var mesh = _a[_i];
  97703. if (mesh.morphTargetManager === this) {
  97704. mesh._syncGeometryWithMorphTargetManager();
  97705. }
  97706. }
  97707. };
  97708. // Statics
  97709. /**
  97710. * Creates a new MorphTargetManager from serialized data
  97711. * @param serializationObject defines the serialized data
  97712. * @param scene defines the hosting scene
  97713. * @returns the new MorphTargetManager
  97714. */
  97715. MorphTargetManager.Parse = function (serializationObject, scene) {
  97716. var result = new MorphTargetManager(scene);
  97717. result._uniqueId = serializationObject.id;
  97718. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  97719. var targetData = _a[_i];
  97720. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  97721. }
  97722. return result;
  97723. };
  97724. return MorphTargetManager;
  97725. }());
  97726. BABYLON.MorphTargetManager = MorphTargetManager;
  97727. })(BABYLON || (BABYLON = {}));
  97728. //# sourceMappingURL=babylon.morphTargetManager.js.map
  97729. var BABYLON;
  97730. (function (BABYLON) {
  97731. var Octree = /** @class */ (function () {
  97732. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  97733. if (maxDepth === void 0) { maxDepth = 2; }
  97734. this.maxDepth = maxDepth;
  97735. this.dynamicContent = new Array();
  97736. this._maxBlockCapacity = maxBlockCapacity || 64;
  97737. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  97738. this._creationFunc = creationFunc;
  97739. }
  97740. // Methods
  97741. Octree.prototype.update = function (worldMin, worldMax, entries) {
  97742. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  97743. };
  97744. Octree.prototype.addMesh = function (entry) {
  97745. for (var index = 0; index < this.blocks.length; index++) {
  97746. var block = this.blocks[index];
  97747. block.addEntry(entry);
  97748. }
  97749. };
  97750. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  97751. this._selectionContent.reset();
  97752. for (var index = 0; index < this.blocks.length; index++) {
  97753. var block = this.blocks[index];
  97754. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  97755. }
  97756. if (allowDuplicate) {
  97757. this._selectionContent.concat(this.dynamicContent);
  97758. }
  97759. else {
  97760. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97761. }
  97762. return this._selectionContent;
  97763. };
  97764. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  97765. this._selectionContent.reset();
  97766. for (var index = 0; index < this.blocks.length; index++) {
  97767. var block = this.blocks[index];
  97768. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  97769. }
  97770. if (allowDuplicate) {
  97771. this._selectionContent.concat(this.dynamicContent);
  97772. }
  97773. else {
  97774. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97775. }
  97776. return this._selectionContent;
  97777. };
  97778. Octree.prototype.intersectsRay = function (ray) {
  97779. this._selectionContent.reset();
  97780. for (var index = 0; index < this.blocks.length; index++) {
  97781. var block = this.blocks[index];
  97782. block.intersectsRay(ray, this._selectionContent);
  97783. }
  97784. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97785. return this._selectionContent;
  97786. };
  97787. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  97788. target.blocks = new Array();
  97789. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  97790. // Segmenting space
  97791. for (var x = 0; x < 2; x++) {
  97792. for (var y = 0; y < 2; y++) {
  97793. for (var z = 0; z < 2; z++) {
  97794. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  97795. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  97796. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  97797. block.addEntries(entries);
  97798. target.blocks.push(block);
  97799. }
  97800. }
  97801. }
  97802. };
  97803. Octree.CreationFuncForMeshes = function (entry, block) {
  97804. var boundingInfo = entry.getBoundingInfo();
  97805. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97806. block.entries.push(entry);
  97807. }
  97808. };
  97809. Octree.CreationFuncForSubMeshes = function (entry, block) {
  97810. var boundingInfo = entry.getBoundingInfo();
  97811. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97812. block.entries.push(entry);
  97813. }
  97814. };
  97815. return Octree;
  97816. }());
  97817. BABYLON.Octree = Octree;
  97818. })(BABYLON || (BABYLON = {}));
  97819. //# sourceMappingURL=babylon.octree.js.map
  97820. var BABYLON;
  97821. (function (BABYLON) {
  97822. /**
  97823. * Class used to store a cell in an octree
  97824. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  97825. */
  97826. var OctreeBlock = /** @class */ (function () {
  97827. /**
  97828. * Creates a new block
  97829. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  97830. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  97831. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  97832. * @param depth defines the current depth of this block in the octree
  97833. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  97834. * @param creationFunc defines a callback to call when an element is added to the block
  97835. */
  97836. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  97837. /**
  97838. * Gets the content of the current block
  97839. */
  97840. this.entries = new Array();
  97841. this._boundingVectors = new Array();
  97842. this._capacity = capacity;
  97843. this._depth = depth;
  97844. this._maxDepth = maxDepth;
  97845. this._creationFunc = creationFunc;
  97846. this._minPoint = minPoint;
  97847. this._maxPoint = maxPoint;
  97848. this._boundingVectors.push(minPoint.clone());
  97849. this._boundingVectors.push(maxPoint.clone());
  97850. this._boundingVectors.push(minPoint.clone());
  97851. this._boundingVectors[2].x = maxPoint.x;
  97852. this._boundingVectors.push(minPoint.clone());
  97853. this._boundingVectors[3].y = maxPoint.y;
  97854. this._boundingVectors.push(minPoint.clone());
  97855. this._boundingVectors[4].z = maxPoint.z;
  97856. this._boundingVectors.push(maxPoint.clone());
  97857. this._boundingVectors[5].z = minPoint.z;
  97858. this._boundingVectors.push(maxPoint.clone());
  97859. this._boundingVectors[6].x = minPoint.x;
  97860. this._boundingVectors.push(maxPoint.clone());
  97861. this._boundingVectors[7].y = minPoint.y;
  97862. }
  97863. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  97864. // Property
  97865. /**
  97866. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  97867. */
  97868. get: function () {
  97869. return this._capacity;
  97870. },
  97871. enumerable: true,
  97872. configurable: true
  97873. });
  97874. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  97875. /**
  97876. * Gets the minimum vector (in world space) of the block's bounding box
  97877. */
  97878. get: function () {
  97879. return this._minPoint;
  97880. },
  97881. enumerable: true,
  97882. configurable: true
  97883. });
  97884. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  97885. /**
  97886. * Gets the maximum vector (in world space) of the block's bounding box
  97887. */
  97888. get: function () {
  97889. return this._maxPoint;
  97890. },
  97891. enumerable: true,
  97892. configurable: true
  97893. });
  97894. // Methods
  97895. /**
  97896. * Add a new element to this block
  97897. * @param entry defines the element to add
  97898. */
  97899. OctreeBlock.prototype.addEntry = function (entry) {
  97900. if (this.blocks) {
  97901. for (var index = 0; index < this.blocks.length; index++) {
  97902. var block = this.blocks[index];
  97903. block.addEntry(entry);
  97904. }
  97905. return;
  97906. }
  97907. this._creationFunc(entry, this);
  97908. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  97909. this.createInnerBlocks();
  97910. }
  97911. };
  97912. /**
  97913. * Add an array of elements to this block
  97914. * @param entries defines the array of elements to add
  97915. */
  97916. OctreeBlock.prototype.addEntries = function (entries) {
  97917. for (var index = 0; index < entries.length; index++) {
  97918. var mesh = entries[index];
  97919. this.addEntry(mesh);
  97920. }
  97921. };
  97922. /**
  97923. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  97924. * @param frustumPlanes defines the frustum planes to test
  97925. * @param selection defines the array to store current content if selection is positive
  97926. * @param allowDuplicate defines if the selection array can contains duplicated entries
  97927. */
  97928. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  97929. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  97930. if (this.blocks) {
  97931. for (var index = 0; index < this.blocks.length; index++) {
  97932. var block = this.blocks[index];
  97933. block.select(frustumPlanes, selection, allowDuplicate);
  97934. }
  97935. return;
  97936. }
  97937. if (allowDuplicate) {
  97938. selection.concat(this.entries);
  97939. }
  97940. else {
  97941. selection.concatWithNoDuplicate(this.entries);
  97942. }
  97943. }
  97944. };
  97945. /**
  97946. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  97947. * @param sphereCenter defines the bounding sphere center
  97948. * @param sphereRadius defines the bounding sphere radius
  97949. * @param selection defines the array to store current content if selection is positive
  97950. * @param allowDuplicate defines if the selection array can contains duplicated entries
  97951. */
  97952. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  97953. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  97954. if (this.blocks) {
  97955. for (var index = 0; index < this.blocks.length; index++) {
  97956. var block = this.blocks[index];
  97957. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  97958. }
  97959. return;
  97960. }
  97961. if (allowDuplicate) {
  97962. selection.concat(this.entries);
  97963. }
  97964. else {
  97965. selection.concatWithNoDuplicate(this.entries);
  97966. }
  97967. }
  97968. };
  97969. /**
  97970. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  97971. * @param ray defines the ray to test with
  97972. * @param selection defines the array to store current content if selection is positive
  97973. */
  97974. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  97975. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  97976. if (this.blocks) {
  97977. for (var index = 0; index < this.blocks.length; index++) {
  97978. var block = this.blocks[index];
  97979. block.intersectsRay(ray, selection);
  97980. }
  97981. return;
  97982. }
  97983. selection.concatWithNoDuplicate(this.entries);
  97984. }
  97985. };
  97986. /**
  97987. * Subdivide the content into child blocks (this block will then be empty)
  97988. */
  97989. OctreeBlock.prototype.createInnerBlocks = function () {
  97990. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  97991. };
  97992. return OctreeBlock;
  97993. }());
  97994. BABYLON.OctreeBlock = OctreeBlock;
  97995. })(BABYLON || (BABYLON = {}));
  97996. //# sourceMappingURL=babylon.octreeBlock.js.map
  97997. var BABYLON;
  97998. (function (BABYLON) {
  97999. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98000. if (maxCapacity === void 0) { maxCapacity = 64; }
  98001. if (maxDepth === void 0) { maxDepth = 2; }
  98002. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98003. if (!component) {
  98004. component = new OctreeSceneComponent(this);
  98005. this._addComponent(component);
  98006. }
  98007. if (!this._selectionOctree) {
  98008. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98009. }
  98010. var worldExtends = this.getWorldExtends();
  98011. // Update octree
  98012. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98013. return this._selectionOctree;
  98014. };
  98015. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98016. get: function () {
  98017. return this._selectionOctree;
  98018. },
  98019. enumerable: true,
  98020. configurable: true
  98021. });
  98022. /**
  98023. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98024. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98025. * @param maxCapacity defines the maximum size of each block (64 by default)
  98026. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98027. * @returns the new octree
  98028. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98029. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98030. */
  98031. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98032. if (maxCapacity === void 0) { maxCapacity = 64; }
  98033. if (maxDepth === void 0) { maxDepth = 2; }
  98034. var scene = this.getScene();
  98035. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98036. if (!component) {
  98037. component = new OctreeSceneComponent(scene);
  98038. scene._addComponent(component);
  98039. }
  98040. if (!this._submeshesOctree) {
  98041. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98042. }
  98043. this.computeWorldMatrix(true);
  98044. var boundingInfo = this.getBoundingInfo();
  98045. // Update octree
  98046. var bbox = boundingInfo.boundingBox;
  98047. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98048. return this._submeshesOctree;
  98049. };
  98050. /**
  98051. * Defines the octree scene component responsible to manage any octrees
  98052. * in a given scene.
  98053. */
  98054. var OctreeSceneComponent = /** @class */ (function () {
  98055. /**
  98056. * Creates a new instance of the component for the given scene
  98057. * @param scene Defines the scene to register the component in
  98058. */
  98059. function OctreeSceneComponent(scene) {
  98060. /**
  98061. * The component name helpfull to identify the component in the list of scene components.
  98062. */
  98063. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98064. /**
  98065. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98066. */
  98067. this.checksIsEnabled = true;
  98068. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98069. this.scene = scene;
  98070. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98071. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98072. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98073. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98074. }
  98075. /**
  98076. * Registers the component in a given scene
  98077. */
  98078. OctreeSceneComponent.prototype.register = function () {
  98079. var _this = this;
  98080. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98081. var sceneOctree = _this.scene.selectionOctree;
  98082. if (sceneOctree !== undefined && sceneOctree !== null) {
  98083. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98084. if (index !== -1) {
  98085. sceneOctree.dynamicContent.splice(index, 1);
  98086. }
  98087. }
  98088. });
  98089. this.scene.onMeshImportedObservable.add(function (mesh) {
  98090. var sceneOctree = _this.scene.selectionOctree;
  98091. if (sceneOctree !== undefined && sceneOctree !== null) {
  98092. sceneOctree.addMesh(mesh);
  98093. }
  98094. });
  98095. };
  98096. /**
  98097. * Return the list of active meshes
  98098. * @returns the list of active meshes
  98099. */
  98100. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98101. if (this.scene._selectionOctree) {
  98102. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98103. return selection;
  98104. }
  98105. return this.scene._getDefaultMeshCandidates();
  98106. };
  98107. /**
  98108. * Return the list of active sub meshes
  98109. * @param mesh The mesh to get the candidates sub meshes from
  98110. * @returns the list of active sub meshes
  98111. */
  98112. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98113. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98114. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98115. return intersections;
  98116. }
  98117. return this.scene._getDefaultSubMeshCandidates(mesh);
  98118. };
  98119. /**
  98120. * Return the list of sub meshes intersecting with a given local ray
  98121. * @param mesh defines the mesh to find the submesh for
  98122. * @param localRay defines the ray in local space
  98123. * @returns the list of intersecting sub meshes
  98124. */
  98125. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  98126. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  98127. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  98128. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  98129. return intersections;
  98130. }
  98131. return this.scene._getDefaultSubMeshCandidates(mesh);
  98132. };
  98133. /**
  98134. * Return the list of sub meshes colliding with a collider
  98135. * @param mesh defines the mesh to find the submesh for
  98136. * @param collider defines the collider to evaluate the collision against
  98137. * @returns the list of colliding sub meshes
  98138. */
  98139. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  98140. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  98141. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  98142. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  98143. return intersections;
  98144. }
  98145. return this.scene._getDefaultSubMeshCandidates(mesh);
  98146. };
  98147. /**
  98148. * Rebuilds the elements related to this component in case of
  98149. * context lost for instance.
  98150. */
  98151. OctreeSceneComponent.prototype.rebuild = function () {
  98152. // Nothing to do here.
  98153. };
  98154. /**
  98155. * Disposes the component and the associated ressources.
  98156. */
  98157. OctreeSceneComponent.prototype.dispose = function () {
  98158. // Nothing to do here.
  98159. };
  98160. return OctreeSceneComponent;
  98161. }());
  98162. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  98163. })(BABYLON || (BABYLON = {}));
  98164. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  98165. var BABYLON;
  98166. (function (BABYLON) {
  98167. /**
  98168. * Postprocess used to generate anaglyphic rendering
  98169. */
  98170. var AnaglyphPostProcess = /** @class */ (function (_super) {
  98171. __extends(AnaglyphPostProcess, _super);
  98172. /**
  98173. * Creates a new AnaglyphPostProcess
  98174. * @param name defines postprocess name
  98175. * @param options defines creation options or target ratio scale
  98176. * @param rigCameras defines cameras using this postprocess
  98177. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  98178. * @param engine defines hosting engine
  98179. * @param reusable defines if the postprocess will be reused multiple times per frame
  98180. */
  98181. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  98182. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  98183. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98184. _this.onApplyObservable.add(function (effect) {
  98185. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  98186. });
  98187. return _this;
  98188. }
  98189. return AnaglyphPostProcess;
  98190. }(BABYLON.PostProcess));
  98191. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  98192. })(BABYLON || (BABYLON = {}));
  98193. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  98194. var BABYLON;
  98195. (function (BABYLON) {
  98196. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  98197. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98198. });
  98199. /**
  98200. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  98201. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98202. */
  98203. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  98204. __extends(AnaglyphArcRotateCamera, _super);
  98205. /**
  98206. * Creates a new AnaglyphArcRotateCamera
  98207. * @param name defines camera name
  98208. * @param alpha defines alpha angle (in radians)
  98209. * @param beta defines beta angle (in radians)
  98210. * @param radius defines radius
  98211. * @param target defines camera target
  98212. * @param interaxialDistance defines distance between each color axis
  98213. * @param scene defines the hosting scene
  98214. */
  98215. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  98216. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98217. _this.interaxialDistance = interaxialDistance;
  98218. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98219. return _this;
  98220. }
  98221. /**
  98222. * Gets camera class name
  98223. * @returns AnaglyphArcRotateCamera
  98224. */
  98225. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  98226. return "AnaglyphArcRotateCamera";
  98227. };
  98228. return AnaglyphArcRotateCamera;
  98229. }(BABYLON.ArcRotateCamera));
  98230. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  98231. })(BABYLON || (BABYLON = {}));
  98232. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  98233. var BABYLON;
  98234. (function (BABYLON) {
  98235. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  98236. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98237. });
  98238. /**
  98239. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  98240. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98241. */
  98242. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  98243. __extends(AnaglyphFreeCamera, _super);
  98244. /**
  98245. * Creates a new AnaglyphFreeCamera
  98246. * @param name defines camera name
  98247. * @param position defines initial position
  98248. * @param interaxialDistance defines distance between each color axis
  98249. * @param scene defines the hosting scene
  98250. */
  98251. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  98252. var _this = _super.call(this, name, position, scene) || this;
  98253. _this.interaxialDistance = interaxialDistance;
  98254. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98255. return _this;
  98256. }
  98257. /**
  98258. * Gets camera class name
  98259. * @returns AnaglyphFreeCamera
  98260. */
  98261. AnaglyphFreeCamera.prototype.getClassName = function () {
  98262. return "AnaglyphFreeCamera";
  98263. };
  98264. return AnaglyphFreeCamera;
  98265. }(BABYLON.FreeCamera));
  98266. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  98267. })(BABYLON || (BABYLON = {}));
  98268. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  98269. var BABYLON;
  98270. (function (BABYLON) {
  98271. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  98272. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98273. });
  98274. /**
  98275. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  98276. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98277. */
  98278. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  98279. __extends(AnaglyphGamepadCamera, _super);
  98280. /**
  98281. * Creates a new AnaglyphGamepadCamera
  98282. * @param name defines camera name
  98283. * @param position defines initial position
  98284. * @param interaxialDistance defines distance between each color axis
  98285. * @param scene defines the hosting scene
  98286. */
  98287. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  98288. var _this = _super.call(this, name, position, scene) || this;
  98289. _this.interaxialDistance = interaxialDistance;
  98290. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98291. return _this;
  98292. }
  98293. /**
  98294. * Gets camera class name
  98295. * @returns AnaglyphGamepadCamera
  98296. */
  98297. AnaglyphGamepadCamera.prototype.getClassName = function () {
  98298. return "AnaglyphGamepadCamera";
  98299. };
  98300. return AnaglyphGamepadCamera;
  98301. }(BABYLON.GamepadCamera));
  98302. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  98303. })(BABYLON || (BABYLON = {}));
  98304. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  98305. var BABYLON;
  98306. (function (BABYLON) {
  98307. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  98308. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98309. });
  98310. /**
  98311. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  98312. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98313. */
  98314. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  98315. __extends(AnaglyphUniversalCamera, _super);
  98316. /**
  98317. * Creates a new AnaglyphUniversalCamera
  98318. * @param name defines camera name
  98319. * @param position defines initial position
  98320. * @param interaxialDistance defines distance between each color axis
  98321. * @param scene defines the hosting scene
  98322. */
  98323. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  98324. var _this = _super.call(this, name, position, scene) || this;
  98325. _this.interaxialDistance = interaxialDistance;
  98326. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98327. return _this;
  98328. }
  98329. /**
  98330. * Gets camera class name
  98331. * @returns AnaglyphUniversalCamera
  98332. */
  98333. AnaglyphUniversalCamera.prototype.getClassName = function () {
  98334. return "AnaglyphUniversalCamera";
  98335. };
  98336. return AnaglyphUniversalCamera;
  98337. }(BABYLON.UniversalCamera));
  98338. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  98339. })(BABYLON || (BABYLON = {}));
  98340. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  98341. var BABYLON;
  98342. (function (BABYLON) {
  98343. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  98344. __extends(StereoscopicInterlacePostProcess, _super);
  98345. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  98346. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  98347. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98348. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98349. _this.onSizeChangedObservable.add(function () {
  98350. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98351. });
  98352. _this.onApplyObservable.add(function (effect) {
  98353. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  98354. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  98355. });
  98356. return _this;
  98357. }
  98358. return StereoscopicInterlacePostProcess;
  98359. }(BABYLON.PostProcess));
  98360. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  98361. })(BABYLON || (BABYLON = {}));
  98362. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  98363. var BABYLON;
  98364. (function (BABYLON) {
  98365. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  98366. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98367. });
  98368. /**
  98369. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  98370. * @see http://doc.babylonjs.com/features/cameras
  98371. */
  98372. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  98373. __extends(StereoscopicArcRotateCamera, _super);
  98374. /**
  98375. * Creates a new StereoscopicArcRotateCamera
  98376. * @param name defines camera name
  98377. * @param alpha defines alpha angle (in radians)
  98378. * @param beta defines beta angle (in radians)
  98379. * @param radius defines radius
  98380. * @param target defines camera target
  98381. * @param interaxialDistance defines distance between each color axis
  98382. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98383. * @param scene defines the hosting scene
  98384. */
  98385. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  98386. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98387. _this.interaxialDistance = interaxialDistance;
  98388. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98389. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98390. return _this;
  98391. }
  98392. /**
  98393. * Gets camera class name
  98394. * @returns StereoscopicArcRotateCamera
  98395. */
  98396. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  98397. return "StereoscopicArcRotateCamera";
  98398. };
  98399. return StereoscopicArcRotateCamera;
  98400. }(BABYLON.ArcRotateCamera));
  98401. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  98402. })(BABYLON || (BABYLON = {}));
  98403. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  98404. var BABYLON;
  98405. (function (BABYLON) {
  98406. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98407. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98408. });
  98409. /**
  98410. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  98411. * @see http://doc.babylonjs.com/features/cameras
  98412. */
  98413. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  98414. __extends(StereoscopicFreeCamera, _super);
  98415. /**
  98416. * Creates a new StereoscopicFreeCamera
  98417. * @param name defines camera name
  98418. * @param position defines initial position
  98419. * @param interaxialDistance defines distance between each color axis
  98420. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98421. * @param scene defines the hosting scene
  98422. */
  98423. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98424. var _this = _super.call(this, name, position, scene) || this;
  98425. _this.interaxialDistance = interaxialDistance;
  98426. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98427. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98428. return _this;
  98429. }
  98430. /**
  98431. * Gets camera class name
  98432. * @returns StereoscopicFreeCamera
  98433. */
  98434. StereoscopicFreeCamera.prototype.getClassName = function () {
  98435. return "StereoscopicFreeCamera";
  98436. };
  98437. return StereoscopicFreeCamera;
  98438. }(BABYLON.FreeCamera));
  98439. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  98440. })(BABYLON || (BABYLON = {}));
  98441. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  98442. var BABYLON;
  98443. (function (BABYLON) {
  98444. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  98445. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98446. });
  98447. /**
  98448. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  98449. * @see http://doc.babylonjs.com/features/cameras
  98450. */
  98451. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  98452. __extends(StereoscopicGamepadCamera, _super);
  98453. /**
  98454. * Creates a new StereoscopicGamepadCamera
  98455. * @param name defines camera name
  98456. * @param position defines initial position
  98457. * @param interaxialDistance defines distance between each color axis
  98458. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98459. * @param scene defines the hosting scene
  98460. */
  98461. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98462. var _this = _super.call(this, name, position, scene) || this;
  98463. _this.interaxialDistance = interaxialDistance;
  98464. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98465. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98466. return _this;
  98467. }
  98468. /**
  98469. * Gets camera class name
  98470. * @returns StereoscopicGamepadCamera
  98471. */
  98472. StereoscopicGamepadCamera.prototype.getClassName = function () {
  98473. return "StereoscopicGamepadCamera";
  98474. };
  98475. return StereoscopicGamepadCamera;
  98476. }(BABYLON.GamepadCamera));
  98477. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  98478. })(BABYLON || (BABYLON = {}));
  98479. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  98480. var BABYLON;
  98481. (function (BABYLON) {
  98482. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98483. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98484. });
  98485. /**
  98486. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  98487. * @see http://doc.babylonjs.com/features/cameras
  98488. */
  98489. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  98490. __extends(StereoscopicUniversalCamera, _super);
  98491. /**
  98492. * Creates a new StereoscopicUniversalCamera
  98493. * @param name defines camera name
  98494. * @param position defines initial position
  98495. * @param interaxialDistance defines distance between each color axis
  98496. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98497. * @param scene defines the hosting scene
  98498. */
  98499. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98500. var _this = _super.call(this, name, position, scene) || this;
  98501. _this.interaxialDistance = interaxialDistance;
  98502. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98503. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98504. return _this;
  98505. }
  98506. /**
  98507. * Gets camera class name
  98508. * @returns StereoscopicUniversalCamera
  98509. */
  98510. StereoscopicUniversalCamera.prototype.getClassName = function () {
  98511. return "StereoscopicUniversalCamera";
  98512. };
  98513. return StereoscopicUniversalCamera;
  98514. }(BABYLON.UniversalCamera));
  98515. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  98516. })(BABYLON || (BABYLON = {}));
  98517. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  98518. var BABYLON;
  98519. (function (BABYLON) {
  98520. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  98521. __extends(VRDistortionCorrectionPostProcess, _super);
  98522. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  98523. var _this = _super.call(this, name, "vrDistortionCorrection", [
  98524. 'LensCenter',
  98525. 'Scale',
  98526. 'ScaleIn',
  98527. 'HmdWarpParam'
  98528. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  98529. _this._isRightEye = isRightEye;
  98530. _this._distortionFactors = vrMetrics.distortionK;
  98531. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  98532. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  98533. _this.adaptScaleToCurrentViewport = true;
  98534. _this.onSizeChangedObservable.add(function () {
  98535. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  98536. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  98537. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  98538. });
  98539. _this.onApplyObservable.add(function (effect) {
  98540. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  98541. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  98542. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  98543. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  98544. });
  98545. return _this;
  98546. }
  98547. return VRDistortionCorrectionPostProcess;
  98548. }(BABYLON.PostProcess));
  98549. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  98550. })(BABYLON || (BABYLON = {}));
  98551. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  98552. var BABYLON;
  98553. (function (BABYLON) {
  98554. /**
  98555. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  98556. * Screen rotation is taken into account.
  98557. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98558. */
  98559. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  98560. /**
  98561. * Instantiates a new input
  98562. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98563. */
  98564. function FreeCameraDeviceOrientationInput() {
  98565. var _this = this;
  98566. this._screenOrientationAngle = 0;
  98567. this._screenQuaternion = new BABYLON.Quaternion();
  98568. this._alpha = 0;
  98569. this._beta = 0;
  98570. this._gamma = 0;
  98571. this._orientationChanged = function () {
  98572. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  98573. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  98574. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  98575. };
  98576. this._deviceOrientation = function (evt) {
  98577. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  98578. _this._beta = evt.beta !== null ? evt.beta : 0;
  98579. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  98580. };
  98581. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  98582. this._orientationChanged();
  98583. }
  98584. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  98585. /**
  98586. * Define the camera controlled by the input.
  98587. */
  98588. get: function () {
  98589. return this._camera;
  98590. },
  98591. set: function (camera) {
  98592. this._camera = camera;
  98593. if (this._camera != null && !this._camera.rotationQuaternion) {
  98594. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  98595. }
  98596. },
  98597. enumerable: true,
  98598. configurable: true
  98599. });
  98600. /**
  98601. * Attach the input controls to a specific dom element to get the input from.
  98602. * @param element Defines the element the controls should be listened from
  98603. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98604. */
  98605. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98606. window.addEventListener("orientationchange", this._orientationChanged);
  98607. window.addEventListener("deviceorientation", this._deviceOrientation);
  98608. //In certain cases, the attach control is called AFTER orientation was changed,
  98609. //So this is needed.
  98610. this._orientationChanged();
  98611. };
  98612. /**
  98613. * Detach the current controls from the specified dom element.
  98614. * @param element Defines the element to stop listening the inputs from
  98615. */
  98616. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  98617. window.removeEventListener("orientationchange", this._orientationChanged);
  98618. window.removeEventListener("deviceorientation", this._deviceOrientation);
  98619. };
  98620. /**
  98621. * Update the current camera state depending on the inputs that have been used this frame.
  98622. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98623. */
  98624. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  98625. //if no device orientation provided, don't update the rotation.
  98626. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  98627. if (!this._alpha)
  98628. return;
  98629. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  98630. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  98631. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  98632. //Mirror on XY Plane
  98633. this._camera.rotationQuaternion.z *= -1;
  98634. this._camera.rotationQuaternion.w *= -1;
  98635. };
  98636. /**
  98637. * Gets the class name of the current intput.
  98638. * @returns the class name
  98639. */
  98640. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  98641. return "FreeCameraDeviceOrientationInput";
  98642. };
  98643. /**
  98644. * Get the friendly name associated with the input class.
  98645. * @returns the input friendly name
  98646. */
  98647. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  98648. return "deviceOrientation";
  98649. };
  98650. return FreeCameraDeviceOrientationInput;
  98651. }());
  98652. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  98653. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  98654. })(BABYLON || (BABYLON = {}));
  98655. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  98656. var BABYLON;
  98657. (function (BABYLON) {
  98658. /**
  98659. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  98660. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98661. */
  98662. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  98663. /**
  98664. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  98665. */
  98666. function ArcRotateCameraVRDeviceOrientationInput() {
  98667. /**
  98668. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  98669. */
  98670. this.alphaCorrection = 1;
  98671. /**
  98672. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  98673. */
  98674. this.betaCorrection = 1;
  98675. /**
  98676. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  98677. */
  98678. this.gammaCorrection = 1;
  98679. this._alpha = 0;
  98680. this._gamma = 0;
  98681. this._dirty = false;
  98682. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  98683. }
  98684. /**
  98685. * Attach the input controls to a specific dom element to get the input from.
  98686. * @param element Defines the element the controls should be listened from
  98687. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98688. */
  98689. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98690. this.camera.attachControl(element, noPreventDefault);
  98691. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  98692. };
  98693. /** @hidden */
  98694. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  98695. if (evt.alpha !== null) {
  98696. this._alpha = +evt.alpha | 0;
  98697. }
  98698. if (evt.gamma !== null) {
  98699. this._gamma = +evt.gamma | 0;
  98700. }
  98701. this._dirty = true;
  98702. };
  98703. /**
  98704. * Update the current camera state depending on the inputs that have been used this frame.
  98705. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98706. */
  98707. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  98708. if (this._dirty) {
  98709. this._dirty = false;
  98710. if (this._gamma < 0) {
  98711. this._gamma = 180 + this._gamma;
  98712. }
  98713. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  98714. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  98715. }
  98716. };
  98717. /**
  98718. * Detach the current controls from the specified dom element.
  98719. * @param element Defines the element to stop listening the inputs from
  98720. */
  98721. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  98722. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  98723. };
  98724. /**
  98725. * Gets the class name of the current intput.
  98726. * @returns the class name
  98727. */
  98728. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  98729. return "ArcRotateCameraVRDeviceOrientationInput";
  98730. };
  98731. /**
  98732. * Get the friendly name associated with the input class.
  98733. * @returns the input friendly name
  98734. */
  98735. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  98736. return "VRDeviceOrientation";
  98737. };
  98738. return ArcRotateCameraVRDeviceOrientationInput;
  98739. }());
  98740. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  98741. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  98742. })(BABYLON || (BABYLON = {}));
  98743. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  98744. var BABYLON;
  98745. (function (BABYLON) {
  98746. /**
  98747. * This represents all the required metrics to create a VR camera.
  98748. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  98749. */
  98750. var VRCameraMetrics = /** @class */ (function () {
  98751. function VRCameraMetrics() {
  98752. /**
  98753. * Define if the current vr camera should compensate the distortion of the lense or not.
  98754. */
  98755. this.compensateDistortion = true;
  98756. }
  98757. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  98758. /**
  98759. * Gets the rendering aspect ratio based on the provided resolutions.
  98760. */
  98761. get: function () {
  98762. return this.hResolution / (2 * this.vResolution);
  98763. },
  98764. enumerable: true,
  98765. configurable: true
  98766. });
  98767. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  98768. /**
  98769. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  98770. */
  98771. get: function () {
  98772. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  98773. },
  98774. enumerable: true,
  98775. configurable: true
  98776. });
  98777. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  98778. /**
  98779. * @hidden
  98780. */
  98781. get: function () {
  98782. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98783. var h = (4 * meters) / this.hScreenSize;
  98784. return BABYLON.Matrix.Translation(h, 0, 0);
  98785. },
  98786. enumerable: true,
  98787. configurable: true
  98788. });
  98789. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  98790. /**
  98791. * @hidden
  98792. */
  98793. get: function () {
  98794. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98795. var h = (4 * meters) / this.hScreenSize;
  98796. return BABYLON.Matrix.Translation(-h, 0, 0);
  98797. },
  98798. enumerable: true,
  98799. configurable: true
  98800. });
  98801. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  98802. /**
  98803. * @hidden
  98804. */
  98805. get: function () {
  98806. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  98807. },
  98808. enumerable: true,
  98809. configurable: true
  98810. });
  98811. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  98812. /**
  98813. * @hidden
  98814. */
  98815. get: function () {
  98816. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  98817. },
  98818. enumerable: true,
  98819. configurable: true
  98820. });
  98821. /**
  98822. * Get the default VRMetrics based on the most generic setup.
  98823. * @returns the default vr metrics
  98824. */
  98825. VRCameraMetrics.GetDefault = function () {
  98826. var result = new VRCameraMetrics();
  98827. result.hResolution = 1280;
  98828. result.vResolution = 800;
  98829. result.hScreenSize = 0.149759993;
  98830. result.vScreenSize = 0.0935999975;
  98831. result.vScreenCenter = 0.0467999987;
  98832. result.eyeToScreenDistance = 0.0410000011;
  98833. result.lensSeparationDistance = 0.0635000020;
  98834. result.interpupillaryDistance = 0.0640000030;
  98835. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  98836. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  98837. result.postProcessScaleFactor = 1.714605507808412;
  98838. result.lensCenterOffset = 0.151976421;
  98839. return result;
  98840. };
  98841. return VRCameraMetrics;
  98842. }());
  98843. BABYLON.VRCameraMetrics = VRCameraMetrics;
  98844. })(BABYLON || (BABYLON = {}));
  98845. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  98846. var BABYLON;
  98847. (function (BABYLON) {
  98848. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  98849. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98850. });
  98851. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  98852. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98853. });
  98854. /**
  98855. * This represents a WebVR camera.
  98856. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  98857. * @example http://doc.babylonjs.com/how_to/webvr_camera
  98858. */
  98859. var WebVRFreeCamera = /** @class */ (function (_super) {
  98860. __extends(WebVRFreeCamera, _super);
  98861. /**
  98862. * Instantiates a WebVRFreeCamera.
  98863. * @param name The name of the WebVRFreeCamera
  98864. * @param position The starting anchor position for the camera
  98865. * @param scene The scene the camera belongs to
  98866. * @param webVROptions a set of customizable options for the webVRCamera
  98867. */
  98868. function WebVRFreeCamera(name, position, scene, webVROptions) {
  98869. if (webVROptions === void 0) { webVROptions = {}; }
  98870. var _this = _super.call(this, name, position, scene) || this;
  98871. _this.webVROptions = webVROptions;
  98872. /**
  98873. * @hidden
  98874. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  98875. */
  98876. _this._vrDevice = null;
  98877. /**
  98878. * The rawPose of the vrDevice.
  98879. */
  98880. _this.rawPose = null;
  98881. _this._specsVersion = "1.1";
  98882. _this._attached = false;
  98883. _this._descendants = [];
  98884. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  98885. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  98886. /** @hidden */
  98887. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  98888. _this._standingMatrix = null;
  98889. /**
  98890. * Represents device position in babylon space.
  98891. */
  98892. _this.devicePosition = BABYLON.Vector3.Zero();
  98893. /**
  98894. * Represents device rotation in babylon space.
  98895. */
  98896. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  98897. /**
  98898. * The scale of the device to be used when translating from device space to babylon space.
  98899. */
  98900. _this.deviceScaleFactor = 1;
  98901. _this._deviceToWorld = BABYLON.Matrix.Identity();
  98902. _this._worldToDevice = BABYLON.Matrix.Identity();
  98903. /**
  98904. * References to the webVR controllers for the vrDevice.
  98905. */
  98906. _this.controllers = [];
  98907. /**
  98908. * Emits an event when a controller is attached.
  98909. */
  98910. _this.onControllersAttachedObservable = new BABYLON.Observable();
  98911. /**
  98912. * Emits an event when a controller's mesh has been loaded;
  98913. */
  98914. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  98915. /**
  98916. * Emits an event when the HMD's pose has been updated.
  98917. */
  98918. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  98919. _this._poseSet = false;
  98920. /**
  98921. * If the rig cameras be used as parent instead of this camera.
  98922. */
  98923. _this.rigParenting = true;
  98924. _this._defaultHeight = undefined;
  98925. _this._htmlElementAttached = null;
  98926. _this._detachIfAttached = function () {
  98927. var vrDisplay = _this.getEngine().getVRDevice();
  98928. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  98929. _this.detachControl(_this._htmlElementAttached);
  98930. }
  98931. };
  98932. _this._workingVector = BABYLON.Vector3.Zero();
  98933. _this._oneVector = BABYLON.Vector3.One();
  98934. _this._workingMatrix = BABYLON.Matrix.Identity();
  98935. _this._tmpMatrix = new BABYLON.Matrix();
  98936. _this._cache.position = BABYLON.Vector3.Zero();
  98937. if (webVROptions.defaultHeight) {
  98938. _this._defaultHeight = webVROptions.defaultHeight;
  98939. _this.position.y = _this._defaultHeight;
  98940. }
  98941. _this.minZ = 0.1;
  98942. //legacy support - the compensation boolean was removed.
  98943. if (arguments.length === 5) {
  98944. _this.webVROptions = arguments[4];
  98945. }
  98946. // default webVR options
  98947. if (_this.webVROptions.trackPosition == undefined) {
  98948. _this.webVROptions.trackPosition = true;
  98949. }
  98950. if (_this.webVROptions.controllerMeshes == undefined) {
  98951. _this.webVROptions.controllerMeshes = true;
  98952. }
  98953. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  98954. _this.webVROptions.defaultLightingOnControllers = true;
  98955. }
  98956. _this.rotationQuaternion = new BABYLON.Quaternion();
  98957. if (_this.webVROptions && _this.webVROptions.positionScale) {
  98958. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  98959. }
  98960. //enable VR
  98961. var engine = _this.getEngine();
  98962. _this._onVREnabled = function (success) { if (success) {
  98963. _this.initControllers();
  98964. } };
  98965. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  98966. engine.initWebVR().add(function (event) {
  98967. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  98968. return;
  98969. }
  98970. _this._vrDevice = event.vrDisplay;
  98971. //reset the rig parameters.
  98972. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  98973. if (_this._attached) {
  98974. _this.getEngine().enableVR();
  98975. }
  98976. });
  98977. if (typeof (VRFrameData) !== "undefined")
  98978. _this._frameData = new VRFrameData();
  98979. /**
  98980. * The idea behind the following lines:
  98981. * objects that have the camera as parent should actually have the rig cameras as a parent.
  98982. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  98983. * the second will not show it correctly.
  98984. *
  98985. * To solve this - each object that has the camera as parent will be added to a protected array.
  98986. * When the rig camera renders, it will take this array and set all of those to be its children.
  98987. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  98988. * Amazing!
  98989. */
  98990. scene.onBeforeCameraRenderObservable.add(function (camera) {
  98991. if (camera.parent === _this && _this.rigParenting) {
  98992. _this._descendants = _this.getDescendants(true, function (n) {
  98993. // don't take the cameras or the controllers!
  98994. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  98995. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  98996. return !isController && !isRigCamera;
  98997. });
  98998. _this._descendants.forEach(function (node) {
  98999. node.parent = camera;
  99000. });
  99001. }
  99002. });
  99003. scene.onAfterCameraRenderObservable.add(function (camera) {
  99004. if (camera.parent === _this && _this.rigParenting) {
  99005. _this._descendants.forEach(function (node) {
  99006. node.parent = _this;
  99007. });
  99008. }
  99009. });
  99010. return _this;
  99011. }
  99012. /**
  99013. * Gets the device distance from the ground in meters.
  99014. * @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.
  99015. */
  99016. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99017. if (this._standingMatrix) {
  99018. // Add standing matrix offset to get real offset from ground in room
  99019. this._standingMatrix.getTranslationToRef(this._workingVector);
  99020. return this._deviceRoomPosition.y + this._workingVector.y;
  99021. }
  99022. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99023. return this._defaultHeight || 0;
  99024. };
  99025. /**
  99026. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99027. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99028. */
  99029. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99030. var _this = this;
  99031. if (callback === void 0) { callback = function (bool) { }; }
  99032. // Use standing matrix if available
  99033. this.getEngine().initWebVRAsync().then(function (result) {
  99034. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99035. callback(false);
  99036. }
  99037. else {
  99038. _this._standingMatrix = new BABYLON.Matrix();
  99039. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99040. if (!_this.getScene().useRightHandedSystem) {
  99041. [2, 6, 8, 9, 14].forEach(function (num) {
  99042. if (_this._standingMatrix) {
  99043. _this._standingMatrix.m[num] *= -1;
  99044. }
  99045. });
  99046. }
  99047. callback(true);
  99048. }
  99049. });
  99050. };
  99051. /**
  99052. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99053. * @returns A promise with a boolean set to if the standing matrix is supported.
  99054. */
  99055. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99056. var _this = this;
  99057. return new Promise(function (res, rej) {
  99058. _this.useStandingMatrix(function (supported) {
  99059. res(supported);
  99060. });
  99061. });
  99062. };
  99063. /**
  99064. * Disposes the camera
  99065. */
  99066. WebVRFreeCamera.prototype.dispose = function () {
  99067. this._detachIfAttached();
  99068. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99069. if (this._updateCacheWhenTrackingDisabledObserver) {
  99070. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99071. }
  99072. _super.prototype.dispose.call(this);
  99073. };
  99074. /**
  99075. * Gets a vrController by name.
  99076. * @param name The name of the controller to retreive
  99077. * @returns the controller matching the name specified or null if not found
  99078. */
  99079. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99080. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99081. var gp = _a[_i];
  99082. if (gp.hand === name) {
  99083. return gp;
  99084. }
  99085. }
  99086. return null;
  99087. };
  99088. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99089. /**
  99090. * The controller corrisponding to the users left hand.
  99091. */
  99092. get: function () {
  99093. if (!this._leftController) {
  99094. this._leftController = this.getControllerByName("left");
  99095. }
  99096. return this._leftController;
  99097. },
  99098. enumerable: true,
  99099. configurable: true
  99100. });
  99101. ;
  99102. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99103. /**
  99104. * The controller corrisponding to the users right hand.
  99105. */
  99106. get: function () {
  99107. if (!this._rightController) {
  99108. this._rightController = this.getControllerByName("right");
  99109. }
  99110. return this._rightController;
  99111. },
  99112. enumerable: true,
  99113. configurable: true
  99114. });
  99115. ;
  99116. /**
  99117. * Casts a ray forward from the vrCamera's gaze.
  99118. * @param length Length of the ray (default: 100)
  99119. * @returns the ray corrisponding to the gaze
  99120. */
  99121. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99122. if (length === void 0) { length = 100; }
  99123. if (this.leftCamera) {
  99124. // Use left eye to avoid computation to compute center on every call
  99125. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  99126. }
  99127. else {
  99128. return _super.prototype.getForwardRay.call(this, length);
  99129. }
  99130. };
  99131. /**
  99132. * @hidden
  99133. * Updates the camera based on device's frame data
  99134. */
  99135. WebVRFreeCamera.prototype._checkInputs = function () {
  99136. if (this._vrDevice && this._vrDevice.isPresenting) {
  99137. this._vrDevice.getFrameData(this._frameData);
  99138. this.updateFromDevice(this._frameData.pose);
  99139. }
  99140. _super.prototype._checkInputs.call(this);
  99141. };
  99142. /**
  99143. * Updates the poseControlled values based on the input device pose.
  99144. * @param poseData Pose coming from the device
  99145. */
  99146. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  99147. if (poseData && poseData.orientation) {
  99148. this.rawPose = poseData;
  99149. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  99150. if (this.getScene().useRightHandedSystem) {
  99151. this._deviceRoomRotationQuaternion.z *= -1;
  99152. this._deviceRoomRotationQuaternion.w *= -1;
  99153. }
  99154. if (this.webVROptions.trackPosition && this.rawPose.position) {
  99155. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  99156. if (this.getScene().useRightHandedSystem) {
  99157. this._deviceRoomPosition.z *= -1;
  99158. }
  99159. }
  99160. this._poseSet = true;
  99161. }
  99162. };
  99163. /**
  99164. * WebVR's attach control will start broadcasting frames to the device.
  99165. * Note that in certain browsers (chrome for example) this function must be called
  99166. * within a user-interaction callback. Example:
  99167. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  99168. *
  99169. * @param element html element to attach the vrDevice to
  99170. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  99171. */
  99172. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  99173. _super.prototype.attachControl.call(this, element, noPreventDefault);
  99174. this._attached = true;
  99175. this._htmlElementAttached = element;
  99176. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  99177. if (this._vrDevice) {
  99178. this.getEngine().enableVR();
  99179. }
  99180. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  99181. };
  99182. /**
  99183. * Detaches the camera from the html element and disables VR
  99184. *
  99185. * @param element html element to detach from
  99186. */
  99187. WebVRFreeCamera.prototype.detachControl = function (element) {
  99188. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  99189. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  99190. _super.prototype.detachControl.call(this, element);
  99191. this._attached = false;
  99192. this.getEngine().disableVR();
  99193. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  99194. };
  99195. /**
  99196. * @returns the name of this class
  99197. */
  99198. WebVRFreeCamera.prototype.getClassName = function () {
  99199. return "WebVRFreeCamera";
  99200. };
  99201. /**
  99202. * Calls resetPose on the vrDisplay
  99203. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  99204. */
  99205. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  99206. //uses the vrDisplay's "resetPose()".
  99207. //pitch and roll won't be affected.
  99208. this._vrDevice.resetPose();
  99209. };
  99210. /**
  99211. * @hidden
  99212. * Updates the rig cameras (left and right eye)
  99213. */
  99214. WebVRFreeCamera.prototype._updateRigCameras = function () {
  99215. var camLeft = this._rigCameras[0];
  99216. var camRight = this._rigCameras[1];
  99217. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  99218. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  99219. camLeft.position.copyFrom(this._deviceRoomPosition);
  99220. camRight.position.copyFrom(this._deviceRoomPosition);
  99221. };
  99222. // Remove translation from 6dof headset if trackposition is set to false
  99223. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  99224. if (isViewMatrix === void 0) { isViewMatrix = false; }
  99225. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  99226. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  99227. if (!isViewMatrix) {
  99228. this._tmpMatrix.invert();
  99229. }
  99230. this._tmpMatrix.multiplyToRef(matrix, matrix);
  99231. }
  99232. };
  99233. /**
  99234. * @hidden
  99235. * Updates the cached values of the camera
  99236. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  99237. */
  99238. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  99239. var _this = this;
  99240. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  99241. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  99242. if (!this.updateCacheCalled) {
  99243. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  99244. this.updateCacheCalled = true;
  99245. this.update();
  99246. }
  99247. // Set working vector to the device position in room space rotated by the new rotation
  99248. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  99249. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  99250. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  99251. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  99252. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  99253. // Add translation from anchor position
  99254. this._deviceToWorld.getTranslationToRef(this._workingVector);
  99255. this._workingVector.addInPlace(this.position);
  99256. this._workingVector.subtractInPlace(this._cache.position);
  99257. this._deviceToWorld.setTranslation(this._workingVector);
  99258. // Set an inverted matrix to be used when updating the camera
  99259. this._deviceToWorld.invertToRef(this._worldToDevice);
  99260. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  99261. this.controllers.forEach(function (controller) {
  99262. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  99263. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  99264. controller.update();
  99265. });
  99266. }
  99267. if (!ignoreParentClass) {
  99268. _super.prototype._updateCache.call(this);
  99269. }
  99270. this.updateCacheCalled = false;
  99271. };
  99272. /**
  99273. * @hidden
  99274. * Get current device position in babylon world
  99275. */
  99276. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  99277. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  99278. };
  99279. /**
  99280. * Updates the current device position and rotation in the babylon world
  99281. */
  99282. WebVRFreeCamera.prototype.update = function () {
  99283. this._computeDevicePosition();
  99284. // Get current device rotation in babylon world
  99285. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  99286. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  99287. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  99288. if (this._poseSet) {
  99289. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  99290. }
  99291. _super.prototype.update.call(this);
  99292. };
  99293. /**
  99294. * @hidden
  99295. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  99296. * @returns an identity matrix
  99297. */
  99298. WebVRFreeCamera.prototype._getViewMatrix = function () {
  99299. return BABYLON.Matrix.Identity();
  99300. };
  99301. /**
  99302. * This function is called by the two RIG cameras.
  99303. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  99304. */
  99305. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  99306. var _this = this;
  99307. // Update the parent camera prior to using a child camera to avoid desynchronization
  99308. var parentCamera = this._cameraRigParams["parentCamera"];
  99309. parentCamera._updateCache();
  99310. //WebVR 1.1
  99311. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  99312. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  99313. if (!this.getScene().useRightHandedSystem) {
  99314. [2, 6, 8, 9, 14].forEach(function (num) {
  99315. _this._webvrViewMatrix.m[num] *= -1;
  99316. });
  99317. }
  99318. // update the camera rotation matrix
  99319. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  99320. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  99321. // Computing target and final matrix
  99322. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  99323. // should the view matrix be updated with scale and position offset?
  99324. if (parentCamera.deviceScaleFactor !== 1) {
  99325. this._webvrViewMatrix.invert();
  99326. // scale the position, if set
  99327. if (parentCamera.deviceScaleFactor) {
  99328. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  99329. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  99330. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  99331. }
  99332. this._webvrViewMatrix.invert();
  99333. }
  99334. // Remove translation from 6dof headset if trackposition is set to false
  99335. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  99336. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  99337. // Compute global position
  99338. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  99339. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  99340. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  99341. this._workingMatrix.getTranslationToRef(this._globalPosition);
  99342. this._markSyncedWithParent();
  99343. return this._webvrViewMatrix;
  99344. };
  99345. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  99346. var _this = this;
  99347. var parentCamera = this.parent;
  99348. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  99349. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  99350. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  99351. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  99352. //babylon compatible matrix
  99353. if (!this.getScene().useRightHandedSystem) {
  99354. [8, 9, 10, 11].forEach(function (num) {
  99355. _this._projectionMatrix.m[num] *= -1;
  99356. });
  99357. }
  99358. return this._projectionMatrix;
  99359. };
  99360. /**
  99361. * Initializes the controllers and their meshes
  99362. */
  99363. WebVRFreeCamera.prototype.initControllers = function () {
  99364. var _this = this;
  99365. this.controllers = [];
  99366. var manager = this.getScene().gamepadManager;
  99367. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  99368. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99369. var webVrController = gamepad;
  99370. if (webVrController.defaultModel) {
  99371. webVrController.defaultModel.setEnabled(false);
  99372. }
  99373. if (webVrController.hand === "right") {
  99374. _this._rightController = null;
  99375. }
  99376. if (webVrController.hand === "left") {
  99377. _this._leftController = null;
  99378. }
  99379. var controllerIndex = _this.controllers.indexOf(webVrController);
  99380. if (controllerIndex !== -1) {
  99381. _this.controllers.splice(controllerIndex, 1);
  99382. }
  99383. }
  99384. });
  99385. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  99386. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99387. var webVrController_1 = gamepad;
  99388. if (!_this.webVROptions.trackPosition) {
  99389. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  99390. // Cache must be updated before rendering controllers to avoid them being one frame behind
  99391. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  99392. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  99393. _this._updateCache();
  99394. });
  99395. }
  99396. }
  99397. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  99398. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  99399. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  99400. if (_this.webVROptions.controllerMeshes) {
  99401. if (webVrController_1.defaultModel) {
  99402. webVrController_1.defaultModel.setEnabled(true);
  99403. }
  99404. else {
  99405. // Load the meshes
  99406. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  99407. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  99408. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  99409. if (_this.webVROptions.defaultLightingOnControllers) {
  99410. if (!_this._lightOnControllers) {
  99411. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  99412. }
  99413. var activateLightOnSubMeshes_1 = function (mesh, light) {
  99414. var children = mesh.getChildren();
  99415. if (children && children.length !== 0) {
  99416. children.forEach(function (mesh) {
  99417. light.includedOnlyMeshes.push(mesh);
  99418. activateLightOnSubMeshes_1(mesh, light);
  99419. });
  99420. }
  99421. };
  99422. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  99423. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  99424. }
  99425. });
  99426. }
  99427. }
  99428. webVrController_1.attachToPoseControlledCamera(_this);
  99429. // since this is async - sanity check. Is the controller already stored?
  99430. if (_this.controllers.indexOf(webVrController_1) === -1) {
  99431. //add to the controllers array
  99432. _this.controllers.push(webVrController_1);
  99433. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  99434. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  99435. // So we're overriding setting left & right manually to be sure
  99436. var firstViveWandDetected = false;
  99437. for (var i = 0; i < _this.controllers.length; i++) {
  99438. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99439. if (!firstViveWandDetected) {
  99440. firstViveWandDetected = true;
  99441. _this.controllers[i].hand = "left";
  99442. }
  99443. else {
  99444. _this.controllers[i].hand = "right";
  99445. }
  99446. }
  99447. }
  99448. //did we find enough controllers? Great! let the developer know.
  99449. if (_this.controllers.length >= 2) {
  99450. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  99451. }
  99452. }
  99453. }
  99454. });
  99455. };
  99456. return WebVRFreeCamera;
  99457. }(BABYLON.FreeCamera));
  99458. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  99459. })(BABYLON || (BABYLON = {}));
  99460. //# sourceMappingURL=babylon.webVRCamera.js.map
  99461. var BABYLON;
  99462. (function (BABYLON) {
  99463. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  99464. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  99465. });
  99466. // We're mainly based on the logic defined into the FreeCamera code
  99467. /**
  99468. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  99469. * being tilted forward or back and left or right.
  99470. */
  99471. var DeviceOrientationCamera = /** @class */ (function (_super) {
  99472. __extends(DeviceOrientationCamera, _super);
  99473. /**
  99474. * Creates a new device orientation camera
  99475. * @param name The name of the camera
  99476. * @param position The start position camera
  99477. * @param scene The scene the camera belongs to
  99478. */
  99479. function DeviceOrientationCamera(name, position, scene) {
  99480. var _this = _super.call(this, name, position, scene) || this;
  99481. _this._quaternionCache = new BABYLON.Quaternion();
  99482. _this.inputs.addDeviceOrientation();
  99483. return _this;
  99484. }
  99485. /**
  99486. * Gets the current instance class name ("DeviceOrientationCamera").
  99487. * This helps avoiding instanceof at run time.
  99488. * @returns the class name
  99489. */
  99490. DeviceOrientationCamera.prototype.getClassName = function () {
  99491. return "DeviceOrientationCamera";
  99492. };
  99493. /**
  99494. * @hidden
  99495. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  99496. */
  99497. DeviceOrientationCamera.prototype._checkInputs = function () {
  99498. _super.prototype._checkInputs.call(this);
  99499. this._quaternionCache.copyFrom(this.rotationQuaternion);
  99500. if (this._initialQuaternion) {
  99501. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99502. }
  99503. };
  99504. /**
  99505. * Reset the camera to its default orientation on the specified axis only.
  99506. * @param axis The axis to reset
  99507. */
  99508. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  99509. var _this = this;
  99510. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  99511. //can only work if this camera has a rotation quaternion already.
  99512. if (!this.rotationQuaternion)
  99513. return;
  99514. if (!this._initialQuaternion) {
  99515. this._initialQuaternion = new BABYLON.Quaternion();
  99516. }
  99517. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  99518. ['x', 'y', 'z'].forEach(function (axisName) {
  99519. if (!axis[axisName]) {
  99520. _this._initialQuaternion[axisName] = 0;
  99521. }
  99522. else {
  99523. _this._initialQuaternion[axisName] *= -1;
  99524. }
  99525. });
  99526. this._initialQuaternion.normalize();
  99527. //force rotation update
  99528. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99529. };
  99530. return DeviceOrientationCamera;
  99531. }(BABYLON.FreeCamera));
  99532. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  99533. })(BABYLON || (BABYLON = {}));
  99534. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  99535. var BABYLON;
  99536. (function (BABYLON) {
  99537. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99538. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99539. });
  99540. /**
  99541. * Camera used to simulate VR rendering (based on FreeCamera)
  99542. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99543. */
  99544. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  99545. __extends(VRDeviceOrientationFreeCamera, _super);
  99546. /**
  99547. * Creates a new VRDeviceOrientationFreeCamera
  99548. * @param name defines camera name
  99549. * @param position defines the start position of the camera
  99550. * @param scene defines the scene the camera belongs to
  99551. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99552. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99553. */
  99554. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99555. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99556. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99557. var _this = _super.call(this, name, position, scene) || this;
  99558. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99559. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99560. return _this;
  99561. }
  99562. /**
  99563. * Gets camera class name
  99564. * @returns VRDeviceOrientationFreeCamera
  99565. */
  99566. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  99567. return "VRDeviceOrientationFreeCamera";
  99568. };
  99569. return VRDeviceOrientationFreeCamera;
  99570. }(BABYLON.DeviceOrientationCamera));
  99571. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  99572. })(BABYLON || (BABYLON = {}));
  99573. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  99574. var BABYLON;
  99575. (function (BABYLON) {
  99576. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99577. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  99578. });
  99579. /**
  99580. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  99581. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99582. */
  99583. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  99584. __extends(VRDeviceOrientationArcRotateCamera, _super);
  99585. /**
  99586. * Creates a new VRDeviceOrientationArcRotateCamera
  99587. * @param name defines camera name
  99588. * @param alpha defines the camera rotation along the logitudinal axis
  99589. * @param beta defines the camera rotation along the latitudinal axis
  99590. * @param radius defines the camera distance from its target
  99591. * @param target defines the camera target
  99592. * @param scene defines the scene the camera belongs to
  99593. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99594. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99595. */
  99596. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  99597. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99598. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99599. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99600. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99601. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99602. _this.inputs.addVRDeviceOrientation();
  99603. return _this;
  99604. }
  99605. /**
  99606. * Gets camera class name
  99607. * @returns VRDeviceOrientationArcRotateCamera
  99608. */
  99609. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  99610. return "VRDeviceOrientationArcRotateCamera";
  99611. };
  99612. return VRDeviceOrientationArcRotateCamera;
  99613. }(BABYLON.ArcRotateCamera));
  99614. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  99615. })(BABYLON || (BABYLON = {}));
  99616. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  99617. var BABYLON;
  99618. (function (BABYLON) {
  99619. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  99620. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  99621. });
  99622. /**
  99623. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  99624. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99625. */
  99626. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  99627. __extends(VRDeviceOrientationGamepadCamera, _super);
  99628. /**
  99629. * Creates a new VRDeviceOrientationGamepadCamera
  99630. * @param name defines camera name
  99631. * @param position defines the start position of the camera
  99632. * @param scene defines the scene the camera belongs to
  99633. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99634. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99635. */
  99636. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99637. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99638. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99639. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  99640. _this.inputs.addGamepad();
  99641. return _this;
  99642. }
  99643. /**
  99644. * Gets camera class name
  99645. * @returns VRDeviceOrientationGamepadCamera
  99646. */
  99647. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  99648. return "VRDeviceOrientationGamepadCamera";
  99649. };
  99650. return VRDeviceOrientationGamepadCamera;
  99651. }(BABYLON.VRDeviceOrientationFreeCamera));
  99652. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  99653. })(BABYLON || (BABYLON = {}));
  99654. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  99655. var BABYLON;
  99656. (function (BABYLON) {
  99657. var VRExperienceHelperGazer = /** @class */ (function () {
  99658. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  99659. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  99660. this.scene = scene;
  99661. /** @hidden */
  99662. this._pointerDownOnMeshAsked = false;
  99663. /** @hidden */
  99664. this._isActionableMesh = false;
  99665. /** @hidden */
  99666. this._teleportationRequestInitiated = false;
  99667. /** @hidden */
  99668. this._teleportationBackRequestInitiated = false;
  99669. /** @hidden */
  99670. this._rotationRightAsked = false;
  99671. /** @hidden */
  99672. this._rotationLeftAsked = false;
  99673. /** @hidden */
  99674. this._dpadPressed = true;
  99675. /** @hidden */
  99676. this._activePointer = false;
  99677. this._id = VRExperienceHelperGazer._idCounter++;
  99678. // Gaze tracker
  99679. if (!gazeTrackerToClone) {
  99680. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  99681. this._gazeTracker.bakeCurrentTransformIntoVertices();
  99682. this._gazeTracker.isPickable = false;
  99683. this._gazeTracker.isVisible = false;
  99684. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  99685. targetMat.specularColor = BABYLON.Color3.Black();
  99686. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99687. targetMat.backFaceCulling = false;
  99688. this._gazeTracker.material = targetMat;
  99689. }
  99690. else {
  99691. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  99692. }
  99693. }
  99694. /** @hidden */
  99695. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  99696. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  99697. };
  99698. /** @hidden */
  99699. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  99700. this._pointerDownOnMeshAsked = true;
  99701. if (this._currentHit) {
  99702. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  99703. }
  99704. };
  99705. /** @hidden */
  99706. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  99707. if (this._currentHit) {
  99708. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  99709. }
  99710. this._pointerDownOnMeshAsked = false;
  99711. };
  99712. /** @hidden */
  99713. VRExperienceHelperGazer.prototype._activatePointer = function () {
  99714. this._activePointer = true;
  99715. };
  99716. /** @hidden */
  99717. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  99718. this._activePointer = false;
  99719. };
  99720. /** @hidden */
  99721. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  99722. if (distance === void 0) { distance = 100; }
  99723. };
  99724. VRExperienceHelperGazer.prototype.dispose = function () {
  99725. this._interactionsEnabled = false;
  99726. this._teleportationEnabled = false;
  99727. if (this._gazeTracker) {
  99728. this._gazeTracker.dispose();
  99729. }
  99730. };
  99731. VRExperienceHelperGazer._idCounter = 0;
  99732. return VRExperienceHelperGazer;
  99733. }());
  99734. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  99735. __extends(VRExperienceHelperControllerGazer, _super);
  99736. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  99737. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  99738. _this.webVRController = webVRController;
  99739. // Laser pointer
  99740. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  99741. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  99742. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99743. laserPointerMaterial.alpha = 0.6;
  99744. _this._laserPointer.material = laserPointerMaterial;
  99745. _this._laserPointer.rotation.x = Math.PI / 2;
  99746. _this._laserPointer.position.z = -0.5;
  99747. _this._laserPointer.isVisible = false;
  99748. _this._laserPointer.isPickable = false;
  99749. if (!webVRController.mesh) {
  99750. // Create an empty mesh that is used prior to loading the high quality model
  99751. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  99752. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  99753. preloadPointerPose.rotation.x = -0.7;
  99754. preloadMesh.addChild(preloadPointerPose);
  99755. webVRController.attachToMesh(preloadMesh);
  99756. }
  99757. _this._setLaserPointerParent(webVRController.mesh);
  99758. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  99759. _this._setLaserPointerParent(mesh);
  99760. });
  99761. return _this;
  99762. }
  99763. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  99764. return this.webVRController.getForwardRay(length);
  99765. };
  99766. /** @hidden */
  99767. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  99768. _super.prototype._activatePointer.call(this);
  99769. this._laserPointer.isVisible = true;
  99770. };
  99771. /** @hidden */
  99772. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  99773. _super.prototype._deactivatePointer.call(this);
  99774. this._laserPointer.isVisible = false;
  99775. };
  99776. /** @hidden */
  99777. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  99778. this._laserPointer.material.emissiveColor = color;
  99779. };
  99780. /** @hidden */
  99781. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  99782. var makeNotPick = function (root) {
  99783. root.isPickable = false;
  99784. root.getChildMeshes().forEach(function (c) {
  99785. makeNotPick(c);
  99786. });
  99787. };
  99788. makeNotPick(mesh);
  99789. var childMeshes = mesh.getChildMeshes();
  99790. this.webVRController._pointingPoseNode = null;
  99791. for (var i = 0; i < childMeshes.length; i++) {
  99792. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  99793. mesh = childMeshes[i];
  99794. this.webVRController._pointingPoseNode = mesh;
  99795. break;
  99796. }
  99797. }
  99798. this._laserPointer.parent = mesh;
  99799. };
  99800. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  99801. if (distance === void 0) { distance = 100; }
  99802. this._laserPointer.scaling.y = distance;
  99803. this._laserPointer.position.z = -distance / 2;
  99804. };
  99805. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  99806. _super.prototype.dispose.call(this);
  99807. this._laserPointer.dispose();
  99808. if (this._meshAttachedObserver) {
  99809. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  99810. }
  99811. };
  99812. return VRExperienceHelperControllerGazer;
  99813. }(VRExperienceHelperGazer));
  99814. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  99815. __extends(VRExperienceHelperCameraGazer, _super);
  99816. function VRExperienceHelperCameraGazer(getCamera, scene) {
  99817. var _this = _super.call(this, scene) || this;
  99818. _this.getCamera = getCamera;
  99819. return _this;
  99820. }
  99821. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  99822. var camera = this.getCamera();
  99823. if (camera) {
  99824. return camera.getForwardRay(length);
  99825. }
  99826. else {
  99827. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  99828. }
  99829. };
  99830. return VRExperienceHelperCameraGazer;
  99831. }(VRExperienceHelperGazer));
  99832. /**
  99833. * Helps to quickly add VR support to an existing scene.
  99834. * See http://doc.babylonjs.com/how_to/webvr_helper
  99835. */
  99836. var VRExperienceHelper = /** @class */ (function () {
  99837. /**
  99838. * Instantiates a VRExperienceHelper.
  99839. * Helps to quickly add VR support to an existing scene.
  99840. * @param scene The scene the VRExperienceHelper belongs to.
  99841. * @param webVROptions Options to modify the vr experience helper's behavior.
  99842. */
  99843. function VRExperienceHelper(scene,
  99844. /** Options to modify the vr experience helper's behavior. */
  99845. webVROptions) {
  99846. if (webVROptions === void 0) { webVROptions = {}; }
  99847. var _this = this;
  99848. this.webVROptions = webVROptions;
  99849. // Can the system support WebVR, even if a headset isn't plugged in?
  99850. this._webVRsupported = false;
  99851. // If WebVR is supported, is a headset plugged in and are we ready to present?
  99852. this._webVRready = false;
  99853. // Are we waiting for the requestPresent callback to complete?
  99854. this._webVRrequesting = false;
  99855. // Are we presenting to the headset right now? (this is the vrDevice state)
  99856. this._webVRpresenting = false;
  99857. // Are we presenting in the fullscreen fallback?
  99858. this._fullscreenVRpresenting = false;
  99859. /**
  99860. * Observable raised when entering VR.
  99861. */
  99862. this.onEnteringVRObservable = new BABYLON.Observable();
  99863. /**
  99864. * Observable raised when exiting VR.
  99865. */
  99866. this.onExitingVRObservable = new BABYLON.Observable();
  99867. /**
  99868. * Observable raised when controller mesh is loaded.
  99869. */
  99870. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99871. this._useCustomVRButton = false;
  99872. this._teleportationRequested = false;
  99873. this._teleportActive = false;
  99874. this._floorMeshesCollection = [];
  99875. this._rotationAllowed = true;
  99876. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  99877. this._isDefaultTeleportationTarget = true;
  99878. this._teleportationFillColor = "#444444";
  99879. this._teleportationBorderColor = "#FFFFFF";
  99880. this._rotationAngle = 0;
  99881. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  99882. this._padSensibilityUp = 0.65;
  99883. this._padSensibilityDown = 0.35;
  99884. this._leftController = null;
  99885. this._rightController = null;
  99886. /**
  99887. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  99888. */
  99889. this.onNewMeshSelected = new BABYLON.Observable();
  99890. /**
  99891. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  99892. */
  99893. this.onNewMeshPicked = new BABYLON.Observable();
  99894. /**
  99895. * Observable raised before camera teleportation
  99896. */
  99897. this.onBeforeCameraTeleport = new BABYLON.Observable();
  99898. /**
  99899. * Observable raised after camera teleportation
  99900. */
  99901. this.onAfterCameraTeleport = new BABYLON.Observable();
  99902. /**
  99903. * Observable raised when current selected mesh gets unselected
  99904. */
  99905. this.onSelectedMeshUnselected = new BABYLON.Observable();
  99906. /**
  99907. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  99908. */
  99909. this.teleportationEnabled = true;
  99910. this._teleportationInitialized = false;
  99911. this._interactionsEnabled = false;
  99912. this._interactionsRequested = false;
  99913. this._displayGaze = true;
  99914. this._displayLaserPointer = true;
  99915. /**
  99916. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  99917. */
  99918. this.updateGazeTrackerScale = true;
  99919. this._onResize = function () {
  99920. _this.moveButtonToBottomRight();
  99921. if (_this._fullscreenVRpresenting && _this._webVRready) {
  99922. _this.exitVR();
  99923. }
  99924. };
  99925. this._onFullscreenChange = function () {
  99926. if (document.fullscreen !== undefined) {
  99927. _this._fullscreenVRpresenting = document.fullscreen;
  99928. }
  99929. else if (document.mozFullScreen !== undefined) {
  99930. _this._fullscreenVRpresenting = document.mozFullScreen;
  99931. }
  99932. else if (document.webkitIsFullScreen !== undefined) {
  99933. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  99934. }
  99935. else if (document.msIsFullScreen !== undefined) {
  99936. _this._fullscreenVRpresenting = document.msIsFullScreen;
  99937. }
  99938. else if (document.msFullscreenElement !== undefined) {
  99939. _this._fullscreenVRpresenting = document.msFullscreenElement;
  99940. }
  99941. if (!_this._fullscreenVRpresenting && _this._canvas) {
  99942. _this.exitVR();
  99943. if (!_this._useCustomVRButton) {
  99944. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  99945. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  99946. }
  99947. }
  99948. };
  99949. this.beforeRender = function () {
  99950. if (_this._leftController && _this._leftController._activePointer) {
  99951. _this._castRayAndSelectObject(_this._leftController);
  99952. }
  99953. if (_this._rightController && _this._rightController._activePointer) {
  99954. _this._castRayAndSelectObject(_this._rightController);
  99955. }
  99956. if (_this._noControllerIsActive) {
  99957. _this._castRayAndSelectObject(_this._cameraGazer);
  99958. }
  99959. else {
  99960. _this._cameraGazer._gazeTracker.isVisible = false;
  99961. }
  99962. };
  99963. this._onNewGamepadConnected = function (gamepad) {
  99964. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  99965. if (gamepad.leftStick) {
  99966. gamepad.onleftstickchanged(function (stickValues) {
  99967. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  99968. // Listening to classic/xbox gamepad only if no VR controller is active
  99969. if ((!_this._leftController && !_this._rightController) ||
  99970. ((_this._leftController && !_this._leftController._activePointer) &&
  99971. (_this._rightController && !_this._rightController._activePointer))) {
  99972. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  99973. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  99974. }
  99975. }
  99976. });
  99977. }
  99978. if (gamepad.rightStick) {
  99979. gamepad.onrightstickchanged(function (stickValues) {
  99980. if (_this._teleportationInitialized) {
  99981. _this._checkRotate(stickValues, _this._cameraGazer);
  99982. }
  99983. });
  99984. }
  99985. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  99986. gamepad.onbuttondown(function (buttonPressed) {
  99987. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99988. _this._cameraGazer._selectionPointerDown();
  99989. }
  99990. });
  99991. gamepad.onbuttonup(function (buttonPressed) {
  99992. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99993. _this._cameraGazer._selectionPointerUp();
  99994. }
  99995. });
  99996. }
  99997. }
  99998. else {
  99999. var webVRController = gamepad;
  100000. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100001. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100002. _this._rightController = controller;
  100003. }
  100004. else {
  100005. _this._leftController = controller;
  100006. }
  100007. _this._tryEnableInteractionOnController(controller);
  100008. }
  100009. };
  100010. // 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
  100011. this._tryEnableInteractionOnController = function (controller) {
  100012. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100013. _this._enableInteractionOnController(controller);
  100014. }
  100015. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100016. _this._enableTeleportationOnController(controller);
  100017. }
  100018. };
  100019. this._onNewGamepadDisconnected = function (gamepad) {
  100020. if (gamepad instanceof BABYLON.WebVRController) {
  100021. if (gamepad.hand === "left" && _this._leftController != null) {
  100022. _this._leftController.dispose();
  100023. _this._leftController = null;
  100024. }
  100025. if (gamepad.hand === "right" && _this._rightController != null) {
  100026. _this._rightController.dispose();
  100027. _this._rightController = null;
  100028. }
  100029. }
  100030. };
  100031. this._workingVector = BABYLON.Vector3.Zero();
  100032. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100033. this._workingMatrix = BABYLON.Matrix.Identity();
  100034. this._scene = scene;
  100035. this._canvas = scene.getEngine().getRenderingCanvas();
  100036. // Parse options
  100037. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100038. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100039. }
  100040. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100041. webVROptions.createDeviceOrientationCamera = true;
  100042. }
  100043. if (webVROptions.laserToggle === undefined) {
  100044. webVROptions.laserToggle = true;
  100045. }
  100046. if (webVROptions.defaultHeight === undefined) {
  100047. webVROptions.defaultHeight = 1.7;
  100048. }
  100049. if (webVROptions.useCustomVRButton) {
  100050. this._useCustomVRButton = true;
  100051. if (webVROptions.customVRButton) {
  100052. this._btnVR = webVROptions.customVRButton;
  100053. }
  100054. }
  100055. if (webVROptions.rayLength) {
  100056. this._rayLength = webVROptions.rayLength;
  100057. }
  100058. this._defaultHeight = webVROptions.defaultHeight;
  100059. if (webVROptions.positionScale) {
  100060. this._rayLength *= webVROptions.positionScale;
  100061. this._defaultHeight *= webVROptions.positionScale;
  100062. }
  100063. this._hasEnteredVR = false;
  100064. // Set position
  100065. if (this._scene.activeCamera) {
  100066. this._position = this._scene.activeCamera.position.clone();
  100067. }
  100068. else {
  100069. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100070. }
  100071. // Set non-vr camera
  100072. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100073. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100074. // Copy data from existing camera
  100075. if (this._scene.activeCamera) {
  100076. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100077. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100078. // Set rotation from previous camera
  100079. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100080. var targetCamera = this._scene.activeCamera;
  100081. if (targetCamera.rotationQuaternion) {
  100082. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100083. }
  100084. else {
  100085. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100086. }
  100087. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100088. }
  100089. }
  100090. this._scene.activeCamera = this._deviceOrientationCamera;
  100091. if (this._canvas) {
  100092. this._scene.activeCamera.attachControl(this._canvas);
  100093. }
  100094. }
  100095. else {
  100096. this._existingCamera = this._scene.activeCamera;
  100097. }
  100098. // Create VR cameras
  100099. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100100. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100101. }
  100102. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100103. this._webVRCamera.useStandingMatrix();
  100104. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100105. // Create default button
  100106. if (!this._useCustomVRButton) {
  100107. this._btnVR = document.createElement("BUTTON");
  100108. this._btnVR.className = "babylonVRicon";
  100109. this._btnVR.id = "babylonVRiconbtn";
  100110. this._btnVR.title = "Click to switch to VR";
  100111. 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) }";
  100112. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100113. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100114. // css += ".babylonVRicon.vrdisplaysupported { }";
  100115. // css += ".babylonVRicon.vrdisplayready { }";
  100116. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100117. var style = document.createElement('style');
  100118. style.appendChild(document.createTextNode(css));
  100119. document.getElementsByTagName('head')[0].appendChild(style);
  100120. this.moveButtonToBottomRight();
  100121. }
  100122. // VR button click event
  100123. if (this._btnVR) {
  100124. this._btnVR.addEventListener("click", function () {
  100125. if (!_this.isInVRMode) {
  100126. _this.enterVR();
  100127. }
  100128. else {
  100129. _this.exitVR();
  100130. }
  100131. });
  100132. }
  100133. // Window events
  100134. window.addEventListener("resize", this._onResize);
  100135. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  100136. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  100137. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  100138. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  100139. document.onmsfullscreenchange = this._onFullscreenChange;
  100140. // Display vr button when headset is connected
  100141. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100142. this.displayVRButton();
  100143. }
  100144. else {
  100145. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  100146. if (e.vrDisplay) {
  100147. _this.displayVRButton();
  100148. }
  100149. });
  100150. }
  100151. // Exiting VR mode using 'ESC' key on desktop
  100152. this._onKeyDown = function (event) {
  100153. if (event.keyCode === 27 && _this.isInVRMode) {
  100154. _this.exitVR();
  100155. }
  100156. };
  100157. document.addEventListener("keydown", this._onKeyDown);
  100158. // Exiting VR mode double tapping the touch screen
  100159. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  100160. if (_this.isInVRMode) {
  100161. _this.exitVR();
  100162. if (_this._fullscreenVRpresenting) {
  100163. _this._scene.getEngine().switchFullscreen(true);
  100164. }
  100165. }
  100166. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  100167. // Listen for WebVR display changes
  100168. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  100169. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  100170. this._onVRRequestPresentStart = function () {
  100171. _this._webVRrequesting = true;
  100172. _this.updateButtonVisibility();
  100173. };
  100174. this._onVRRequestPresentComplete = function (success) {
  100175. _this._webVRrequesting = false;
  100176. _this.updateButtonVisibility();
  100177. };
  100178. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  100179. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  100180. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  100181. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  100182. scene.onDisposeObservable.add(function () {
  100183. _this.dispose();
  100184. });
  100185. // Gamepad connection events
  100186. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  100187. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  100188. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  100189. this.updateButtonVisibility();
  100190. //create easing functions
  100191. this._circleEase = new BABYLON.CircleEase();
  100192. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  100193. if (this.webVROptions.floorMeshes) {
  100194. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  100195. }
  100196. }
  100197. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  100198. /** Return this.onEnteringVRObservable
  100199. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  100200. */
  100201. get: function () {
  100202. return this.onEnteringVRObservable;
  100203. },
  100204. enumerable: true,
  100205. configurable: true
  100206. });
  100207. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  100208. /** Return this.onExitingVRObservable
  100209. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  100210. */
  100211. get: function () {
  100212. return this.onExitingVRObservable;
  100213. },
  100214. enumerable: true,
  100215. configurable: true
  100216. });
  100217. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  100218. /** Return this.onControllerMeshLoadedObservable
  100219. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  100220. */
  100221. get: function () {
  100222. return this.onControllerMeshLoadedObservable;
  100223. },
  100224. enumerable: true,
  100225. configurable: true
  100226. });
  100227. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  100228. /**
  100229. * The mesh used to display where the user is going to teleport.
  100230. */
  100231. get: function () {
  100232. return this._teleportationTarget;
  100233. },
  100234. /**
  100235. * Sets the mesh to be used to display where the user is going to teleport.
  100236. */
  100237. set: function (value) {
  100238. if (value) {
  100239. value.name = "teleportationTarget";
  100240. this._isDefaultTeleportationTarget = false;
  100241. this._teleportationTarget = value;
  100242. }
  100243. },
  100244. enumerable: true,
  100245. configurable: true
  100246. });
  100247. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  100248. /**
  100249. * 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
  100250. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  100251. * See http://doc.babylonjs.com/resources/baking_transformations
  100252. */
  100253. get: function () {
  100254. return this._cameraGazer._gazeTracker;
  100255. },
  100256. set: function (value) {
  100257. if (value) {
  100258. // Dispose of existing meshes
  100259. if (this._cameraGazer._gazeTracker) {
  100260. this._cameraGazer._gazeTracker.dispose();
  100261. }
  100262. if (this._leftController && this._leftController._gazeTracker) {
  100263. this._leftController._gazeTracker.dispose();
  100264. }
  100265. if (this._rightController && this._rightController._gazeTracker) {
  100266. this._rightController._gazeTracker.dispose();
  100267. }
  100268. // Set and create gaze trackers on head and controllers
  100269. this._cameraGazer._gazeTracker = value;
  100270. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  100271. this._cameraGazer._gazeTracker.isPickable = false;
  100272. this._cameraGazer._gazeTracker.isVisible = false;
  100273. this._cameraGazer._gazeTracker.name = "gazeTracker";
  100274. if (this._leftController) {
  100275. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100276. }
  100277. if (this._rightController) {
  100278. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100279. }
  100280. }
  100281. },
  100282. enumerable: true,
  100283. configurable: true
  100284. });
  100285. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  100286. /**
  100287. * The gaze tracking mesh corresponding to the left controller
  100288. */
  100289. get: function () {
  100290. if (this._leftController) {
  100291. return this._leftController._gazeTracker;
  100292. }
  100293. return null;
  100294. },
  100295. enumerable: true,
  100296. configurable: true
  100297. });
  100298. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  100299. /**
  100300. * The gaze tracking mesh corresponding to the right controller
  100301. */
  100302. get: function () {
  100303. if (this._rightController) {
  100304. return this._rightController._gazeTracker;
  100305. }
  100306. return null;
  100307. },
  100308. enumerable: true,
  100309. configurable: true
  100310. });
  100311. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  100312. /**
  100313. * If the ray of the gaze should be displayed.
  100314. */
  100315. get: function () {
  100316. return this._displayGaze;
  100317. },
  100318. /**
  100319. * Sets if the ray of the gaze should be displayed.
  100320. */
  100321. set: function (value) {
  100322. this._displayGaze = value;
  100323. if (!value) {
  100324. this._cameraGazer._gazeTracker.isVisible = false;
  100325. if (this._leftController) {
  100326. this._leftController._gazeTracker.isVisible = false;
  100327. }
  100328. if (this._rightController) {
  100329. this._rightController._gazeTracker.isVisible = false;
  100330. }
  100331. }
  100332. },
  100333. enumerable: true,
  100334. configurable: true
  100335. });
  100336. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  100337. /**
  100338. * If the ray of the LaserPointer should be displayed.
  100339. */
  100340. get: function () {
  100341. return this._displayLaserPointer;
  100342. },
  100343. /**
  100344. * Sets if the ray of the LaserPointer should be displayed.
  100345. */
  100346. set: function (value) {
  100347. this._displayLaserPointer = value;
  100348. if (!value) {
  100349. if (this._rightController) {
  100350. this._rightController._deactivatePointer();
  100351. this._rightController._gazeTracker.isVisible = false;
  100352. }
  100353. if (this._leftController) {
  100354. this._leftController._deactivatePointer();
  100355. this._leftController._gazeTracker.isVisible = false;
  100356. }
  100357. }
  100358. else {
  100359. if (this._rightController) {
  100360. this._rightController._activatePointer();
  100361. }
  100362. if (this._leftController) {
  100363. this._leftController._activatePointer();
  100364. }
  100365. }
  100366. },
  100367. enumerable: true,
  100368. configurable: true
  100369. });
  100370. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  100371. /**
  100372. * The deviceOrientationCamera used as the camera when not in VR.
  100373. */
  100374. get: function () {
  100375. return this._deviceOrientationCamera;
  100376. },
  100377. enumerable: true,
  100378. configurable: true
  100379. });
  100380. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  100381. /**
  100382. * Based on the current WebVR support, returns the current VR camera used.
  100383. */
  100384. get: function () {
  100385. if (this._webVRready) {
  100386. return this._webVRCamera;
  100387. }
  100388. else {
  100389. return this._scene.activeCamera;
  100390. }
  100391. },
  100392. enumerable: true,
  100393. configurable: true
  100394. });
  100395. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  100396. /**
  100397. * The webVRCamera which is used when in VR.
  100398. */
  100399. get: function () {
  100400. return this._webVRCamera;
  100401. },
  100402. enumerable: true,
  100403. configurable: true
  100404. });
  100405. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  100406. /**
  100407. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  100408. */
  100409. get: function () {
  100410. return this._vrDeviceOrientationCamera;
  100411. },
  100412. enumerable: true,
  100413. configurable: true
  100414. });
  100415. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  100416. get: function () {
  100417. var result = this._cameraGazer._teleportationRequestInitiated
  100418. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  100419. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  100420. return result;
  100421. },
  100422. enumerable: true,
  100423. configurable: true
  100424. });
  100425. // Raised when one of the controller has loaded successfully its associated default mesh
  100426. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  100427. if (this._leftController && this._leftController.webVRController == webVRController) {
  100428. if (webVRController.mesh) {
  100429. this._leftController._setLaserPointerParent(webVRController.mesh);
  100430. }
  100431. }
  100432. if (this._rightController && this._rightController.webVRController == webVRController) {
  100433. if (webVRController.mesh) {
  100434. this._rightController._setLaserPointerParent(webVRController.mesh);
  100435. }
  100436. }
  100437. try {
  100438. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  100439. }
  100440. catch (err) {
  100441. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  100442. }
  100443. };
  100444. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  100445. /**
  100446. * Gets a value indicating if we are currently in VR mode.
  100447. */
  100448. get: function () {
  100449. return this._webVRpresenting || this._fullscreenVRpresenting;
  100450. },
  100451. enumerable: true,
  100452. configurable: true
  100453. });
  100454. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  100455. var vrDisplay = this._scene.getEngine().getVRDevice();
  100456. if (vrDisplay) {
  100457. var wasPresenting = this._webVRpresenting;
  100458. this._webVRpresenting = vrDisplay.isPresenting;
  100459. if (wasPresenting && !this._webVRpresenting)
  100460. this.exitVR();
  100461. }
  100462. else {
  100463. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  100464. }
  100465. this.updateButtonVisibility();
  100466. };
  100467. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  100468. this._webVRsupported = eventArgs.vrSupported;
  100469. this._webVRready = !!eventArgs.vrDisplay;
  100470. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  100471. this.updateButtonVisibility();
  100472. };
  100473. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  100474. if (this._canvas && !this._useCustomVRButton) {
  100475. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  100476. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  100477. }
  100478. };
  100479. VRExperienceHelper.prototype.displayVRButton = function () {
  100480. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  100481. document.body.appendChild(this._btnVR);
  100482. this._btnVRDisplayed = true;
  100483. }
  100484. };
  100485. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  100486. if (!this._btnVR || this._useCustomVRButton) {
  100487. return;
  100488. }
  100489. this._btnVR.className = "babylonVRicon";
  100490. if (this.isInVRMode) {
  100491. this._btnVR.className += " vrdisplaypresenting";
  100492. }
  100493. else {
  100494. if (this._webVRready)
  100495. this._btnVR.className += " vrdisplayready";
  100496. if (this._webVRsupported)
  100497. this._btnVR.className += " vrdisplaysupported";
  100498. if (this._webVRrequesting)
  100499. this._btnVR.className += " vrdisplayrequesting";
  100500. }
  100501. };
  100502. /**
  100503. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  100504. * Otherwise, will use the fullscreen API.
  100505. */
  100506. VRExperienceHelper.prototype.enterVR = function () {
  100507. if (this.onEnteringVRObservable) {
  100508. try {
  100509. this.onEnteringVRObservable.notifyObservers(this);
  100510. }
  100511. catch (err) {
  100512. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  100513. }
  100514. }
  100515. if (this._scene.activeCamera) {
  100516. this._position = this._scene.activeCamera.position.clone();
  100517. // make sure that we return to the last active camera
  100518. this._existingCamera = this._scene.activeCamera;
  100519. }
  100520. if (this._webVRrequesting)
  100521. return;
  100522. // If WebVR is supported and a headset is connected
  100523. if (this._webVRready) {
  100524. if (!this._webVRpresenting) {
  100525. this._webVRCamera.position = this._position;
  100526. this._scene.activeCamera = this._webVRCamera;
  100527. }
  100528. }
  100529. else if (this._vrDeviceOrientationCamera) {
  100530. this._vrDeviceOrientationCamera.position = this._position;
  100531. if (this._scene.activeCamera) {
  100532. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100533. }
  100534. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  100535. this._scene.getEngine().switchFullscreen(true);
  100536. this.updateButtonVisibility();
  100537. }
  100538. if (this._scene.activeCamera && this._canvas) {
  100539. this._scene.activeCamera.attachControl(this._canvas);
  100540. }
  100541. if (this._interactionsEnabled) {
  100542. this._scene.registerBeforeRender(this.beforeRender);
  100543. }
  100544. this._hasEnteredVR = true;
  100545. };
  100546. /**
  100547. * Attempt to exit VR, or fullscreen.
  100548. */
  100549. VRExperienceHelper.prototype.exitVR = function () {
  100550. if (this._hasEnteredVR) {
  100551. if (this.onExitingVRObservable) {
  100552. try {
  100553. this.onExitingVRObservable.notifyObservers(this);
  100554. }
  100555. catch (err) {
  100556. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  100557. }
  100558. }
  100559. if (this._webVRpresenting) {
  100560. this._scene.getEngine().disableVR();
  100561. }
  100562. if (this._scene.activeCamera) {
  100563. this._position = this._scene.activeCamera.position.clone();
  100564. }
  100565. if (this._deviceOrientationCamera) {
  100566. this._deviceOrientationCamera.position = this._position;
  100567. this._scene.activeCamera = this._deviceOrientationCamera;
  100568. if (this._canvas) {
  100569. this._scene.activeCamera.attachControl(this._canvas);
  100570. }
  100571. }
  100572. else if (this._existingCamera) {
  100573. this._existingCamera.position = this._position;
  100574. this._scene.activeCamera = this._existingCamera;
  100575. }
  100576. this.updateButtonVisibility();
  100577. if (this._interactionsEnabled) {
  100578. this._scene.unregisterBeforeRender(this.beforeRender);
  100579. this._cameraGazer._gazeTracker.isVisible = false;
  100580. if (this._leftController) {
  100581. this._leftController._gazeTracker.isVisible = false;
  100582. }
  100583. if (this._rightController) {
  100584. this._rightController._gazeTracker.isVisible = false;
  100585. }
  100586. }
  100587. // resize to update width and height when exiting vr exits fullscreen
  100588. this._scene.getEngine().resize();
  100589. this._hasEnteredVR = false;
  100590. }
  100591. };
  100592. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  100593. /**
  100594. * The position of the vr experience helper.
  100595. */
  100596. get: function () {
  100597. return this._position;
  100598. },
  100599. /**
  100600. * Sets the position of the vr experience helper.
  100601. */
  100602. set: function (value) {
  100603. this._position = value;
  100604. if (this._scene.activeCamera) {
  100605. this._scene.activeCamera.position = value;
  100606. }
  100607. },
  100608. enumerable: true,
  100609. configurable: true
  100610. });
  100611. /**
  100612. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  100613. */
  100614. VRExperienceHelper.prototype.enableInteractions = function () {
  100615. var _this = this;
  100616. if (!this._interactionsEnabled) {
  100617. this._interactionsRequested = true;
  100618. if (this._leftController) {
  100619. this._enableInteractionOnController(this._leftController);
  100620. }
  100621. if (this._rightController) {
  100622. this._enableInteractionOnController(this._rightController);
  100623. }
  100624. this.raySelectionPredicate = function (mesh) {
  100625. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  100626. };
  100627. this.meshSelectionPredicate = function (mesh) {
  100628. return true;
  100629. };
  100630. this._raySelectionPredicate = function (mesh) {
  100631. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  100632. && mesh.name.indexOf("teleportationTarget") === -1
  100633. && mesh.name.indexOf("torusTeleportation") === -1)) {
  100634. return _this.raySelectionPredicate(mesh);
  100635. }
  100636. return false;
  100637. };
  100638. this._interactionsEnabled = true;
  100639. }
  100640. };
  100641. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  100642. get: function () {
  100643. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  100644. },
  100645. enumerable: true,
  100646. configurable: true
  100647. });
  100648. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  100649. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  100650. if (this._floorMeshesCollection[i].id === mesh.id) {
  100651. return true;
  100652. }
  100653. }
  100654. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  100655. return true;
  100656. }
  100657. return false;
  100658. };
  100659. /**
  100660. * Adds a floor mesh to be used for teleportation.
  100661. * @param floorMesh the mesh to be used for teleportation.
  100662. */
  100663. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  100664. if (!this._floorMeshesCollection) {
  100665. return;
  100666. }
  100667. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  100668. return;
  100669. }
  100670. this._floorMeshesCollection.push(floorMesh);
  100671. };
  100672. /**
  100673. * Removes a floor mesh from being used for teleportation.
  100674. * @param floorMesh the mesh to be removed.
  100675. */
  100676. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  100677. if (!this._floorMeshesCollection) {
  100678. return;
  100679. }
  100680. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  100681. if (meshIndex !== -1) {
  100682. this._floorMeshesCollection.splice(meshIndex, 1);
  100683. }
  100684. };
  100685. /**
  100686. * Enables interactions and teleportation using the VR controllers and gaze.
  100687. * @param vrTeleportationOptions options to modify teleportation behavior.
  100688. */
  100689. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  100690. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  100691. if (!this._teleportationInitialized) {
  100692. this._teleportationRequested = true;
  100693. this.enableInteractions();
  100694. if (vrTeleportationOptions.floorMeshName) {
  100695. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  100696. }
  100697. if (vrTeleportationOptions.floorMeshes) {
  100698. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  100699. }
  100700. if (this._leftController != null) {
  100701. this._enableTeleportationOnController(this._leftController);
  100702. }
  100703. if (this._rightController != null) {
  100704. this._enableTeleportationOnController(this._rightController);
  100705. }
  100706. // Creates an image processing post process for the vignette not relying
  100707. // on the main scene configuration for image processing to reduce setup and spaces
  100708. // (gamma/linear) conflicts.
  100709. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  100710. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  100711. imageProcessingConfiguration.vignetteEnabled = true;
  100712. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  100713. this._webVRCamera.detachPostProcess(this._postProcessMove);
  100714. this._teleportationInitialized = true;
  100715. if (this._isDefaultTeleportationTarget) {
  100716. this._createTeleportationCircles();
  100717. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  100718. }
  100719. }
  100720. };
  100721. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  100722. var _this = this;
  100723. var controllerMesh = controller.webVRController.mesh;
  100724. if (controllerMesh) {
  100725. controller._interactionsEnabled = true;
  100726. controller._activatePointer();
  100727. if (this.webVROptions.laserToggle) {
  100728. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  100729. // Enabling / disabling laserPointer
  100730. if (_this._displayLaserPointer && stateObject.value === 1) {
  100731. if (controller._activePointer) {
  100732. controller._deactivatePointer();
  100733. }
  100734. else {
  100735. controller._activatePointer();
  100736. }
  100737. if (_this.displayGaze) {
  100738. controller._gazeTracker.isVisible = controller._activePointer;
  100739. }
  100740. }
  100741. });
  100742. }
  100743. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  100744. var gazer = controller;
  100745. if (_this._noControllerIsActive) {
  100746. gazer = _this._cameraGazer;
  100747. }
  100748. if (!gazer._pointerDownOnMeshAsked) {
  100749. if (stateObject.value > _this._padSensibilityUp) {
  100750. gazer._selectionPointerDown();
  100751. }
  100752. }
  100753. else if (stateObject.value < _this._padSensibilityDown) {
  100754. gazer._selectionPointerUp();
  100755. }
  100756. });
  100757. }
  100758. };
  100759. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  100760. // Dont teleport if another gaze already requested teleportation
  100761. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  100762. return;
  100763. }
  100764. if (!gazer._teleportationRequestInitiated) {
  100765. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  100766. gazer._activatePointer();
  100767. gazer._teleportationRequestInitiated = true;
  100768. }
  100769. }
  100770. else {
  100771. // Listening to the proper controller values changes to confirm teleportation
  100772. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  100773. if (this._teleportActive) {
  100774. this.teleportCamera(this._haloCenter);
  100775. }
  100776. gazer._teleportationRequestInitiated = false;
  100777. }
  100778. }
  100779. };
  100780. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  100781. // Only rotate when user is not currently selecting a teleportation location
  100782. if (gazer._teleportationRequestInitiated) {
  100783. return;
  100784. }
  100785. if (!gazer._rotationLeftAsked) {
  100786. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  100787. gazer._rotationLeftAsked = true;
  100788. if (this._rotationAllowed) {
  100789. this._rotateCamera(false);
  100790. }
  100791. }
  100792. }
  100793. else {
  100794. if (stateObject.x > -this._padSensibilityDown) {
  100795. gazer._rotationLeftAsked = false;
  100796. }
  100797. }
  100798. if (!gazer._rotationRightAsked) {
  100799. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  100800. gazer._rotationRightAsked = true;
  100801. if (this._rotationAllowed) {
  100802. this._rotateCamera(true);
  100803. }
  100804. }
  100805. }
  100806. else {
  100807. if (stateObject.x < this._padSensibilityDown) {
  100808. gazer._rotationRightAsked = false;
  100809. }
  100810. }
  100811. };
  100812. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  100813. // Only teleport backwards when user is not currently selecting a teleportation location
  100814. if (gazer._teleportationRequestInitiated) {
  100815. return;
  100816. }
  100817. // Teleport backwards
  100818. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  100819. if (!gazer._teleportationBackRequestInitiated) {
  100820. if (!this.currentVRCamera) {
  100821. return;
  100822. }
  100823. // Get rotation and position of the current camera
  100824. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  100825. var position = this.currentVRCamera.position;
  100826. // If the camera has device position, use that instead
  100827. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  100828. rotation = this.currentVRCamera.deviceRotationQuaternion;
  100829. position = this.currentVRCamera.devicePosition;
  100830. }
  100831. // Get matrix with only the y rotation of the device rotation
  100832. rotation.toEulerAnglesToRef(this._workingVector);
  100833. this._workingVector.z = 0;
  100834. this._workingVector.x = 0;
  100835. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  100836. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  100837. // Rotate backwards ray by device rotation to cast at the ground behind the user
  100838. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  100839. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  100840. var ray = new BABYLON.Ray(position, this._workingVector);
  100841. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  100842. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  100843. this.teleportCamera(hit.pickedPoint);
  100844. }
  100845. gazer._teleportationBackRequestInitiated = true;
  100846. }
  100847. }
  100848. else {
  100849. gazer._teleportationBackRequestInitiated = false;
  100850. }
  100851. };
  100852. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  100853. var _this = this;
  100854. var controllerMesh = controller.webVRController.mesh;
  100855. if (controllerMesh) {
  100856. if (!controller._interactionsEnabled) {
  100857. this._enableInteractionOnController(controller);
  100858. }
  100859. controller._interactionsEnabled = true;
  100860. controller._teleportationEnabled = true;
  100861. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100862. controller._dpadPressed = false;
  100863. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  100864. controller._dpadPressed = stateObject.pressed;
  100865. if (!controller._dpadPressed) {
  100866. controller._rotationLeftAsked = false;
  100867. controller._rotationRightAsked = false;
  100868. controller._teleportationBackRequestInitiated = false;
  100869. }
  100870. });
  100871. }
  100872. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  100873. if (_this.teleportationEnabled) {
  100874. _this._checkTeleportBackwards(stateObject, controller);
  100875. _this._checkTeleportWithRay(stateObject, controller);
  100876. }
  100877. _this._checkRotate(stateObject, controller);
  100878. });
  100879. }
  100880. };
  100881. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  100882. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  100883. this._teleportationTarget.isPickable = false;
  100884. var length = 512;
  100885. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  100886. dynamicTexture.hasAlpha = true;
  100887. var context = dynamicTexture.getContext();
  100888. var centerX = length / 2;
  100889. var centerY = length / 2;
  100890. var radius = 200;
  100891. context.beginPath();
  100892. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  100893. context.fillStyle = this._teleportationFillColor;
  100894. context.fill();
  100895. context.lineWidth = 10;
  100896. context.strokeStyle = this._teleportationBorderColor;
  100897. context.stroke();
  100898. context.closePath();
  100899. dynamicTexture.update();
  100900. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  100901. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  100902. this._teleportationTarget.material = teleportationCircleMaterial;
  100903. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  100904. torus.isPickable = false;
  100905. torus.parent = this._teleportationTarget;
  100906. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  100907. var keys = [];
  100908. keys.push({
  100909. frame: 0,
  100910. value: 0
  100911. });
  100912. keys.push({
  100913. frame: 30,
  100914. value: 0.4
  100915. });
  100916. keys.push({
  100917. frame: 60,
  100918. value: 0
  100919. });
  100920. animationInnerCircle.setKeys(keys);
  100921. var easingFunction = new BABYLON.SineEase();
  100922. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  100923. animationInnerCircle.setEasingFunction(easingFunction);
  100924. torus.animations = [];
  100925. torus.animations.push(animationInnerCircle);
  100926. this._scene.beginAnimation(torus, 0, 60, true);
  100927. this._hideTeleportationTarget();
  100928. };
  100929. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  100930. this._teleportActive = true;
  100931. if (this._teleportationInitialized) {
  100932. this._teleportationTarget.isVisible = true;
  100933. if (this._isDefaultTeleportationTarget) {
  100934. this._teleportationTarget.getChildren()[0].isVisible = true;
  100935. }
  100936. }
  100937. };
  100938. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  100939. this._teleportActive = false;
  100940. if (this._teleportationInitialized) {
  100941. this._teleportationTarget.isVisible = false;
  100942. if (this._isDefaultTeleportationTarget) {
  100943. this._teleportationTarget.getChildren()[0].isVisible = false;
  100944. }
  100945. }
  100946. };
  100947. VRExperienceHelper.prototype._rotateCamera = function (right) {
  100948. var _this = this;
  100949. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100950. return;
  100951. }
  100952. if (right) {
  100953. this._rotationAngle++;
  100954. }
  100955. else {
  100956. this._rotationAngle--;
  100957. }
  100958. this.currentVRCamera.animations = [];
  100959. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  100960. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100961. var animationRotationKeys = [];
  100962. animationRotationKeys.push({
  100963. frame: 0,
  100964. value: this.currentVRCamera.rotationQuaternion
  100965. });
  100966. animationRotationKeys.push({
  100967. frame: 6,
  100968. value: target
  100969. });
  100970. animationRotation.setKeys(animationRotationKeys);
  100971. animationRotation.setEasingFunction(this._circleEase);
  100972. this.currentVRCamera.animations.push(animationRotation);
  100973. this._postProcessMove.animations = [];
  100974. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100975. var vignetteWeightKeys = [];
  100976. vignetteWeightKeys.push({
  100977. frame: 0,
  100978. value: 0
  100979. });
  100980. vignetteWeightKeys.push({
  100981. frame: 3,
  100982. value: 4
  100983. });
  100984. vignetteWeightKeys.push({
  100985. frame: 6,
  100986. value: 0
  100987. });
  100988. animationPP.setKeys(vignetteWeightKeys);
  100989. animationPP.setEasingFunction(this._circleEase);
  100990. this._postProcessMove.animations.push(animationPP);
  100991. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100992. var vignetteStretchKeys = [];
  100993. vignetteStretchKeys.push({
  100994. frame: 0,
  100995. value: 0
  100996. });
  100997. vignetteStretchKeys.push({
  100998. frame: 3,
  100999. value: 10
  101000. });
  101001. vignetteStretchKeys.push({
  101002. frame: 6,
  101003. value: 0
  101004. });
  101005. animationPP2.setKeys(vignetteStretchKeys);
  101006. animationPP2.setEasingFunction(this._circleEase);
  101007. this._postProcessMove.animations.push(animationPP2);
  101008. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101009. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101010. this._postProcessMove.samples = 4;
  101011. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101012. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101013. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101014. });
  101015. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101016. };
  101017. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101018. if (hit.pickedPoint) {
  101019. if (gazer._teleportationRequestInitiated) {
  101020. this._displayTeleportationTarget();
  101021. this._haloCenter.copyFrom(hit.pickedPoint);
  101022. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101023. }
  101024. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101025. if (pickNormal) {
  101026. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101027. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101028. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101029. }
  101030. this._teleportationTarget.position.y += 0.1;
  101031. }
  101032. };
  101033. /**
  101034. * Teleports the users feet to the desired location
  101035. * @param location The location where the user's feet should be placed
  101036. */
  101037. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101038. var _this = this;
  101039. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101040. return;
  101041. }
  101042. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101043. // offset of the headset from the anchor.
  101044. if (this.webVRCamera.leftCamera) {
  101045. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101046. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101047. location.subtractToRef(this._workingVector, this._workingVector);
  101048. }
  101049. else {
  101050. this._workingVector.copyFrom(location);
  101051. }
  101052. // Add height to account for user's height offset
  101053. if (this.isInVRMode) {
  101054. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101055. }
  101056. else {
  101057. this._workingVector.y += this._defaultHeight;
  101058. }
  101059. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101060. // Create animation from the camera's position to the new location
  101061. this.currentVRCamera.animations = [];
  101062. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101063. var animationCameraTeleportationKeys = [{
  101064. frame: 0,
  101065. value: this.currentVRCamera.position
  101066. },
  101067. {
  101068. frame: 11,
  101069. value: this._workingVector
  101070. }
  101071. ];
  101072. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101073. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101074. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101075. this._postProcessMove.animations = [];
  101076. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101077. var vignetteWeightKeys = [];
  101078. vignetteWeightKeys.push({
  101079. frame: 0,
  101080. value: 0
  101081. });
  101082. vignetteWeightKeys.push({
  101083. frame: 5,
  101084. value: 8
  101085. });
  101086. vignetteWeightKeys.push({
  101087. frame: 11,
  101088. value: 0
  101089. });
  101090. animationPP.setKeys(vignetteWeightKeys);
  101091. this._postProcessMove.animations.push(animationPP);
  101092. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101093. var vignetteStretchKeys = [];
  101094. vignetteStretchKeys.push({
  101095. frame: 0,
  101096. value: 0
  101097. });
  101098. vignetteStretchKeys.push({
  101099. frame: 5,
  101100. value: 10
  101101. });
  101102. vignetteStretchKeys.push({
  101103. frame: 11,
  101104. value: 0
  101105. });
  101106. animationPP2.setKeys(vignetteStretchKeys);
  101107. this._postProcessMove.animations.push(animationPP2);
  101108. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101109. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101110. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101111. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101112. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101113. });
  101114. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101115. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101116. });
  101117. this._hideTeleportationTarget();
  101118. };
  101119. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101120. if (normal) {
  101121. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101122. if (angle < Math.PI / 2) {
  101123. normal.scaleInPlace(-1);
  101124. }
  101125. }
  101126. return normal;
  101127. };
  101128. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  101129. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101130. return;
  101131. }
  101132. var ray = gazer._getForwardRay(this._rayLength);
  101133. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101134. if (hit) {
  101135. // Populate the contrllers mesh that can be used for drag/drop
  101136. if (gazer._laserPointer) {
  101137. hit.originMesh = gazer._laserPointer.parent;
  101138. }
  101139. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  101140. }
  101141. gazer._currentHit = hit;
  101142. // Moving the gazeTracker on the mesh face targetted
  101143. if (hit && hit.pickedPoint) {
  101144. if (this._displayGaze) {
  101145. var multiplier = 1;
  101146. gazer._gazeTracker.isVisible = true;
  101147. if (gazer._isActionableMesh) {
  101148. multiplier = 3;
  101149. }
  101150. if (this.updateGazeTrackerScale) {
  101151. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  101152. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  101153. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  101154. }
  101155. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  101156. // To avoid z-fighting
  101157. var deltaFighting = 0.002;
  101158. if (pickNormal) {
  101159. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101160. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101161. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  101162. }
  101163. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  101164. if (gazer._gazeTracker.position.x < 0) {
  101165. gazer._gazeTracker.position.x += deltaFighting;
  101166. }
  101167. else {
  101168. gazer._gazeTracker.position.x -= deltaFighting;
  101169. }
  101170. if (gazer._gazeTracker.position.y < 0) {
  101171. gazer._gazeTracker.position.y += deltaFighting;
  101172. }
  101173. else {
  101174. gazer._gazeTracker.position.y -= deltaFighting;
  101175. }
  101176. if (gazer._gazeTracker.position.z < 0) {
  101177. gazer._gazeTracker.position.z += deltaFighting;
  101178. }
  101179. else {
  101180. gazer._gazeTracker.position.z -= deltaFighting;
  101181. }
  101182. }
  101183. // Changing the size of the laser pointer based on the distance from the targetted point
  101184. gazer._updatePointerDistance(hit.distance);
  101185. }
  101186. else {
  101187. gazer._updatePointerDistance();
  101188. gazer._gazeTracker.isVisible = false;
  101189. }
  101190. if (hit && hit.pickedMesh) {
  101191. // The object selected is the floor, we're in a teleportation scenario
  101192. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  101193. // Moving the teleportation area to this targetted point
  101194. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  101195. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  101196. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101197. }
  101198. gazer._currentMeshSelected = null;
  101199. if (gazer._teleportationRequestInitiated) {
  101200. this._moveTeleportationSelectorTo(hit, gazer, ray);
  101201. }
  101202. return;
  101203. }
  101204. // If not, we're in a selection scenario
  101205. //this._teleportationAllowed = false;
  101206. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  101207. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  101208. this.onNewMeshPicked.notifyObservers(hit);
  101209. gazer._currentMeshSelected = hit.pickedMesh;
  101210. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  101211. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  101212. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  101213. gazer._isActionableMesh = true;
  101214. }
  101215. else {
  101216. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101217. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101218. gazer._isActionableMesh = false;
  101219. }
  101220. try {
  101221. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  101222. }
  101223. catch (err) {
  101224. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  101225. }
  101226. }
  101227. else {
  101228. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101229. gazer._currentMeshSelected = null;
  101230. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101231. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101232. }
  101233. }
  101234. }
  101235. else {
  101236. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  101237. gazer._currentMeshSelected = null;
  101238. //this._teleportationAllowed = false;
  101239. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101240. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  101241. }
  101242. };
  101243. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  101244. if (mesh) {
  101245. this.onSelectedMeshUnselected.notifyObservers(mesh);
  101246. }
  101247. };
  101248. /**
  101249. * Sets the color of the laser ray from the vr controllers.
  101250. * @param color new color for the ray.
  101251. */
  101252. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  101253. if (this._leftController) {
  101254. this._leftController._setLaserPointerColor(color);
  101255. }
  101256. if (this._rightController) {
  101257. this._rightController._setLaserPointerColor(color);
  101258. }
  101259. };
  101260. /**
  101261. * Sets the color of the ray from the vr headsets gaze.
  101262. * @param color new color for the ray.
  101263. */
  101264. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  101265. if (!this._cameraGazer._gazeTracker.material) {
  101266. return;
  101267. }
  101268. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  101269. if (this._leftController) {
  101270. this._leftController._gazeTracker.material.emissiveColor = color;
  101271. }
  101272. if (this._rightController) {
  101273. this._rightController._gazeTracker.material.emissiveColor = color;
  101274. }
  101275. };
  101276. /**
  101277. * Exits VR and disposes of the vr experience helper
  101278. */
  101279. VRExperienceHelper.prototype.dispose = function () {
  101280. if (this.isInVRMode) {
  101281. this.exitVR();
  101282. }
  101283. if (this._postProcessMove) {
  101284. this._postProcessMove.dispose();
  101285. }
  101286. if (this._webVRCamera) {
  101287. this._webVRCamera.dispose();
  101288. }
  101289. if (this._vrDeviceOrientationCamera) {
  101290. this._vrDeviceOrientationCamera.dispose();
  101291. }
  101292. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  101293. document.body.removeChild(this._btnVR);
  101294. }
  101295. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  101296. this._deviceOrientationCamera.dispose();
  101297. }
  101298. if (this._cameraGazer) {
  101299. this._cameraGazer.dispose();
  101300. }
  101301. if (this._leftController) {
  101302. this._leftController.dispose();
  101303. }
  101304. if (this._rightController) {
  101305. this._rightController.dispose();
  101306. }
  101307. if (this._teleportationTarget) {
  101308. this._teleportationTarget.dispose();
  101309. }
  101310. this._floorMeshesCollection = [];
  101311. document.removeEventListener("keydown", this._onKeyDown);
  101312. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101313. window.removeEventListener("resize", this._onResize);
  101314. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  101315. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  101316. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  101317. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  101318. document.onmsfullscreenchange = null;
  101319. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  101320. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  101321. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  101322. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101323. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  101324. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  101325. this._scene.unregisterBeforeRender(this.beforeRender);
  101326. };
  101327. /**
  101328. * Gets the name of the VRExperienceHelper class
  101329. * @returns "VRExperienceHelper"
  101330. */
  101331. VRExperienceHelper.prototype.getClassName = function () {
  101332. return "VRExperienceHelper";
  101333. };
  101334. return VRExperienceHelper;
  101335. }());
  101336. BABYLON.VRExperienceHelper = VRExperienceHelper;
  101337. })(BABYLON || (BABYLON = {}));
  101338. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  101339. // Mainly based on these 2 articles :
  101340. // 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
  101341. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  101342. var BABYLON;
  101343. (function (BABYLON) {
  101344. /**
  101345. * Defines the potential axis of a Joystick
  101346. */
  101347. var JoystickAxis;
  101348. (function (JoystickAxis) {
  101349. /** X axis */
  101350. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  101351. /** Y axis */
  101352. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  101353. /** Z axis */
  101354. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  101355. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  101356. /**
  101357. * Class used to define virtual joystick (used in touch mode)
  101358. */
  101359. var VirtualJoystick = /** @class */ (function () {
  101360. /**
  101361. * Creates a new virtual joystick
  101362. * @param leftJoystick defines that the joystick is for left hand (false by default)
  101363. */
  101364. function VirtualJoystick(leftJoystick) {
  101365. var _this = this;
  101366. if (leftJoystick) {
  101367. this._leftJoystick = true;
  101368. }
  101369. else {
  101370. this._leftJoystick = false;
  101371. }
  101372. VirtualJoystick._globalJoystickIndex++;
  101373. // By default left & right arrow keys are moving the X
  101374. // and up & down keys are moving the Y
  101375. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101376. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101377. this.reverseLeftRight = false;
  101378. this.reverseUpDown = false;
  101379. // collections of pointers
  101380. this._touches = new BABYLON.StringDictionary();
  101381. this.deltaPosition = BABYLON.Vector3.Zero();
  101382. this._joystickSensibility = 25;
  101383. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101384. this._onResize = function (evt) {
  101385. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101386. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101387. if (VirtualJoystick.vjCanvas) {
  101388. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  101389. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  101390. }
  101391. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  101392. };
  101393. // injecting a canvas element on top of the canvas 3D game
  101394. if (!VirtualJoystick.vjCanvas) {
  101395. window.addEventListener("resize", this._onResize, false);
  101396. VirtualJoystick.vjCanvas = document.createElement("canvas");
  101397. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101398. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101399. VirtualJoystick.vjCanvas.width = window.innerWidth;
  101400. VirtualJoystick.vjCanvas.height = window.innerHeight;
  101401. VirtualJoystick.vjCanvas.style.width = "100%";
  101402. VirtualJoystick.vjCanvas.style.height = "100%";
  101403. VirtualJoystick.vjCanvas.style.position = "absolute";
  101404. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  101405. VirtualJoystick.vjCanvas.style.top = "0px";
  101406. VirtualJoystick.vjCanvas.style.left = "0px";
  101407. VirtualJoystick.vjCanvas.style.zIndex = "5";
  101408. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  101409. // Support for jQuery PEP polyfill
  101410. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  101411. var context = VirtualJoystick.vjCanvas.getContext('2d');
  101412. if (!context) {
  101413. throw new Error("Unable to create canvas for virtual joystick");
  101414. }
  101415. VirtualJoystick.vjCanvasContext = context;
  101416. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  101417. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101418. document.body.appendChild(VirtualJoystick.vjCanvas);
  101419. }
  101420. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  101421. this.pressed = false;
  101422. // default joystick color
  101423. this._joystickColor = "cyan";
  101424. this._joystickPointerID = -1;
  101425. // current joystick position
  101426. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  101427. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  101428. // origin joystick position
  101429. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  101430. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  101431. this._onPointerDownHandlerRef = function (evt) {
  101432. _this._onPointerDown(evt);
  101433. };
  101434. this._onPointerMoveHandlerRef = function (evt) {
  101435. _this._onPointerMove(evt);
  101436. };
  101437. this._onPointerUpHandlerRef = function (evt) {
  101438. _this._onPointerUp(evt);
  101439. };
  101440. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  101441. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  101442. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  101443. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  101444. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  101445. evt.preventDefault(); // Disables system menu
  101446. }, false);
  101447. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101448. }
  101449. /**
  101450. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  101451. * @param newJoystickSensibility defines the new sensibility
  101452. */
  101453. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  101454. this._joystickSensibility = newJoystickSensibility;
  101455. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101456. };
  101457. VirtualJoystick.prototype._onPointerDown = function (e) {
  101458. var positionOnScreenCondition;
  101459. e.preventDefault();
  101460. if (this._leftJoystick === true) {
  101461. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  101462. }
  101463. else {
  101464. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  101465. }
  101466. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  101467. // First contact will be dedicated to the virtual joystick
  101468. this._joystickPointerID = e.pointerId;
  101469. this._joystickPointerStartPos.x = e.clientX;
  101470. this._joystickPointerStartPos.y = e.clientY;
  101471. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  101472. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  101473. this._deltaJoystickVector.x = 0;
  101474. this._deltaJoystickVector.y = 0;
  101475. this.pressed = true;
  101476. this._touches.add(e.pointerId.toString(), e);
  101477. }
  101478. else {
  101479. // You can only trigger the action buttons with a joystick declared
  101480. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  101481. this._action();
  101482. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  101483. }
  101484. }
  101485. };
  101486. VirtualJoystick.prototype._onPointerMove = function (e) {
  101487. // If the current pointer is the one associated to the joystick (first touch contact)
  101488. if (this._joystickPointerID == e.pointerId) {
  101489. this._joystickPointerPos.x = e.clientX;
  101490. this._joystickPointerPos.y = e.clientY;
  101491. this._deltaJoystickVector = this._joystickPointerPos.clone();
  101492. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  101493. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  101494. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  101495. switch (this._axisTargetedByLeftAndRight) {
  101496. case JoystickAxis.X:
  101497. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  101498. break;
  101499. case JoystickAxis.Y:
  101500. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  101501. break;
  101502. case JoystickAxis.Z:
  101503. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  101504. break;
  101505. }
  101506. var directionUpDown = this.reverseUpDown ? 1 : -1;
  101507. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  101508. switch (this._axisTargetedByUpAndDown) {
  101509. case JoystickAxis.X:
  101510. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  101511. break;
  101512. case JoystickAxis.Y:
  101513. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  101514. break;
  101515. case JoystickAxis.Z:
  101516. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  101517. break;
  101518. }
  101519. }
  101520. else {
  101521. var data = this._touches.get(e.pointerId.toString());
  101522. if (data) {
  101523. data.x = e.clientX;
  101524. data.y = e.clientY;
  101525. }
  101526. }
  101527. };
  101528. VirtualJoystick.prototype._onPointerUp = function (e) {
  101529. if (this._joystickPointerID == e.pointerId) {
  101530. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  101531. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  101532. this._joystickPointerID = -1;
  101533. this.pressed = false;
  101534. }
  101535. else {
  101536. var touch = this._touches.get(e.pointerId.toString());
  101537. if (touch) {
  101538. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101539. }
  101540. }
  101541. this._deltaJoystickVector.x = 0;
  101542. this._deltaJoystickVector.y = 0;
  101543. this._touches.remove(e.pointerId.toString());
  101544. };
  101545. /**
  101546. * Change the color of the virtual joystick
  101547. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  101548. */
  101549. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  101550. this._joystickColor = newColor;
  101551. };
  101552. /**
  101553. * Defines a callback to call when the joystick is touched
  101554. * @param action defines the callback
  101555. */
  101556. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  101557. this._action = action;
  101558. };
  101559. /**
  101560. * Defines which axis you'd like to control for left & right
  101561. * @param axis defines the axis to use
  101562. */
  101563. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  101564. switch (axis) {
  101565. case JoystickAxis.X:
  101566. case JoystickAxis.Y:
  101567. case JoystickAxis.Z:
  101568. this._axisTargetedByLeftAndRight = axis;
  101569. break;
  101570. default:
  101571. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101572. break;
  101573. }
  101574. };
  101575. /**
  101576. * Defines which axis you'd like to control for up & down
  101577. * @param axis defines the axis to use
  101578. */
  101579. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  101580. switch (axis) {
  101581. case JoystickAxis.X:
  101582. case JoystickAxis.Y:
  101583. case JoystickAxis.Z:
  101584. this._axisTargetedByUpAndDown = axis;
  101585. break;
  101586. default:
  101587. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101588. break;
  101589. }
  101590. };
  101591. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  101592. var _this = this;
  101593. if (this.pressed) {
  101594. this._touches.forEach(function (key, touch) {
  101595. if (touch.pointerId === _this._joystickPointerID) {
  101596. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  101597. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  101598. VirtualJoystick.vjCanvasContext.beginPath();
  101599. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101600. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101601. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  101602. VirtualJoystick.vjCanvasContext.stroke();
  101603. VirtualJoystick.vjCanvasContext.closePath();
  101604. VirtualJoystick.vjCanvasContext.beginPath();
  101605. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101606. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101607. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  101608. VirtualJoystick.vjCanvasContext.stroke();
  101609. VirtualJoystick.vjCanvasContext.closePath();
  101610. VirtualJoystick.vjCanvasContext.beginPath();
  101611. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101612. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  101613. VirtualJoystick.vjCanvasContext.stroke();
  101614. VirtualJoystick.vjCanvasContext.closePath();
  101615. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  101616. }
  101617. else {
  101618. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101619. VirtualJoystick.vjCanvasContext.beginPath();
  101620. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  101621. VirtualJoystick.vjCanvasContext.beginPath();
  101622. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  101623. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101624. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  101625. VirtualJoystick.vjCanvasContext.stroke();
  101626. VirtualJoystick.vjCanvasContext.closePath();
  101627. touch.prevX = touch.x;
  101628. touch.prevY = touch.y;
  101629. }
  101630. ;
  101631. });
  101632. }
  101633. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101634. };
  101635. /**
  101636. * Release internal HTML canvas
  101637. */
  101638. VirtualJoystick.prototype.releaseCanvas = function () {
  101639. if (VirtualJoystick.vjCanvas) {
  101640. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  101641. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  101642. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  101643. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  101644. window.removeEventListener("resize", this._onResize);
  101645. document.body.removeChild(VirtualJoystick.vjCanvas);
  101646. VirtualJoystick.vjCanvas = null;
  101647. }
  101648. };
  101649. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  101650. VirtualJoystick._globalJoystickIndex = 0;
  101651. return VirtualJoystick;
  101652. }());
  101653. BABYLON.VirtualJoystick = VirtualJoystick;
  101654. })(BABYLON || (BABYLON = {}));
  101655. //# sourceMappingURL=babylon.virtualJoystick.js.map
  101656. var BABYLON;
  101657. (function (BABYLON) {
  101658. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  101659. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  101660. });
  101661. /**
  101662. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  101663. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101664. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101665. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101666. */
  101667. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  101668. __extends(VirtualJoysticksCamera, _super);
  101669. /**
  101670. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  101671. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101672. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101673. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101674. * @param name Define the name of the camera in the scene
  101675. * @param position Define the start position of the camera in the scene
  101676. * @param scene Define the scene the camera belongs to
  101677. */
  101678. function VirtualJoysticksCamera(name, position, scene) {
  101679. var _this = _super.call(this, name, position, scene) || this;
  101680. _this.inputs.addVirtualJoystick();
  101681. return _this;
  101682. }
  101683. /**
  101684. * Gets the current object class name.
  101685. * @return the class name
  101686. */
  101687. VirtualJoysticksCamera.prototype.getClassName = function () {
  101688. return "VirtualJoysticksCamera";
  101689. };
  101690. return VirtualJoysticksCamera;
  101691. }(BABYLON.FreeCamera));
  101692. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  101693. })(BABYLON || (BABYLON = {}));
  101694. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  101695. var BABYLON;
  101696. (function (BABYLON) {
  101697. /**
  101698. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  101699. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101700. */
  101701. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  101702. function FreeCameraVirtualJoystickInput() {
  101703. }
  101704. /**
  101705. * Gets the left stick of the virtual joystick.
  101706. * @returns The virtual Joystick
  101707. */
  101708. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  101709. return this._leftjoystick;
  101710. };
  101711. /**
  101712. * Gets the right stick of the virtual joystick.
  101713. * @returns The virtual Joystick
  101714. */
  101715. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  101716. return this._rightjoystick;
  101717. };
  101718. /**
  101719. * Update the current camera state depending on the inputs that have been used this frame.
  101720. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101721. */
  101722. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  101723. if (this._leftjoystick) {
  101724. var camera = this.camera;
  101725. var speed = camera._computeLocalCameraSpeed() * 50;
  101726. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  101727. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  101728. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  101729. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  101730. if (!this._leftjoystick.pressed) {
  101731. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  101732. }
  101733. if (!this._rightjoystick.pressed) {
  101734. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  101735. }
  101736. }
  101737. };
  101738. /**
  101739. * Attach the input controls to a specific dom element to get the input from.
  101740. * @param element Defines the element the controls should be listened from
  101741. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101742. */
  101743. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  101744. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  101745. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  101746. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  101747. this._leftjoystick.setJoystickSensibility(0.15);
  101748. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  101749. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  101750. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  101751. this._rightjoystick.reverseUpDown = true;
  101752. this._rightjoystick.setJoystickSensibility(0.05);
  101753. this._rightjoystick.setJoystickColor("yellow");
  101754. };
  101755. /**
  101756. * Detach the current controls from the specified dom element.
  101757. * @param element Defines the element to stop listening the inputs from
  101758. */
  101759. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  101760. this._leftjoystick.releaseCanvas();
  101761. this._rightjoystick.releaseCanvas();
  101762. };
  101763. /**
  101764. * Gets the class name of the current intput.
  101765. * @returns the class name
  101766. */
  101767. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  101768. return "FreeCameraVirtualJoystickInput";
  101769. };
  101770. /**
  101771. * Get the friendly name associated with the input class.
  101772. * @returns the input friendly name
  101773. */
  101774. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  101775. return "virtualJoystick";
  101776. };
  101777. return FreeCameraVirtualJoystickInput;
  101778. }());
  101779. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  101780. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  101781. })(BABYLON || (BABYLON = {}));
  101782. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  101783. var BABYLON;
  101784. (function (BABYLON) {
  101785. var SimplificationSettings = /** @class */ (function () {
  101786. function SimplificationSettings(quality, distance, optimizeMesh) {
  101787. this.quality = quality;
  101788. this.distance = distance;
  101789. this.optimizeMesh = optimizeMesh;
  101790. }
  101791. return SimplificationSettings;
  101792. }());
  101793. BABYLON.SimplificationSettings = SimplificationSettings;
  101794. var SimplificationQueue = /** @class */ (function () {
  101795. function SimplificationQueue() {
  101796. this.running = false;
  101797. this._simplificationArray = [];
  101798. }
  101799. SimplificationQueue.prototype.addTask = function (task) {
  101800. this._simplificationArray.push(task);
  101801. };
  101802. SimplificationQueue.prototype.executeNext = function () {
  101803. var task = this._simplificationArray.pop();
  101804. if (task) {
  101805. this.running = true;
  101806. this.runSimplification(task);
  101807. }
  101808. else {
  101809. this.running = false;
  101810. }
  101811. };
  101812. SimplificationQueue.prototype.runSimplification = function (task) {
  101813. var _this = this;
  101814. if (task.parallelProcessing) {
  101815. //parallel simplifier
  101816. task.settings.forEach(function (setting) {
  101817. var simplifier = _this.getSimplifier(task);
  101818. simplifier.simplify(setting, function (newMesh) {
  101819. task.mesh.addLODLevel(setting.distance, newMesh);
  101820. newMesh.isVisible = true;
  101821. //check if it is the last
  101822. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  101823. //all done, run the success callback.
  101824. task.successCallback();
  101825. }
  101826. _this.executeNext();
  101827. });
  101828. });
  101829. }
  101830. else {
  101831. //single simplifier.
  101832. var simplifier = this.getSimplifier(task);
  101833. var runDecimation = function (setting, callback) {
  101834. simplifier.simplify(setting, function (newMesh) {
  101835. task.mesh.addLODLevel(setting.distance, newMesh);
  101836. newMesh.isVisible = true;
  101837. //run the next quality level
  101838. callback();
  101839. });
  101840. };
  101841. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  101842. runDecimation(task.settings[loop.index], function () {
  101843. loop.executeNext();
  101844. });
  101845. }, function () {
  101846. //execution ended, run the success callback.
  101847. if (task.successCallback) {
  101848. task.successCallback();
  101849. }
  101850. _this.executeNext();
  101851. });
  101852. }
  101853. };
  101854. SimplificationQueue.prototype.getSimplifier = function (task) {
  101855. switch (task.simplificationType) {
  101856. case SimplificationType.QUADRATIC:
  101857. default:
  101858. return new QuadraticErrorSimplification(task.mesh);
  101859. }
  101860. };
  101861. return SimplificationQueue;
  101862. }());
  101863. BABYLON.SimplificationQueue = SimplificationQueue;
  101864. /**
  101865. * The implemented types of simplification
  101866. * At the moment only Quadratic Error Decimation is implemented
  101867. */
  101868. var SimplificationType;
  101869. (function (SimplificationType) {
  101870. /** Quadratic error decimation */
  101871. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  101872. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  101873. var DecimationTriangle = /** @class */ (function () {
  101874. function DecimationTriangle(vertices) {
  101875. this.vertices = vertices;
  101876. this.error = new Array(4);
  101877. this.deleted = false;
  101878. this.isDirty = false;
  101879. this.deletePending = false;
  101880. this.borderFactor = 0;
  101881. }
  101882. return DecimationTriangle;
  101883. }());
  101884. BABYLON.DecimationTriangle = DecimationTriangle;
  101885. var DecimationVertex = /** @class */ (function () {
  101886. function DecimationVertex(position, id) {
  101887. this.position = position;
  101888. this.id = id;
  101889. this.isBorder = true;
  101890. this.q = new QuadraticMatrix();
  101891. this.triangleCount = 0;
  101892. this.triangleStart = 0;
  101893. this.originalOffsets = [];
  101894. }
  101895. DecimationVertex.prototype.updatePosition = function (newPosition) {
  101896. this.position.copyFrom(newPosition);
  101897. };
  101898. return DecimationVertex;
  101899. }());
  101900. BABYLON.DecimationVertex = DecimationVertex;
  101901. var QuadraticMatrix = /** @class */ (function () {
  101902. function QuadraticMatrix(data) {
  101903. this.data = new Array(10);
  101904. for (var i = 0; i < 10; ++i) {
  101905. if (data && data[i]) {
  101906. this.data[i] = data[i];
  101907. }
  101908. else {
  101909. this.data[i] = 0;
  101910. }
  101911. }
  101912. }
  101913. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  101914. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  101915. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  101916. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  101917. return det;
  101918. };
  101919. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  101920. for (var i = 0; i < 10; ++i) {
  101921. this.data[i] += matrix.data[i];
  101922. }
  101923. };
  101924. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  101925. for (var i = 0; i < 10; ++i) {
  101926. this.data[i] += data[i];
  101927. }
  101928. };
  101929. QuadraticMatrix.prototype.add = function (matrix) {
  101930. var m = new QuadraticMatrix();
  101931. for (var i = 0; i < 10; ++i) {
  101932. m.data[i] = this.data[i] + matrix.data[i];
  101933. }
  101934. return m;
  101935. };
  101936. QuadraticMatrix.FromData = function (a, b, c, d) {
  101937. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  101938. };
  101939. //returning an array to avoid garbage collection
  101940. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  101941. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  101942. };
  101943. return QuadraticMatrix;
  101944. }());
  101945. BABYLON.QuadraticMatrix = QuadraticMatrix;
  101946. var Reference = /** @class */ (function () {
  101947. function Reference(vertexId, triangleId) {
  101948. this.vertexId = vertexId;
  101949. this.triangleId = triangleId;
  101950. }
  101951. return Reference;
  101952. }());
  101953. BABYLON.Reference = Reference;
  101954. /**
  101955. * An implementation of the Quadratic Error simplification algorithm.
  101956. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  101957. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  101958. * @author RaananW
  101959. */
  101960. var QuadraticErrorSimplification = /** @class */ (function () {
  101961. function QuadraticErrorSimplification(_mesh) {
  101962. this._mesh = _mesh;
  101963. this.syncIterations = 5000;
  101964. this.aggressiveness = 7;
  101965. this.decimationIterations = 100;
  101966. this.boundingBoxEpsilon = BABYLON.Epsilon;
  101967. }
  101968. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  101969. var _this = this;
  101970. this.initDecimatedMesh();
  101971. //iterating through the submeshes array, one after the other.
  101972. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  101973. _this.initWithMesh(loop.index, function () {
  101974. _this.runDecimation(settings, loop.index, function () {
  101975. loop.executeNext();
  101976. });
  101977. }, settings.optimizeMesh);
  101978. }, function () {
  101979. setTimeout(function () {
  101980. successCallback(_this._reconstructedMesh);
  101981. }, 0);
  101982. });
  101983. };
  101984. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  101985. var _this = this;
  101986. var targetCount = ~~(this.triangles.length * settings.quality);
  101987. var deletedTriangles = 0;
  101988. var triangleCount = this.triangles.length;
  101989. var iterationFunction = function (iteration, callback) {
  101990. setTimeout(function () {
  101991. if (iteration % 5 === 0) {
  101992. _this.updateMesh(iteration === 0);
  101993. }
  101994. for (var i = 0; i < _this.triangles.length; ++i) {
  101995. _this.triangles[i].isDirty = false;
  101996. }
  101997. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  101998. var trianglesIterator = function (i) {
  101999. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102000. var t = _this.triangles[tIdx];
  102001. if (!t)
  102002. return;
  102003. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102004. return;
  102005. }
  102006. for (var j = 0; j < 3; ++j) {
  102007. if (t.error[j] < threshold) {
  102008. var deleted0 = [];
  102009. var deleted1 = [];
  102010. var v0 = t.vertices[j];
  102011. var v1 = t.vertices[(j + 1) % 3];
  102012. if (v0.isBorder || v1.isBorder)
  102013. continue;
  102014. var p = BABYLON.Vector3.Zero();
  102015. var n = BABYLON.Vector3.Zero();
  102016. var uv = BABYLON.Vector2.Zero();
  102017. var color = new BABYLON.Color4(0, 0, 0, 1);
  102018. _this.calculateError(v0, v1, p, n, uv, color);
  102019. var delTr = new Array();
  102020. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102021. continue;
  102022. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102023. continue;
  102024. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102025. continue;
  102026. var uniqueArray = new Array();
  102027. delTr.forEach(function (deletedT) {
  102028. if (uniqueArray.indexOf(deletedT) === -1) {
  102029. deletedT.deletePending = true;
  102030. uniqueArray.push(deletedT);
  102031. }
  102032. });
  102033. if (uniqueArray.length % 2 !== 0) {
  102034. continue;
  102035. }
  102036. v0.q = v1.q.add(v0.q);
  102037. v0.updatePosition(p);
  102038. var tStart = _this.references.length;
  102039. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102040. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102041. var tCount = _this.references.length - tStart;
  102042. if (tCount <= v0.triangleCount) {
  102043. if (tCount) {
  102044. for (var c = 0; c < tCount; c++) {
  102045. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102046. }
  102047. }
  102048. }
  102049. else {
  102050. v0.triangleStart = tStart;
  102051. }
  102052. v0.triangleCount = tCount;
  102053. break;
  102054. }
  102055. }
  102056. };
  102057. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102058. }, 0);
  102059. };
  102060. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102061. if (triangleCount - deletedTriangles <= targetCount)
  102062. loop.breakLoop();
  102063. else {
  102064. iterationFunction(loop.index, function () {
  102065. loop.executeNext();
  102066. });
  102067. }
  102068. }, function () {
  102069. setTimeout(function () {
  102070. //reconstruct this part of the mesh
  102071. _this.reconstructMesh(submeshIndex);
  102072. successCallback();
  102073. }, 0);
  102074. });
  102075. };
  102076. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102077. var _this = this;
  102078. this.vertices = [];
  102079. this.triangles = [];
  102080. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102081. var indices = this._mesh.getIndices();
  102082. var submesh = this._mesh.subMeshes[submeshIndex];
  102083. var findInVertices = function (positionToSearch) {
  102084. if (optimizeMesh) {
  102085. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102086. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102087. return _this.vertices[ii];
  102088. }
  102089. }
  102090. }
  102091. return null;
  102092. };
  102093. var vertexReferences = [];
  102094. var vertexInit = function (i) {
  102095. if (!positionData) {
  102096. return;
  102097. }
  102098. var offset = i + submesh.verticesStart;
  102099. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102100. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102101. vertex.originalOffsets.push(offset);
  102102. if (vertex.id === _this.vertices.length) {
  102103. _this.vertices.push(vertex);
  102104. }
  102105. vertexReferences.push(vertex.id);
  102106. };
  102107. //var totalVertices = mesh.getTotalVertices();
  102108. var totalVertices = submesh.verticesCount;
  102109. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102110. var indicesInit = function (i) {
  102111. if (!indices) {
  102112. return;
  102113. }
  102114. var offset = (submesh.indexStart / 3) + i;
  102115. var pos = (offset * 3);
  102116. var i0 = indices[pos + 0];
  102117. var i1 = indices[pos + 1];
  102118. var i2 = indices[pos + 2];
  102119. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102120. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102121. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102122. var triangle = new DecimationTriangle([v0, v1, v2]);
  102123. triangle.originalOffset = pos;
  102124. _this.triangles.push(triangle);
  102125. };
  102126. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  102127. _this.init(callback);
  102128. });
  102129. });
  102130. };
  102131. QuadraticErrorSimplification.prototype.init = function (callback) {
  102132. var _this = this;
  102133. var triangleInit1 = function (i) {
  102134. var t = _this.triangles[i];
  102135. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  102136. for (var j = 0; j < 3; j++) {
  102137. 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))));
  102138. }
  102139. };
  102140. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  102141. var triangleInit2 = function (i) {
  102142. var t = _this.triangles[i];
  102143. for (var j = 0; j < 3; ++j) {
  102144. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  102145. }
  102146. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102147. };
  102148. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  102149. callback();
  102150. });
  102151. });
  102152. };
  102153. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  102154. var newTriangles = [];
  102155. var i;
  102156. for (i = 0; i < this.vertices.length; ++i) {
  102157. this.vertices[i].triangleCount = 0;
  102158. }
  102159. var t;
  102160. var j;
  102161. for (i = 0; i < this.triangles.length; ++i) {
  102162. if (!this.triangles[i].deleted) {
  102163. t = this.triangles[i];
  102164. for (j = 0; j < 3; ++j) {
  102165. t.vertices[j].triangleCount = 1;
  102166. }
  102167. newTriangles.push(t);
  102168. }
  102169. }
  102170. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  102171. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  102172. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  102173. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  102174. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  102175. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  102176. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  102177. var vertexCount = 0;
  102178. for (i = 0; i < this.vertices.length; ++i) {
  102179. var vertex = this.vertices[i];
  102180. vertex.id = vertexCount;
  102181. if (vertex.triangleCount) {
  102182. vertex.originalOffsets.forEach(function (originalOffset) {
  102183. if (!normalData) {
  102184. return;
  102185. }
  102186. newPositionData.push(vertex.position.x);
  102187. newPositionData.push(vertex.position.y);
  102188. newPositionData.push(vertex.position.z);
  102189. newNormalData.push(normalData[originalOffset * 3]);
  102190. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  102191. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  102192. if (uvs && uvs.length) {
  102193. newUVsData.push(uvs[(originalOffset * 2)]);
  102194. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  102195. }
  102196. else if (colorsData && colorsData.length) {
  102197. newColorsData.push(colorsData[(originalOffset * 4)]);
  102198. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  102199. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  102200. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  102201. }
  102202. ++vertexCount;
  102203. });
  102204. }
  102205. }
  102206. var startingIndex = this._reconstructedMesh.getTotalIndices();
  102207. var startingVertex = this._reconstructedMesh.getTotalVertices();
  102208. var submeshesArray = this._reconstructedMesh.subMeshes;
  102209. this._reconstructedMesh.subMeshes = [];
  102210. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  102211. var originalIndices = this._mesh.getIndices();
  102212. for (i = 0; i < newTriangles.length; ++i) {
  102213. t = newTriangles[i]; //now get the new referencing point for each vertex
  102214. [0, 1, 2].forEach(function (idx) {
  102215. var id = originalIndices[t.originalOffset + idx];
  102216. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  102217. if (offset < 0)
  102218. offset = 0;
  102219. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  102220. });
  102221. }
  102222. //overwriting the old vertex buffers and indices.
  102223. this._reconstructedMesh.setIndices(newIndicesArray);
  102224. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  102225. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  102226. if (newUVsData.length > 0)
  102227. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  102228. if (newColorsData.length > 0)
  102229. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  102230. //create submesh
  102231. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  102232. if (submeshIndex > 0) {
  102233. this._reconstructedMesh.subMeshes = [];
  102234. submeshesArray.forEach(function (submesh) {
  102235. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  102236. });
  102237. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  102238. }
  102239. };
  102240. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  102241. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  102242. this._reconstructedMesh.material = this._mesh.material;
  102243. this._reconstructedMesh.parent = this._mesh.parent;
  102244. this._reconstructedMesh.isVisible = false;
  102245. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  102246. };
  102247. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  102248. for (var i = 0; i < vertex1.triangleCount; ++i) {
  102249. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  102250. if (t.deleted)
  102251. continue;
  102252. var s = this.references[vertex1.triangleStart + i].vertexId;
  102253. var v1 = t.vertices[(s + 1) % 3];
  102254. var v2 = t.vertices[(s + 2) % 3];
  102255. if ((v1 === vertex2 || v2 === vertex2)) {
  102256. deletedArray[i] = true;
  102257. delTr.push(t);
  102258. continue;
  102259. }
  102260. var d1 = v1.position.subtract(point);
  102261. d1 = d1.normalize();
  102262. var d2 = v2.position.subtract(point);
  102263. d2 = d2.normalize();
  102264. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  102265. return true;
  102266. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  102267. deletedArray[i] = false;
  102268. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  102269. return true;
  102270. }
  102271. return false;
  102272. };
  102273. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  102274. var newDeleted = deletedTriangles;
  102275. for (var i = 0; i < vertex.triangleCount; ++i) {
  102276. var ref = this.references[vertex.triangleStart + i];
  102277. var t = this.triangles[ref.triangleId];
  102278. if (t.deleted)
  102279. continue;
  102280. if (deletedArray[i] && t.deletePending) {
  102281. t.deleted = true;
  102282. newDeleted++;
  102283. continue;
  102284. }
  102285. t.vertices[ref.vertexId] = origVertex;
  102286. t.isDirty = true;
  102287. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  102288. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  102289. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  102290. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102291. this.references.push(ref);
  102292. }
  102293. return newDeleted;
  102294. };
  102295. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  102296. for (var i = 0; i < this.vertices.length; ++i) {
  102297. var vCount = [];
  102298. var vId = [];
  102299. var v = this.vertices[i];
  102300. var j;
  102301. for (j = 0; j < v.triangleCount; ++j) {
  102302. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  102303. for (var ii = 0; ii < 3; ii++) {
  102304. var ofs = 0;
  102305. var vv = triangle.vertices[ii];
  102306. while (ofs < vCount.length) {
  102307. if (vId[ofs] === vv.id)
  102308. break;
  102309. ++ofs;
  102310. }
  102311. if (ofs === vCount.length) {
  102312. vCount.push(1);
  102313. vId.push(vv.id);
  102314. }
  102315. else {
  102316. vCount[ofs]++;
  102317. }
  102318. }
  102319. }
  102320. for (j = 0; j < vCount.length; ++j) {
  102321. if (vCount[j] === 1) {
  102322. this.vertices[vId[j]].isBorder = true;
  102323. }
  102324. else {
  102325. this.vertices[vId[j]].isBorder = false;
  102326. }
  102327. }
  102328. }
  102329. };
  102330. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  102331. if (identifyBorders === void 0) { identifyBorders = false; }
  102332. var i;
  102333. if (!identifyBorders) {
  102334. var newTrianglesVector = [];
  102335. for (i = 0; i < this.triangles.length; ++i) {
  102336. if (!this.triangles[i].deleted) {
  102337. newTrianglesVector.push(this.triangles[i]);
  102338. }
  102339. }
  102340. this.triangles = newTrianglesVector;
  102341. }
  102342. for (i = 0; i < this.vertices.length; ++i) {
  102343. this.vertices[i].triangleCount = 0;
  102344. this.vertices[i].triangleStart = 0;
  102345. }
  102346. var t;
  102347. var j;
  102348. var v;
  102349. for (i = 0; i < this.triangles.length; ++i) {
  102350. t = this.triangles[i];
  102351. for (j = 0; j < 3; ++j) {
  102352. v = t.vertices[j];
  102353. v.triangleCount++;
  102354. }
  102355. }
  102356. var tStart = 0;
  102357. for (i = 0; i < this.vertices.length; ++i) {
  102358. this.vertices[i].triangleStart = tStart;
  102359. tStart += this.vertices[i].triangleCount;
  102360. this.vertices[i].triangleCount = 0;
  102361. }
  102362. var newReferences = new Array(this.triangles.length * 3);
  102363. for (i = 0; i < this.triangles.length; ++i) {
  102364. t = this.triangles[i];
  102365. for (j = 0; j < 3; ++j) {
  102366. v = t.vertices[j];
  102367. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  102368. v.triangleCount++;
  102369. }
  102370. }
  102371. this.references = newReferences;
  102372. if (identifyBorders) {
  102373. this.identifyBorder();
  102374. }
  102375. };
  102376. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  102377. var x = point.x;
  102378. var y = point.y;
  102379. var z = point.z;
  102380. 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
  102381. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  102382. };
  102383. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  102384. var q = vertex1.q.add(vertex2.q);
  102385. var border = vertex1.isBorder && vertex2.isBorder;
  102386. var error = 0;
  102387. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  102388. if (qDet !== 0 && !border) {
  102389. if (!pointResult) {
  102390. pointResult = BABYLON.Vector3.Zero();
  102391. }
  102392. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  102393. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  102394. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  102395. error = this.vertexError(q, pointResult);
  102396. }
  102397. else {
  102398. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  102399. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  102400. var error1 = this.vertexError(q, vertex1.position);
  102401. var error2 = this.vertexError(q, vertex2.position);
  102402. var error3 = this.vertexError(q, p3);
  102403. error = Math.min(error1, error2, error3);
  102404. if (error === error1) {
  102405. if (pointResult) {
  102406. pointResult.copyFrom(vertex1.position);
  102407. }
  102408. }
  102409. else if (error === error2) {
  102410. if (pointResult) {
  102411. pointResult.copyFrom(vertex2.position);
  102412. }
  102413. }
  102414. else {
  102415. if (pointResult) {
  102416. pointResult.copyFrom(p3);
  102417. }
  102418. }
  102419. }
  102420. return error;
  102421. };
  102422. return QuadraticErrorSimplification;
  102423. }());
  102424. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  102425. })(BABYLON || (BABYLON = {}));
  102426. //# sourceMappingURL=babylon.meshSimplification.js.map
  102427. var BABYLON;
  102428. (function (BABYLON) {
  102429. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  102430. get: function () {
  102431. if (!this._simplificationQueue) {
  102432. this._simplificationQueue = new BABYLON.SimplificationQueue();
  102433. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  102434. if (!component) {
  102435. component = new SimplicationQueueSceneComponent(this);
  102436. this._addComponent(component);
  102437. }
  102438. }
  102439. return this._simplificationQueue;
  102440. },
  102441. set: function (value) {
  102442. this._simplificationQueue = value;
  102443. },
  102444. enumerable: true,
  102445. configurable: true
  102446. });
  102447. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  102448. if (parallelProcessing === void 0) { parallelProcessing = true; }
  102449. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  102450. this.getScene().simplificationQueue.addTask({
  102451. settings: settings,
  102452. parallelProcessing: parallelProcessing,
  102453. mesh: this,
  102454. simplificationType: simplificationType,
  102455. successCallback: successCallback
  102456. });
  102457. return this;
  102458. };
  102459. /**
  102460. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  102461. * created in a scene
  102462. */
  102463. var SimplicationQueueSceneComponent = /** @class */ (function () {
  102464. /**
  102465. * Creates a new instance of the component for the given scene
  102466. * @param scene Defines the scene to register the component in
  102467. */
  102468. function SimplicationQueueSceneComponent(scene) {
  102469. /**
  102470. * The component name helpfull to identify the component in the list of scene components.
  102471. */
  102472. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  102473. this.scene = scene;
  102474. }
  102475. /**
  102476. * Registers the component in a given scene
  102477. */
  102478. SimplicationQueueSceneComponent.prototype.register = function () {
  102479. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  102480. };
  102481. /**
  102482. * Rebuilds the elements related to this component in case of
  102483. * context lost for instance.
  102484. */
  102485. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  102486. // Nothing to do for this component
  102487. };
  102488. /**
  102489. * Disposes the component and the associated ressources
  102490. */
  102491. SimplicationQueueSceneComponent.prototype.dispose = function () {
  102492. // Nothing to do for this component
  102493. };
  102494. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  102495. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  102496. this.scene._simplificationQueue.executeNext();
  102497. }
  102498. };
  102499. return SimplicationQueueSceneComponent;
  102500. }());
  102501. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  102502. })(BABYLON || (BABYLON = {}));
  102503. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  102504. var BABYLON;
  102505. (function (BABYLON) {
  102506. /**
  102507. * Class used to represent a specific level of detail of a mesh
  102508. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  102509. */
  102510. var MeshLODLevel = /** @class */ (function () {
  102511. /**
  102512. * Creates a new LOD level
  102513. * @param distance defines the distance where this level should star being displayed
  102514. * @param mesh defines the mesh to use to render this level
  102515. */
  102516. function MeshLODLevel(
  102517. /** Defines the distance where this level should star being displayed */
  102518. distance,
  102519. /** Defines the mesh to use to render this level */
  102520. mesh) {
  102521. this.distance = distance;
  102522. this.mesh = mesh;
  102523. }
  102524. return MeshLODLevel;
  102525. }());
  102526. BABYLON.MeshLODLevel = MeshLODLevel;
  102527. })(BABYLON || (BABYLON = {}));
  102528. //# sourceMappingURL=babylon.meshLODLevel.js.map
  102529. var BABYLON;
  102530. (function (BABYLON) {
  102531. /**
  102532. * Defines the root class used to create scene optimization to use with SceneOptimizer
  102533. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102534. */
  102535. var SceneOptimization = /** @class */ (function () {
  102536. /**
  102537. * Creates the SceneOptimization object
  102538. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102539. * @param desc defines the description associated with the optimization
  102540. */
  102541. function SceneOptimization(
  102542. /**
  102543. * Defines the priority of this optimization (0 by default which means first in the list)
  102544. */
  102545. priority) {
  102546. if (priority === void 0) { priority = 0; }
  102547. this.priority = priority;
  102548. }
  102549. /**
  102550. * Gets a string describing the action executed by the current optimization
  102551. * @returns description string
  102552. */
  102553. SceneOptimization.prototype.getDescription = function () {
  102554. return "";
  102555. };
  102556. /**
  102557. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102558. * @param scene defines the current scene where to apply this optimization
  102559. * @param optimizer defines the current optimizer
  102560. * @returns true if everything that can be done was applied
  102561. */
  102562. SceneOptimization.prototype.apply = function (scene, optimizer) {
  102563. return true;
  102564. };
  102565. ;
  102566. return SceneOptimization;
  102567. }());
  102568. BABYLON.SceneOptimization = SceneOptimization;
  102569. /**
  102570. * Defines an optimization used to reduce the size of render target textures
  102571. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102572. */
  102573. var TextureOptimization = /** @class */ (function (_super) {
  102574. __extends(TextureOptimization, _super);
  102575. /**
  102576. * Creates the TextureOptimization object
  102577. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102578. * @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
  102579. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102580. */
  102581. function TextureOptimization(
  102582. /**
  102583. * Defines the priority of this optimization (0 by default which means first in the list)
  102584. */
  102585. priority,
  102586. /**
  102587. * 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
  102588. */
  102589. maximumSize,
  102590. /**
  102591. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102592. */
  102593. step) {
  102594. if (priority === void 0) { priority = 0; }
  102595. if (maximumSize === void 0) { maximumSize = 1024; }
  102596. if (step === void 0) { step = 0.5; }
  102597. var _this = _super.call(this, priority) || this;
  102598. _this.priority = priority;
  102599. _this.maximumSize = maximumSize;
  102600. _this.step = step;
  102601. return _this;
  102602. }
  102603. /**
  102604. * Gets a string describing the action executed by the current optimization
  102605. * @returns description string
  102606. */
  102607. TextureOptimization.prototype.getDescription = function () {
  102608. return "Reducing render target texture size to " + this.maximumSize;
  102609. };
  102610. /**
  102611. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102612. * @param scene defines the current scene where to apply this optimization
  102613. * @param optimizer defines the current optimizer
  102614. * @returns true if everything that can be done was applied
  102615. */
  102616. TextureOptimization.prototype.apply = function (scene, optimizer) {
  102617. var allDone = true;
  102618. for (var index = 0; index < scene.textures.length; index++) {
  102619. var texture = scene.textures[index];
  102620. if (!texture.canRescale || texture.getContext) {
  102621. continue;
  102622. }
  102623. var currentSize = texture.getSize();
  102624. var maxDimension = Math.max(currentSize.width, currentSize.height);
  102625. if (maxDimension > this.maximumSize) {
  102626. texture.scale(this.step);
  102627. allDone = false;
  102628. }
  102629. }
  102630. return allDone;
  102631. };
  102632. return TextureOptimization;
  102633. }(SceneOptimization));
  102634. BABYLON.TextureOptimization = TextureOptimization;
  102635. /**
  102636. * Defines an optimization used to increase or decrease the rendering resolution
  102637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102638. */
  102639. var HardwareScalingOptimization = /** @class */ (function (_super) {
  102640. __extends(HardwareScalingOptimization, _super);
  102641. /**
  102642. * Creates the HardwareScalingOptimization object
  102643. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102644. * @param maximumScale defines the maximum scale to use (2 by default)
  102645. * @param step defines the step to use between two passes (0.5 by default)
  102646. */
  102647. function HardwareScalingOptimization(
  102648. /**
  102649. * Defines the priority of this optimization (0 by default which means first in the list)
  102650. */
  102651. priority,
  102652. /**
  102653. * Defines the maximum scale to use (2 by default)
  102654. */
  102655. maximumScale,
  102656. /**
  102657. * Defines the step to use between two passes (0.5 by default)
  102658. */
  102659. step) {
  102660. if (priority === void 0) { priority = 0; }
  102661. if (maximumScale === void 0) { maximumScale = 2; }
  102662. if (step === void 0) { step = 0.25; }
  102663. var _this = _super.call(this, priority) || this;
  102664. _this.priority = priority;
  102665. _this.maximumScale = maximumScale;
  102666. _this.step = step;
  102667. _this._currentScale = -1;
  102668. _this._directionOffset = 1;
  102669. return _this;
  102670. }
  102671. /**
  102672. * Gets a string describing the action executed by the current optimization
  102673. * @return description string
  102674. */
  102675. HardwareScalingOptimization.prototype.getDescription = function () {
  102676. return "Setting hardware scaling level to " + this._currentScale;
  102677. };
  102678. /**
  102679. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102680. * @param scene defines the current scene where to apply this optimization
  102681. * @param optimizer defines the current optimizer
  102682. * @returns true if everything that can be done was applied
  102683. */
  102684. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  102685. if (this._currentScale === -1) {
  102686. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  102687. if (this._currentScale > this.maximumScale) {
  102688. this._directionOffset = -1;
  102689. }
  102690. }
  102691. this._currentScale += this._directionOffset * this.step;
  102692. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  102693. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  102694. };
  102695. ;
  102696. return HardwareScalingOptimization;
  102697. }(SceneOptimization));
  102698. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  102699. /**
  102700. * Defines an optimization used to remove shadows
  102701. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102702. */
  102703. var ShadowsOptimization = /** @class */ (function (_super) {
  102704. __extends(ShadowsOptimization, _super);
  102705. function ShadowsOptimization() {
  102706. return _super !== null && _super.apply(this, arguments) || this;
  102707. }
  102708. /**
  102709. * Gets a string describing the action executed by the current optimization
  102710. * @return description string
  102711. */
  102712. ShadowsOptimization.prototype.getDescription = function () {
  102713. return "Turning shadows on/off";
  102714. };
  102715. /**
  102716. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102717. * @param scene defines the current scene where to apply this optimization
  102718. * @param optimizer defines the current optimizer
  102719. * @returns true if everything that can be done was applied
  102720. */
  102721. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  102722. scene.shadowsEnabled = optimizer.isInImprovementMode;
  102723. return true;
  102724. };
  102725. ;
  102726. return ShadowsOptimization;
  102727. }(SceneOptimization));
  102728. BABYLON.ShadowsOptimization = ShadowsOptimization;
  102729. /**
  102730. * Defines an optimization used to turn post-processes off
  102731. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102732. */
  102733. var PostProcessesOptimization = /** @class */ (function (_super) {
  102734. __extends(PostProcessesOptimization, _super);
  102735. function PostProcessesOptimization() {
  102736. return _super !== null && _super.apply(this, arguments) || this;
  102737. }
  102738. /**
  102739. * Gets a string describing the action executed by the current optimization
  102740. * @return description string
  102741. */
  102742. PostProcessesOptimization.prototype.getDescription = function () {
  102743. return "Turning post-processes on/off";
  102744. };
  102745. /**
  102746. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102747. * @param scene defines the current scene where to apply this optimization
  102748. * @param optimizer defines the current optimizer
  102749. * @returns true if everything that can be done was applied
  102750. */
  102751. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  102752. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  102753. return true;
  102754. };
  102755. ;
  102756. return PostProcessesOptimization;
  102757. }(SceneOptimization));
  102758. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  102759. /**
  102760. * Defines an optimization used to turn lens flares off
  102761. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102762. */
  102763. var LensFlaresOptimization = /** @class */ (function (_super) {
  102764. __extends(LensFlaresOptimization, _super);
  102765. function LensFlaresOptimization() {
  102766. return _super !== null && _super.apply(this, arguments) || this;
  102767. }
  102768. /**
  102769. * Gets a string describing the action executed by the current optimization
  102770. * @return description string
  102771. */
  102772. LensFlaresOptimization.prototype.getDescription = function () {
  102773. return "Turning lens flares on/off";
  102774. };
  102775. /**
  102776. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102777. * @param scene defines the current scene where to apply this optimization
  102778. * @param optimizer defines the current optimizer
  102779. * @returns true if everything that can be done was applied
  102780. */
  102781. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  102782. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  102783. return true;
  102784. };
  102785. ;
  102786. return LensFlaresOptimization;
  102787. }(SceneOptimization));
  102788. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  102789. /**
  102790. * Defines an optimization based on user defined callback.
  102791. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102792. */
  102793. var CustomOptimization = /** @class */ (function (_super) {
  102794. __extends(CustomOptimization, _super);
  102795. function CustomOptimization() {
  102796. return _super !== null && _super.apply(this, arguments) || this;
  102797. }
  102798. /**
  102799. * Gets a string describing the action executed by the current optimization
  102800. * @returns description string
  102801. */
  102802. CustomOptimization.prototype.getDescription = function () {
  102803. if (this.onGetDescription) {
  102804. return this.onGetDescription();
  102805. }
  102806. return "Running user defined callback";
  102807. };
  102808. /**
  102809. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102810. * @param scene defines the current scene where to apply this optimization
  102811. * @param optimizer defines the current optimizer
  102812. * @returns true if everything that can be done was applied
  102813. */
  102814. CustomOptimization.prototype.apply = function (scene, optimizer) {
  102815. if (this.onApply) {
  102816. return this.onApply(scene, optimizer);
  102817. }
  102818. return true;
  102819. };
  102820. ;
  102821. return CustomOptimization;
  102822. }(SceneOptimization));
  102823. BABYLON.CustomOptimization = CustomOptimization;
  102824. /**
  102825. * Defines an optimization used to turn particles off
  102826. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102827. */
  102828. var ParticlesOptimization = /** @class */ (function (_super) {
  102829. __extends(ParticlesOptimization, _super);
  102830. function ParticlesOptimization() {
  102831. return _super !== null && _super.apply(this, arguments) || this;
  102832. }
  102833. /**
  102834. * Gets a string describing the action executed by the current optimization
  102835. * @return description string
  102836. */
  102837. ParticlesOptimization.prototype.getDescription = function () {
  102838. return "Turning particles on/off";
  102839. };
  102840. /**
  102841. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102842. * @param scene defines the current scene where to apply this optimization
  102843. * @param optimizer defines the current optimizer
  102844. * @returns true if everything that can be done was applied
  102845. */
  102846. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  102847. scene.particlesEnabled = optimizer.isInImprovementMode;
  102848. return true;
  102849. };
  102850. ;
  102851. return ParticlesOptimization;
  102852. }(SceneOptimization));
  102853. BABYLON.ParticlesOptimization = ParticlesOptimization;
  102854. /**
  102855. * Defines an optimization used to turn render targets off
  102856. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102857. */
  102858. var RenderTargetsOptimization = /** @class */ (function (_super) {
  102859. __extends(RenderTargetsOptimization, _super);
  102860. function RenderTargetsOptimization() {
  102861. return _super !== null && _super.apply(this, arguments) || this;
  102862. }
  102863. /**
  102864. * Gets a string describing the action executed by the current optimization
  102865. * @return description string
  102866. */
  102867. RenderTargetsOptimization.prototype.getDescription = function () {
  102868. return "Turning render targets off";
  102869. };
  102870. /**
  102871. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102872. * @param scene defines the current scene where to apply this optimization
  102873. * @param optimizer defines the current optimizer
  102874. * @returns true if everything that can be done was applied
  102875. */
  102876. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  102877. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  102878. return true;
  102879. };
  102880. ;
  102881. return RenderTargetsOptimization;
  102882. }(SceneOptimization));
  102883. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  102884. /**
  102885. * Defines an optimization used to merge meshes with compatible materials
  102886. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102887. */
  102888. var MergeMeshesOptimization = /** @class */ (function (_super) {
  102889. __extends(MergeMeshesOptimization, _super);
  102890. function MergeMeshesOptimization() {
  102891. var _this = _super !== null && _super.apply(this, arguments) || this;
  102892. _this._canBeMerged = function (abstractMesh) {
  102893. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  102894. return false;
  102895. }
  102896. var mesh = abstractMesh;
  102897. if (mesh.isDisposed()) {
  102898. return false;
  102899. }
  102900. if (!mesh.isVisible || !mesh.isEnabled()) {
  102901. return false;
  102902. }
  102903. if (mesh.instances.length > 0) {
  102904. return false;
  102905. }
  102906. if (mesh.skeleton || mesh.hasLODLevels) {
  102907. return false;
  102908. }
  102909. return true;
  102910. };
  102911. return _this;
  102912. }
  102913. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  102914. /**
  102915. * Gets or sets a boolean which defines if optimization octree has to be updated
  102916. */
  102917. get: function () {
  102918. return MergeMeshesOptimization._UpdateSelectionTree;
  102919. },
  102920. /**
  102921. * Gets or sets a boolean which defines if optimization octree has to be updated
  102922. */
  102923. set: function (value) {
  102924. MergeMeshesOptimization._UpdateSelectionTree = value;
  102925. },
  102926. enumerable: true,
  102927. configurable: true
  102928. });
  102929. /**
  102930. * Gets a string describing the action executed by the current optimization
  102931. * @return description string
  102932. */
  102933. MergeMeshesOptimization.prototype.getDescription = function () {
  102934. return "Merging similar meshes together";
  102935. };
  102936. /**
  102937. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102938. * @param scene defines the current scene where to apply this optimization
  102939. * @param optimizer defines the current optimizer
  102940. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  102941. * @returns true if everything that can be done was applied
  102942. */
  102943. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  102944. var globalPool = scene.meshes.slice(0);
  102945. var globalLength = globalPool.length;
  102946. for (var index = 0; index < globalLength; index++) {
  102947. var currentPool = new Array();
  102948. var current = globalPool[index];
  102949. // Checks
  102950. if (!this._canBeMerged(current)) {
  102951. continue;
  102952. }
  102953. currentPool.push(current);
  102954. // Find compatible meshes
  102955. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  102956. var otherMesh = globalPool[subIndex];
  102957. if (!this._canBeMerged(otherMesh)) {
  102958. continue;
  102959. }
  102960. if (otherMesh.material !== current.material) {
  102961. continue;
  102962. }
  102963. if (otherMesh.checkCollisions !== current.checkCollisions) {
  102964. continue;
  102965. }
  102966. currentPool.push(otherMesh);
  102967. globalLength--;
  102968. globalPool.splice(subIndex, 1);
  102969. subIndex--;
  102970. }
  102971. if (currentPool.length < 2) {
  102972. continue;
  102973. }
  102974. // Merge meshes
  102975. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  102976. }
  102977. // Call the octree system optimization if it is defined.
  102978. var sceneAsAny = scene;
  102979. if (sceneAsAny.createOrUpdateSelectionOctree) {
  102980. if (updateSelectionTree != undefined) {
  102981. if (updateSelectionTree) {
  102982. sceneAsAny.createOrUpdateSelectionOctree();
  102983. }
  102984. }
  102985. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  102986. sceneAsAny.createOrUpdateSelectionOctree();
  102987. }
  102988. }
  102989. return true;
  102990. };
  102991. ;
  102992. MergeMeshesOptimization._UpdateSelectionTree = false;
  102993. return MergeMeshesOptimization;
  102994. }(SceneOptimization));
  102995. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  102996. /**
  102997. * Defines a list of options used by SceneOptimizer
  102998. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102999. */
  103000. var SceneOptimizerOptions = /** @class */ (function () {
  103001. /**
  103002. * Creates a new list of options used by SceneOptimizer
  103003. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103004. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103005. */
  103006. function SceneOptimizerOptions(
  103007. /**
  103008. * Defines the target frame rate to reach (60 by default)
  103009. */
  103010. targetFrameRate,
  103011. /**
  103012. * Defines the interval between two checkes (2000ms by default)
  103013. */
  103014. trackerDuration) {
  103015. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103016. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103017. this.targetFrameRate = targetFrameRate;
  103018. this.trackerDuration = trackerDuration;
  103019. /**
  103020. * Gets the list of optimizations to apply
  103021. */
  103022. this.optimizations = new Array();
  103023. }
  103024. /**
  103025. * Add a new optimization
  103026. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103027. * @returns the current SceneOptimizerOptions
  103028. */
  103029. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103030. this.optimizations.push(optimization);
  103031. return this;
  103032. };
  103033. /**
  103034. * Add a new custom optimization
  103035. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103036. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103037. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103038. * @returns the current SceneOptimizerOptions
  103039. */
  103040. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103041. if (priority === void 0) { priority = 0; }
  103042. var optimization = new CustomOptimization(priority);
  103043. optimization.onApply = onApply;
  103044. optimization.onGetDescription = onGetDescription;
  103045. this.optimizations.push(optimization);
  103046. return this;
  103047. };
  103048. /**
  103049. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103050. * @param targetFrameRate defines the target frame rate (60 by default)
  103051. * @returns a SceneOptimizerOptions object
  103052. */
  103053. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103054. var result = new SceneOptimizerOptions(targetFrameRate);
  103055. var priority = 0;
  103056. result.addOptimization(new MergeMeshesOptimization(priority));
  103057. result.addOptimization(new ShadowsOptimization(priority));
  103058. result.addOptimization(new LensFlaresOptimization(priority));
  103059. // Next priority
  103060. priority++;
  103061. result.addOptimization(new PostProcessesOptimization(priority));
  103062. result.addOptimization(new ParticlesOptimization(priority));
  103063. // Next priority
  103064. priority++;
  103065. result.addOptimization(new TextureOptimization(priority, 1024));
  103066. return result;
  103067. };
  103068. /**
  103069. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103070. * @param targetFrameRate defines the target frame rate (60 by default)
  103071. * @returns a SceneOptimizerOptions object
  103072. */
  103073. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103074. var result = new SceneOptimizerOptions(targetFrameRate);
  103075. var priority = 0;
  103076. result.addOptimization(new MergeMeshesOptimization(priority));
  103077. result.addOptimization(new ShadowsOptimization(priority));
  103078. result.addOptimization(new LensFlaresOptimization(priority));
  103079. // Next priority
  103080. priority++;
  103081. result.addOptimization(new PostProcessesOptimization(priority));
  103082. result.addOptimization(new ParticlesOptimization(priority));
  103083. // Next priority
  103084. priority++;
  103085. result.addOptimization(new TextureOptimization(priority, 512));
  103086. // Next priority
  103087. priority++;
  103088. result.addOptimization(new RenderTargetsOptimization(priority));
  103089. // Next priority
  103090. priority++;
  103091. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103092. return result;
  103093. };
  103094. /**
  103095. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103096. * @param targetFrameRate defines the target frame rate (60 by default)
  103097. * @returns a SceneOptimizerOptions object
  103098. */
  103099. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103100. var result = new SceneOptimizerOptions(targetFrameRate);
  103101. var priority = 0;
  103102. result.addOptimization(new MergeMeshesOptimization(priority));
  103103. result.addOptimization(new ShadowsOptimization(priority));
  103104. result.addOptimization(new LensFlaresOptimization(priority));
  103105. // Next priority
  103106. priority++;
  103107. result.addOptimization(new PostProcessesOptimization(priority));
  103108. result.addOptimization(new ParticlesOptimization(priority));
  103109. // Next priority
  103110. priority++;
  103111. result.addOptimization(new TextureOptimization(priority, 256));
  103112. // Next priority
  103113. priority++;
  103114. result.addOptimization(new RenderTargetsOptimization(priority));
  103115. // Next priority
  103116. priority++;
  103117. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103118. return result;
  103119. };
  103120. return SceneOptimizerOptions;
  103121. }());
  103122. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103123. /**
  103124. * Class used to run optimizations in order to reach a target frame rate
  103125. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103126. */
  103127. var SceneOptimizer = /** @class */ (function () {
  103128. /**
  103129. * Creates a new SceneOptimizer
  103130. * @param scene defines the scene to work on
  103131. * @param options defines the options to use with the SceneOptimizer
  103132. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  103133. * @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)
  103134. */
  103135. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  103136. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  103137. if (improvementMode === void 0) { improvementMode = false; }
  103138. var _this = this;
  103139. this._isRunning = false;
  103140. this._currentPriorityLevel = 0;
  103141. this._targetFrameRate = 60;
  103142. this._trackerDuration = 2000;
  103143. this._currentFrameRate = 0;
  103144. this._improvementMode = false;
  103145. /**
  103146. * Defines an observable called when the optimizer reaches the target frame rate
  103147. */
  103148. this.onSuccessObservable = new BABYLON.Observable();
  103149. /**
  103150. * Defines an observable called when the optimizer enables an optimization
  103151. */
  103152. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  103153. /**
  103154. * Defines an observable called when the optimizer is not able to reach the target frame rate
  103155. */
  103156. this.onFailureObservable = new BABYLON.Observable();
  103157. if (!options) {
  103158. this._options = new SceneOptimizerOptions();
  103159. }
  103160. else {
  103161. this._options = options;
  103162. }
  103163. if (this._options.targetFrameRate) {
  103164. this._targetFrameRate = this._options.targetFrameRate;
  103165. }
  103166. if (this._options.trackerDuration) {
  103167. this._trackerDuration = this._options.trackerDuration;
  103168. }
  103169. if (autoGeneratePriorities) {
  103170. var priority = 0;
  103171. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  103172. var optim = _a[_i];
  103173. optim.priority = priority++;
  103174. }
  103175. }
  103176. this._improvementMode = improvementMode;
  103177. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103178. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  103179. _this._sceneDisposeObserver = null;
  103180. _this.dispose();
  103181. });
  103182. }
  103183. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  103184. /**
  103185. * Gets a boolean indicating if the optimizer is in improvement mode
  103186. */
  103187. get: function () {
  103188. return this._improvementMode;
  103189. },
  103190. enumerable: true,
  103191. configurable: true
  103192. });
  103193. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  103194. /**
  103195. * Gets the current priority level (0 at start)
  103196. */
  103197. get: function () {
  103198. return this._currentPriorityLevel;
  103199. },
  103200. enumerable: true,
  103201. configurable: true
  103202. });
  103203. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  103204. /**
  103205. * Gets the current frame rate checked by the SceneOptimizer
  103206. */
  103207. get: function () {
  103208. return this._currentFrameRate;
  103209. },
  103210. enumerable: true,
  103211. configurable: true
  103212. });
  103213. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  103214. /**
  103215. * Gets or sets the current target frame rate (60 by default)
  103216. */
  103217. get: function () {
  103218. return this._targetFrameRate;
  103219. },
  103220. /**
  103221. * Gets or sets the current target frame rate (60 by default)
  103222. */
  103223. set: function (value) {
  103224. this._targetFrameRate = value;
  103225. },
  103226. enumerable: true,
  103227. configurable: true
  103228. });
  103229. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  103230. /**
  103231. * Gets or sets the current interval between two checks (every 2000ms by default)
  103232. */
  103233. get: function () {
  103234. return this._trackerDuration;
  103235. },
  103236. /**
  103237. * Gets or sets the current interval between two checks (every 2000ms by default)
  103238. */
  103239. set: function (value) {
  103240. this._trackerDuration = value;
  103241. },
  103242. enumerable: true,
  103243. configurable: true
  103244. });
  103245. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  103246. /**
  103247. * Gets the list of active optimizations
  103248. */
  103249. get: function () {
  103250. return this._options.optimizations;
  103251. },
  103252. enumerable: true,
  103253. configurable: true
  103254. });
  103255. /**
  103256. * Stops the current optimizer
  103257. */
  103258. SceneOptimizer.prototype.stop = function () {
  103259. this._isRunning = false;
  103260. };
  103261. /**
  103262. * Reset the optimizer to initial step (current priority level = 0)
  103263. */
  103264. SceneOptimizer.prototype.reset = function () {
  103265. this._currentPriorityLevel = 0;
  103266. };
  103267. /**
  103268. * Start the optimizer. By default it will try to reach a specific framerate
  103269. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  103270. */
  103271. SceneOptimizer.prototype.start = function () {
  103272. var _this = this;
  103273. if (this._isRunning) {
  103274. return;
  103275. }
  103276. this._isRunning = true;
  103277. // Let's wait for the scene to be ready before running our check
  103278. this._scene.executeWhenReady(function () {
  103279. setTimeout(function () {
  103280. _this._checkCurrentState();
  103281. }, _this._trackerDuration);
  103282. });
  103283. };
  103284. SceneOptimizer.prototype._checkCurrentState = function () {
  103285. var _this = this;
  103286. if (!this._isRunning) {
  103287. return;
  103288. }
  103289. var scene = this._scene;
  103290. var options = this._options;
  103291. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  103292. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  103293. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  103294. this._isRunning = false;
  103295. this.onSuccessObservable.notifyObservers(this);
  103296. return;
  103297. }
  103298. // Apply current level of optimizations
  103299. var allDone = true;
  103300. var noOptimizationApplied = true;
  103301. for (var index = 0; index < options.optimizations.length; index++) {
  103302. var optimization = options.optimizations[index];
  103303. if (optimization.priority === this._currentPriorityLevel) {
  103304. noOptimizationApplied = false;
  103305. allDone = allDone && optimization.apply(scene, this);
  103306. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  103307. }
  103308. }
  103309. // If no optimization was applied, this is a failure :(
  103310. if (noOptimizationApplied) {
  103311. this._isRunning = false;
  103312. this.onFailureObservable.notifyObservers(this);
  103313. return;
  103314. }
  103315. // If all optimizations were done, move to next level
  103316. if (allDone) {
  103317. this._currentPriorityLevel++;
  103318. }
  103319. // Let's the system running for a specific amount of time before checking FPS
  103320. scene.executeWhenReady(function () {
  103321. setTimeout(function () {
  103322. _this._checkCurrentState();
  103323. }, _this._trackerDuration);
  103324. });
  103325. };
  103326. /**
  103327. * Release all resources
  103328. */
  103329. SceneOptimizer.prototype.dispose = function () {
  103330. this.stop();
  103331. this.onSuccessObservable.clear();
  103332. this.onFailureObservable.clear();
  103333. this.onNewOptimizationAppliedObservable.clear();
  103334. if (this._sceneDisposeObserver) {
  103335. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  103336. }
  103337. };
  103338. /**
  103339. * Helper function to create a SceneOptimizer with one single line of code
  103340. * @param scene defines the scene to work on
  103341. * @param options defines the options to use with the SceneOptimizer
  103342. * @param onSuccess defines a callback to call on success
  103343. * @param onFailure defines a callback to call on failure
  103344. * @returns the new SceneOptimizer object
  103345. */
  103346. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  103347. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  103348. if (onSuccess) {
  103349. optimizer.onSuccessObservable.add(function () {
  103350. onSuccess();
  103351. });
  103352. }
  103353. if (onFailure) {
  103354. optimizer.onFailureObservable.add(function () {
  103355. onFailure();
  103356. });
  103357. }
  103358. optimizer.start();
  103359. return optimizer;
  103360. };
  103361. return SceneOptimizer;
  103362. }());
  103363. BABYLON.SceneOptimizer = SceneOptimizer;
  103364. })(BABYLON || (BABYLON = {}));
  103365. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  103366. var BABYLON;
  103367. (function (BABYLON) {
  103368. /**
  103369. * Gets the outline renderer associated with the scene
  103370. * @returns a OutlineRenderer
  103371. */
  103372. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  103373. if (!this._outlineRenderer) {
  103374. this._outlineRenderer = new OutlineRenderer(this);
  103375. }
  103376. return this._outlineRenderer;
  103377. };
  103378. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  103379. get: function () {
  103380. return this._renderOutline;
  103381. },
  103382. set: function (value) {
  103383. if (value) {
  103384. // Lazy Load the component.
  103385. this.getScene().getOutlineRenderer();
  103386. }
  103387. this._renderOutline = value;
  103388. },
  103389. enumerable: true,
  103390. configurable: true
  103391. });
  103392. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  103393. get: function () {
  103394. return this._renderOverlay;
  103395. },
  103396. set: function (value) {
  103397. if (value) {
  103398. // Lazy Load the component.
  103399. this.getScene().getOutlineRenderer();
  103400. }
  103401. this._renderOverlay = value;
  103402. },
  103403. enumerable: true,
  103404. configurable: true
  103405. });
  103406. /**
  103407. * This class is responsible to draw bothe outline/overlay of meshes.
  103408. * It should not be used directly but through the available method on mesh.
  103409. */
  103410. var OutlineRenderer = /** @class */ (function () {
  103411. /**
  103412. * Instantiates a new outline renderer. (There could be only one per scene).
  103413. * @param scene Defines the scene it belongs to
  103414. */
  103415. function OutlineRenderer(scene) {
  103416. /**
  103417. * The name of the component. Each component must have a unique name.
  103418. */
  103419. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  103420. /**
  103421. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  103422. */
  103423. this.zOffset = 1;
  103424. this.scene = scene;
  103425. this._engine = scene.getEngine();
  103426. this.scene._addComponent(this);
  103427. }
  103428. /**
  103429. * Register the component to one instance of a scene.
  103430. */
  103431. OutlineRenderer.prototype.register = function () {
  103432. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  103433. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  103434. };
  103435. /**
  103436. * Rebuilds the elements related to this component in case of
  103437. * context lost for instance.
  103438. */
  103439. OutlineRenderer.prototype.rebuild = function () {
  103440. // Nothing to do here.
  103441. };
  103442. /**
  103443. * Disposes the component and the associated ressources.
  103444. */
  103445. OutlineRenderer.prototype.dispose = function () {
  103446. // Nothing to do here.
  103447. };
  103448. /**
  103449. * Renders the outline in the canvas.
  103450. * @param subMesh Defines the sumesh to render
  103451. * @param batch Defines the batch of meshes in case of instances
  103452. * @param useOverlay Defines if the rendering is for the overlay or the outline
  103453. */
  103454. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  103455. var _this = this;
  103456. if (useOverlay === void 0) { useOverlay = false; }
  103457. var scene = this.scene;
  103458. var engine = scene.getEngine();
  103459. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  103460. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  103461. return;
  103462. }
  103463. var mesh = subMesh.getRenderingMesh();
  103464. var material = subMesh.getMaterial();
  103465. if (!material || !scene.activeCamera) {
  103466. return;
  103467. }
  103468. engine.enableEffect(this._effect);
  103469. // Logarithmic depth
  103470. if (material.useLogarithmicDepth) {
  103471. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  103472. }
  103473. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  103474. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  103475. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  103476. // Bones
  103477. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  103478. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  103479. }
  103480. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  103481. // Alpha test
  103482. if (material && material.needAlphaTesting()) {
  103483. var alphaTexture = material.getAlphaTestTexture();
  103484. if (alphaTexture) {
  103485. this._effect.setTexture("diffuseSampler", alphaTexture);
  103486. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  103487. }
  103488. }
  103489. engine.setZOffset(-this.zOffset);
  103490. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  103491. engine.setZOffset(0);
  103492. };
  103493. /**
  103494. * Returns whether or not the outline renderer is ready for a given submesh.
  103495. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  103496. * @param subMesh Defines the submesh to check readyness for
  103497. * @param useInstances Defines wheter wee are trying to render instances or not
  103498. * @returns true if ready otherwise false
  103499. */
  103500. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  103501. var defines = [];
  103502. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  103503. var mesh = subMesh.getMesh();
  103504. var material = subMesh.getMaterial();
  103505. if (material) {
  103506. // Alpha test
  103507. if (material.needAlphaTesting()) {
  103508. defines.push("#define ALPHATEST");
  103509. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  103510. attribs.push(BABYLON.VertexBuffer.UVKind);
  103511. defines.push("#define UV1");
  103512. }
  103513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  103514. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103515. defines.push("#define UV2");
  103516. }
  103517. }
  103518. //Logarithmic depth
  103519. if (material.useLogarithmicDepth) {
  103520. defines.push("#define LOGARITHMICDEPTH");
  103521. }
  103522. }
  103523. // Bones
  103524. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  103525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  103526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  103527. if (mesh.numBoneInfluencers > 4) {
  103528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  103529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  103530. }
  103531. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  103532. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  103533. }
  103534. else {
  103535. defines.push("#define NUM_BONE_INFLUENCERS 0");
  103536. }
  103537. // Instances
  103538. if (useInstances) {
  103539. defines.push("#define INSTANCES");
  103540. attribs.push("world0");
  103541. attribs.push("world1");
  103542. attribs.push("world2");
  103543. attribs.push("world3");
  103544. }
  103545. // Get correct effect
  103546. var join = defines.join("\n");
  103547. if (this._cachedDefines !== join) {
  103548. this._cachedDefines = join;
  103549. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  103550. }
  103551. return this._effect.isReady();
  103552. };
  103553. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  103554. // Outline - step 1
  103555. this._savedDepthWrite = this._engine.getDepthWrite();
  103556. if (mesh.renderOutline) {
  103557. this._engine.setDepthWrite(false);
  103558. this.render(subMesh, batch);
  103559. this._engine.setDepthWrite(this._savedDepthWrite);
  103560. }
  103561. };
  103562. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  103563. // Outline - step 2
  103564. if (mesh.renderOutline && this._savedDepthWrite) {
  103565. this._engine.setDepthWrite(true);
  103566. this._engine.setColorWrite(false);
  103567. this.render(subMesh, batch);
  103568. this._engine.setColorWrite(true);
  103569. }
  103570. // Overlay
  103571. if (mesh.renderOverlay) {
  103572. var currentMode = this._engine.getAlphaMode();
  103573. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103574. this.render(subMesh, batch, true);
  103575. this._engine.setAlphaMode(currentMode);
  103576. }
  103577. };
  103578. return OutlineRenderer;
  103579. }());
  103580. BABYLON.OutlineRenderer = OutlineRenderer;
  103581. })(BABYLON || (BABYLON = {}));
  103582. //# sourceMappingURL=babylon.outlineRenderer.js.map
  103583. var BABYLON;
  103584. (function (BABYLON) {
  103585. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  103586. if (this._edgesRenderer) {
  103587. this._edgesRenderer.dispose();
  103588. this._edgesRenderer = null;
  103589. }
  103590. return this;
  103591. };
  103592. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103593. if (epsilon === void 0) { epsilon = 0.95; }
  103594. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103595. this.disableEdgesRendering();
  103596. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103597. return this;
  103598. };
  103599. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  103600. get: function () {
  103601. return this._edgesRenderer;
  103602. },
  103603. enumerable: true,
  103604. configurable: true
  103605. });
  103606. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103607. if (epsilon === void 0) { epsilon = 0.95; }
  103608. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103609. this.disableEdgesRendering();
  103610. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103611. return this;
  103612. };
  103613. /**
  103614. * FaceAdjacencies Helper class to generate edges
  103615. */
  103616. var FaceAdjacencies = /** @class */ (function () {
  103617. function FaceAdjacencies() {
  103618. this.edges = new Array();
  103619. this.edgesConnectedCount = 0;
  103620. }
  103621. return FaceAdjacencies;
  103622. }());
  103623. /**
  103624. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  103625. */
  103626. var EdgesRenderer = /** @class */ (function () {
  103627. /**
  103628. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  103629. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  103630. * @param source Mesh used to create edges
  103631. * @param epsilon sum of angles in adjacency to check for edge
  103632. * @param checkVerticesInsteadOfIndices
  103633. * @param generateEdgesLines - should generate Lines or only prepare resources.
  103634. */
  103635. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  103636. if (epsilon === void 0) { epsilon = 0.95; }
  103637. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103638. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  103639. var _this = this;
  103640. this.edgesWidthScalerForOrthographic = 1000.0;
  103641. this.edgesWidthScalerForPerspective = 50.0;
  103642. this._linesPositions = new Array();
  103643. this._linesNormals = new Array();
  103644. this._linesIndices = new Array();
  103645. this._buffers = {};
  103646. this._checkVerticesInsteadOfIndices = false;
  103647. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  103648. this.isEnabled = true;
  103649. this._source = source;
  103650. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  103651. this._epsilon = epsilon;
  103652. this._prepareRessources();
  103653. if (generateEdgesLines) {
  103654. this._generateEdgesLines();
  103655. }
  103656. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  103657. _this._rebuild();
  103658. });
  103659. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  103660. _this.dispose();
  103661. });
  103662. }
  103663. EdgesRenderer.prototype._prepareRessources = function () {
  103664. if (this._lineShader) {
  103665. return;
  103666. }
  103667. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  103668. attributes: ["position", "normal"],
  103669. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  103670. });
  103671. this._lineShader.disableDepthWrite = true;
  103672. this._lineShader.backFaceCulling = false;
  103673. };
  103674. /** @hidden */
  103675. EdgesRenderer.prototype._rebuild = function () {
  103676. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103677. if (buffer) {
  103678. buffer._rebuild();
  103679. }
  103680. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103681. if (buffer) {
  103682. buffer._rebuild();
  103683. }
  103684. var scene = this._source.getScene();
  103685. var engine = scene.getEngine();
  103686. this._ib = engine.createIndexBuffer(this._linesIndices);
  103687. };
  103688. /**
  103689. * Releases the required resources for the edges renderer
  103690. */
  103691. EdgesRenderer.prototype.dispose = function () {
  103692. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  103693. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  103694. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103695. if (buffer) {
  103696. buffer.dispose();
  103697. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  103698. }
  103699. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103700. if (buffer) {
  103701. buffer.dispose();
  103702. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  103703. }
  103704. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  103705. this._lineShader.dispose();
  103706. };
  103707. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  103708. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  103709. return 0;
  103710. }
  103711. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  103712. return 1;
  103713. }
  103714. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  103715. return 2;
  103716. }
  103717. return -1;
  103718. };
  103719. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  103720. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  103721. return 0;
  103722. }
  103723. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  103724. return 1;
  103725. }
  103726. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  103727. return 2;
  103728. }
  103729. return -1;
  103730. };
  103731. /**
  103732. * Checks if the pair of p0 and p1 is en edge
  103733. * @param faceIndex
  103734. * @param edge
  103735. * @param faceNormals
  103736. * @param p0
  103737. * @param p1
  103738. * @private
  103739. */
  103740. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103741. var needToCreateLine;
  103742. if (edge === undefined) {
  103743. needToCreateLine = true;
  103744. }
  103745. else {
  103746. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  103747. needToCreateLine = dotProduct < this._epsilon;
  103748. }
  103749. if (needToCreateLine) {
  103750. var offset = this._linesPositions.length / 3;
  103751. var normal = p0.subtract(p1);
  103752. normal.normalize();
  103753. // Positions
  103754. this._linesPositions.push(p0.x);
  103755. this._linesPositions.push(p0.y);
  103756. this._linesPositions.push(p0.z);
  103757. this._linesPositions.push(p0.x);
  103758. this._linesPositions.push(p0.y);
  103759. this._linesPositions.push(p0.z);
  103760. this._linesPositions.push(p1.x);
  103761. this._linesPositions.push(p1.y);
  103762. this._linesPositions.push(p1.z);
  103763. this._linesPositions.push(p1.x);
  103764. this._linesPositions.push(p1.y);
  103765. this._linesPositions.push(p1.z);
  103766. // Normals
  103767. this._linesNormals.push(p1.x);
  103768. this._linesNormals.push(p1.y);
  103769. this._linesNormals.push(p1.z);
  103770. this._linesNormals.push(-1);
  103771. this._linesNormals.push(p1.x);
  103772. this._linesNormals.push(p1.y);
  103773. this._linesNormals.push(p1.z);
  103774. this._linesNormals.push(1);
  103775. this._linesNormals.push(p0.x);
  103776. this._linesNormals.push(p0.y);
  103777. this._linesNormals.push(p0.z);
  103778. this._linesNormals.push(-1);
  103779. this._linesNormals.push(p0.x);
  103780. this._linesNormals.push(p0.y);
  103781. this._linesNormals.push(p0.z);
  103782. this._linesNormals.push(1);
  103783. // Indices
  103784. this._linesIndices.push(offset);
  103785. this._linesIndices.push(offset + 1);
  103786. this._linesIndices.push(offset + 2);
  103787. this._linesIndices.push(offset);
  103788. this._linesIndices.push(offset + 2);
  103789. this._linesIndices.push(offset + 3);
  103790. }
  103791. };
  103792. /**
  103793. * Generates lines edges from adjacencjes
  103794. * @private
  103795. */
  103796. EdgesRenderer.prototype._generateEdgesLines = function () {
  103797. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103798. var indices = this._source.getIndices();
  103799. if (!indices || !positions) {
  103800. return;
  103801. }
  103802. // First let's find adjacencies
  103803. var adjacencies = new Array();
  103804. var faceNormals = new Array();
  103805. var index;
  103806. var faceAdjacencies;
  103807. // Prepare faces
  103808. for (index = 0; index < indices.length; index += 3) {
  103809. faceAdjacencies = new FaceAdjacencies();
  103810. var p0Index = indices[index];
  103811. var p1Index = indices[index + 1];
  103812. var p2Index = indices[index + 2];
  103813. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  103814. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  103815. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  103816. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  103817. faceNormal.normalize();
  103818. faceNormals.push(faceNormal);
  103819. adjacencies.push(faceAdjacencies);
  103820. }
  103821. // Scan
  103822. for (index = 0; index < adjacencies.length; index++) {
  103823. faceAdjacencies = adjacencies[index];
  103824. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  103825. var otherFaceAdjacencies = adjacencies[otherIndex];
  103826. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  103827. break;
  103828. }
  103829. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  103830. continue;
  103831. }
  103832. var otherP0 = indices[otherIndex * 3];
  103833. var otherP1 = indices[otherIndex * 3 + 1];
  103834. var otherP2 = indices[otherIndex * 3 + 2];
  103835. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  103836. var otherEdgeIndex = 0;
  103837. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  103838. continue;
  103839. }
  103840. switch (edgeIndex) {
  103841. case 0:
  103842. if (this._checkVerticesInsteadOfIndices) {
  103843. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103844. }
  103845. else {
  103846. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  103847. }
  103848. break;
  103849. case 1:
  103850. if (this._checkVerticesInsteadOfIndices) {
  103851. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103852. }
  103853. else {
  103854. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  103855. }
  103856. break;
  103857. case 2:
  103858. if (this._checkVerticesInsteadOfIndices) {
  103859. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103860. }
  103861. else {
  103862. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  103863. }
  103864. break;
  103865. }
  103866. if (otherEdgeIndex === -1) {
  103867. continue;
  103868. }
  103869. faceAdjacencies.edges[edgeIndex] = otherIndex;
  103870. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  103871. faceAdjacencies.edgesConnectedCount++;
  103872. otherFaceAdjacencies.edgesConnectedCount++;
  103873. if (faceAdjacencies.edgesConnectedCount === 3) {
  103874. break;
  103875. }
  103876. }
  103877. }
  103878. }
  103879. // Create lines
  103880. for (index = 0; index < adjacencies.length; index++) {
  103881. // 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
  103882. var current = adjacencies[index];
  103883. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  103884. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  103885. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  103886. }
  103887. // Merge into a single mesh
  103888. var engine = this._source.getScene().getEngine();
  103889. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  103890. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  103891. this._ib = engine.createIndexBuffer(this._linesIndices);
  103892. this._indicesCount = this._linesIndices.length;
  103893. };
  103894. /**
  103895. * Checks wether or not the edges renderer is ready to render.
  103896. * @return true if ready, otherwise false.
  103897. */
  103898. EdgesRenderer.prototype.isReady = function () {
  103899. return this._lineShader.isReady();
  103900. };
  103901. /**
  103902. * Renders the edges of the attached mesh,
  103903. */
  103904. EdgesRenderer.prototype.render = function () {
  103905. var scene = this._source.getScene();
  103906. if (!this.isReady() || !scene.activeCamera) {
  103907. return;
  103908. }
  103909. var engine = scene.getEngine();
  103910. this._lineShader._preBind();
  103911. if (this._source.edgesColor.a !== 1) {
  103912. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103913. }
  103914. else {
  103915. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103916. }
  103917. // VBOs
  103918. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  103919. scene.resetCachedMaterial();
  103920. this._lineShader.setColor4("color", this._source.edgesColor);
  103921. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  103922. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  103923. }
  103924. else {
  103925. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  103926. }
  103927. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  103928. this._lineShader.bind(this._source.getWorldMatrix());
  103929. // Draw order
  103930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  103931. this._lineShader.unbind();
  103932. };
  103933. return EdgesRenderer;
  103934. }());
  103935. BABYLON.EdgesRenderer = EdgesRenderer;
  103936. })(BABYLON || (BABYLON = {}));
  103937. //# sourceMappingURL=babylon.edgesRenderer.js.map
  103938. var BABYLON;
  103939. (function (BABYLON) {
  103940. /**
  103941. * FaceAdjacencies Helper class to generate edges
  103942. */
  103943. var FaceAdjacencies = /** @class */ (function () {
  103944. function FaceAdjacencies() {
  103945. this.edges = new Array();
  103946. this.edgesConnectedCount = 0;
  103947. }
  103948. return FaceAdjacencies;
  103949. }());
  103950. /**
  103951. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  103952. */
  103953. var LineEdgesRenderer = /** @class */ (function (_super) {
  103954. __extends(LineEdgesRenderer, _super);
  103955. /**
  103956. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  103957. * @param source LineMesh used to generate edges
  103958. * @param epsilon not important (specified angle for edge detection)
  103959. * @param checkVerticesInsteadOfIndices not important for LineMesh
  103960. */
  103961. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  103962. if (epsilon === void 0) { epsilon = 0.95; }
  103963. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103964. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  103965. _this._generateEdgesLines();
  103966. return _this;
  103967. }
  103968. /**
  103969. * Always create the edge since its a line so only important things are p0 and p1
  103970. * @param faceIndex not important for LineMesh
  103971. * @param edge not important for LineMesh
  103972. * @param faceNormals not important for LineMesh
  103973. * @param p0 beginnig of line
  103974. * @param p1 end of line
  103975. */
  103976. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103977. var offset = this._linesPositions.length / 3;
  103978. var normal = p0.subtract(p1);
  103979. normal.normalize();
  103980. // Positions
  103981. this._linesPositions.push(p0.x);
  103982. this._linesPositions.push(p0.y);
  103983. this._linesPositions.push(p0.z);
  103984. this._linesPositions.push(p0.x);
  103985. this._linesPositions.push(p0.y);
  103986. this._linesPositions.push(p0.z);
  103987. this._linesPositions.push(p1.x);
  103988. this._linesPositions.push(p1.y);
  103989. this._linesPositions.push(p1.z);
  103990. this._linesPositions.push(p1.x);
  103991. this._linesPositions.push(p1.y);
  103992. this._linesPositions.push(p1.z);
  103993. // Normals
  103994. this._linesNormals.push(p1.x);
  103995. this._linesNormals.push(p1.y);
  103996. this._linesNormals.push(p1.z);
  103997. this._linesNormals.push(-1);
  103998. this._linesNormals.push(p1.x);
  103999. this._linesNormals.push(p1.y);
  104000. this._linesNormals.push(p1.z);
  104001. this._linesNormals.push(1);
  104002. this._linesNormals.push(p0.x);
  104003. this._linesNormals.push(p0.y);
  104004. this._linesNormals.push(p0.z);
  104005. this._linesNormals.push(-1);
  104006. this._linesNormals.push(p0.x);
  104007. this._linesNormals.push(p0.y);
  104008. this._linesNormals.push(p0.z);
  104009. this._linesNormals.push(1);
  104010. // Indices
  104011. this._linesIndices.push(offset);
  104012. this._linesIndices.push(offset + 1);
  104013. this._linesIndices.push(offset + 2);
  104014. this._linesIndices.push(offset);
  104015. this._linesIndices.push(offset + 2);
  104016. this._linesIndices.push(offset + 3);
  104017. };
  104018. /**
  104019. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104020. */
  104021. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104022. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104023. var indices = this._source.getIndices();
  104024. if (!indices || !positions) {
  104025. return;
  104026. }
  104027. // First let's find adjacencies
  104028. var adjacencies = new Array();
  104029. var faceNormals = new Array();
  104030. var index;
  104031. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104032. var currentAdjecancy = new FaceAdjacencies();
  104033. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104034. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104035. adjacencies.push(currentAdjecancy);
  104036. }
  104037. // Create lines
  104038. for (index = 0; index < adjacencies.length; index++) {
  104039. // 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
  104040. var current = adjacencies[index];
  104041. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104042. }
  104043. // Merge into a single mesh
  104044. var engine = this._source.getScene().getEngine();
  104045. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104046. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104047. this._ib = engine.createIndexBuffer(this._linesIndices);
  104048. this._indicesCount = this._linesIndices.length;
  104049. };
  104050. return LineEdgesRenderer;
  104051. }(BABYLON.EdgesRenderer));
  104052. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104053. })(BABYLON || (BABYLON = {}));
  104054. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104055. var BABYLON;
  104056. (function (BABYLON) {
  104057. // Adds the parser to the scene parsers.
  104058. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104059. if (parsedData.effectLayers) {
  104060. if (!container.effectLayers) {
  104061. container.effectLayers = new Array();
  104062. }
  104063. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104064. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104065. container.effectLayers.push(effectLayer);
  104066. }
  104067. }
  104068. });
  104069. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104070. var index = this.effectLayers.indexOf(toRemove);
  104071. if (index !== -1) {
  104072. this.effectLayers.splice(index, 1);
  104073. }
  104074. return index;
  104075. };
  104076. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104077. this.effectLayers.push(newEffectLayer);
  104078. };
  104079. /**
  104080. * Defines the layer scene component responsible to manage any effect layers
  104081. * in a given scene.
  104082. */
  104083. var EffectLayerSceneComponent = /** @class */ (function () {
  104084. /**
  104085. * Creates a new instance of the component for the given scene
  104086. * @param scene Defines the scene to register the component in
  104087. */
  104088. function EffectLayerSceneComponent(scene) {
  104089. /**
  104090. * The component name helpfull to identify the component in the list of scene components.
  104091. */
  104092. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104093. this._renderEffects = false;
  104094. this._needStencil = false;
  104095. this._previousStencilState = false;
  104096. this.scene = scene;
  104097. this._engine = scene.getEngine();
  104098. scene.effectLayers = new Array();
  104099. }
  104100. /**
  104101. * Registers the component in a given scene
  104102. */
  104103. EffectLayerSceneComponent.prototype.register = function () {
  104104. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104105. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104106. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104107. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104108. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104109. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104110. };
  104111. /**
  104112. * Rebuilds the elements related to this component in case of
  104113. * context lost for instance.
  104114. */
  104115. EffectLayerSceneComponent.prototype.rebuild = function () {
  104116. var layers = this.scene.effectLayers;
  104117. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104118. var effectLayer = layers_1[_i];
  104119. effectLayer._rebuild();
  104120. }
  104121. };
  104122. /**
  104123. * Serializes the component data to the specified json object
  104124. * @param serializationObject The object to serialize to
  104125. */
  104126. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  104127. // Effect layers
  104128. serializationObject.effectLayers = [];
  104129. var layers = this.scene.effectLayers;
  104130. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104131. var effectLayer = layers_2[_i];
  104132. if (effectLayer.serialize) {
  104133. serializationObject.effectLayers.push(effectLayer.serialize());
  104134. }
  104135. }
  104136. };
  104137. /**
  104138. * Adds all the element from the container to the scene
  104139. * @param container the container holding the elements
  104140. */
  104141. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  104142. var _this = this;
  104143. if (!container.effectLayers) {
  104144. return;
  104145. }
  104146. container.effectLayers.forEach(function (o) {
  104147. _this.scene.addEffectLayer(o);
  104148. });
  104149. };
  104150. /**
  104151. * Removes all the elements in the container from the scene
  104152. * @param container contains the elements to remove
  104153. */
  104154. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  104155. var _this = this;
  104156. if (!container.effectLayers) {
  104157. return;
  104158. }
  104159. container.effectLayers.forEach(function (o) {
  104160. _this.scene.removeEffectLayer(o);
  104161. });
  104162. };
  104163. /**
  104164. * Disposes the component and the associated ressources.
  104165. */
  104166. EffectLayerSceneComponent.prototype.dispose = function () {
  104167. var layers = this.scene.effectLayers;
  104168. while (layers.length) {
  104169. layers[0].dispose();
  104170. }
  104171. };
  104172. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  104173. var layers = this.scene.effectLayers;
  104174. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  104175. var layer = layers_3[_i];
  104176. if (!layer.hasMesh(mesh)) {
  104177. continue;
  104178. }
  104179. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  104180. var subMesh = _b[_a];
  104181. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  104182. return false;
  104183. }
  104184. }
  104185. }
  104186. return true;
  104187. };
  104188. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  104189. this._renderEffects = false;
  104190. this._needStencil = false;
  104191. var layers = this.scene.effectLayers;
  104192. if (layers && layers.length > 0) {
  104193. this._previousStencilState = this._engine.getStencilBuffer();
  104194. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  104195. var effectLayer = layers_4[_i];
  104196. if (effectLayer.shouldRender() &&
  104197. (!effectLayer.camera ||
  104198. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  104199. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  104200. this._renderEffects = true;
  104201. this._needStencil = this._needStencil || effectLayer.needStencil();
  104202. var renderTarget = effectLayer._mainTexture;
  104203. if (renderTarget._shouldRender()) {
  104204. this.scene.incrementRenderId();
  104205. renderTarget.render(false, false);
  104206. }
  104207. }
  104208. }
  104209. this.scene.incrementRenderId();
  104210. }
  104211. };
  104212. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  104213. // Activate effect Layer stencil
  104214. if (this._needStencil) {
  104215. this._engine.setStencilBuffer(true);
  104216. }
  104217. };
  104218. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  104219. // Restore effect Layer stencil
  104220. if (this._needStencil) {
  104221. this._engine.setStencilBuffer(this._previousStencilState);
  104222. }
  104223. };
  104224. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  104225. if (this._renderEffects) {
  104226. this._engine.setDepthBuffer(false);
  104227. var layers = this.scene.effectLayers;
  104228. for (var i = 0; i < layers.length; i++) {
  104229. var effectLayer = layers[i];
  104230. if (effectLayer.renderingGroupId === renderingGroupId) {
  104231. if (effectLayer.shouldRender()) {
  104232. effectLayer.render();
  104233. }
  104234. }
  104235. }
  104236. this._engine.setDepthBuffer(true);
  104237. }
  104238. };
  104239. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  104240. if (this._renderEffects) {
  104241. this._draw(-1);
  104242. }
  104243. };
  104244. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  104245. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  104246. this._draw(index);
  104247. }
  104248. };
  104249. return EffectLayerSceneComponent;
  104250. }());
  104251. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  104252. })(BABYLON || (BABYLON = {}));
  104253. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  104254. var __assign = (this && this.__assign) || function () {
  104255. __assign = Object.assign || function(t) {
  104256. for (var s, i = 1, n = arguments.length; i < n; i++) {
  104257. s = arguments[i];
  104258. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  104259. t[p] = s[p];
  104260. }
  104261. return t;
  104262. };
  104263. return __assign.apply(this, arguments);
  104264. };
  104265. var BABYLON;
  104266. (function (BABYLON) {
  104267. /**
  104268. * The effect layer Helps adding post process effect blended with the main pass.
  104269. *
  104270. * This can be for instance use to generate glow or higlight effects on the scene.
  104271. *
  104272. * The effect layer class can not be used directly and is intented to inherited from to be
  104273. * customized per effects.
  104274. */
  104275. var EffectLayer = /** @class */ (function () {
  104276. /**
  104277. * Instantiates a new effect Layer and references it in the scene.
  104278. * @param name The name of the layer
  104279. * @param scene The scene to use the layer in
  104280. */
  104281. function EffectLayer(
  104282. /** The Friendly of the effect in the scene */
  104283. name, scene) {
  104284. this._vertexBuffers = {};
  104285. this._maxSize = 0;
  104286. this._mainTextureDesiredSize = { width: 0, height: 0 };
  104287. this._shouldRender = true;
  104288. this._postProcesses = [];
  104289. this._textures = [];
  104290. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  104291. /**
  104292. * The clear color of the texture used to generate the glow map.
  104293. */
  104294. this.neutralColor = new BABYLON.Color4();
  104295. /**
  104296. * Specifies wether the highlight layer is enabled or not.
  104297. */
  104298. this.isEnabled = true;
  104299. /**
  104300. * An event triggered when the effect layer has been disposed.
  104301. */
  104302. this.onDisposeObservable = new BABYLON.Observable();
  104303. /**
  104304. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  104305. */
  104306. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  104307. /**
  104308. * An event triggered when the generated texture is being merged in the scene.
  104309. */
  104310. this.onBeforeComposeObservable = new BABYLON.Observable();
  104311. /**
  104312. * An event triggered when the generated texture has been merged in the scene.
  104313. */
  104314. this.onAfterComposeObservable = new BABYLON.Observable();
  104315. /**
  104316. * An event triggered when the efffect layer changes its size.
  104317. */
  104318. this.onSizeChangedObservable = new BABYLON.Observable();
  104319. this.name = name;
  104320. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104321. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  104322. if (!component) {
  104323. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  104324. this._scene._addComponent(component);
  104325. }
  104326. this._engine = this._scene.getEngine();
  104327. this._maxSize = this._engine.getCaps().maxTextureSize;
  104328. this._scene.effectLayers.push(this);
  104329. // Generate Buffers
  104330. this._generateIndexBuffer();
  104331. this._genrateVertexBuffer();
  104332. }
  104333. Object.defineProperty(EffectLayer.prototype, "camera", {
  104334. /**
  104335. * Gets the camera attached to the layer.
  104336. */
  104337. get: function () {
  104338. return this._effectLayerOptions.camera;
  104339. },
  104340. enumerable: true,
  104341. configurable: true
  104342. });
  104343. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  104344. /**
  104345. * Gets the rendering group id the layer should render in.
  104346. */
  104347. get: function () {
  104348. return this._effectLayerOptions.renderingGroupId;
  104349. },
  104350. enumerable: true,
  104351. configurable: true
  104352. });
  104353. /**
  104354. * Initializes the effect layer with the required options.
  104355. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  104356. */
  104357. EffectLayer.prototype._init = function (options) {
  104358. // Adapt options
  104359. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104360. this._setMainTextureSize();
  104361. this._createMainTexture();
  104362. this._createTextureAndPostProcesses();
  104363. this._mergeEffect = this._createMergeEffect();
  104364. };
  104365. /**
  104366. * Generates the index buffer of the full screen quad blending to the main canvas.
  104367. */
  104368. EffectLayer.prototype._generateIndexBuffer = function () {
  104369. // Indices
  104370. var indices = [];
  104371. indices.push(0);
  104372. indices.push(1);
  104373. indices.push(2);
  104374. indices.push(0);
  104375. indices.push(2);
  104376. indices.push(3);
  104377. this._indexBuffer = this._engine.createIndexBuffer(indices);
  104378. };
  104379. /**
  104380. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  104381. */
  104382. EffectLayer.prototype._genrateVertexBuffer = function () {
  104383. // VBO
  104384. var vertices = [];
  104385. vertices.push(1, 1);
  104386. vertices.push(-1, 1);
  104387. vertices.push(-1, -1);
  104388. vertices.push(1, -1);
  104389. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104390. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104391. };
  104392. /**
  104393. * Sets the main texture desired size which is the closest power of two
  104394. * of the engine canvas size.
  104395. */
  104396. EffectLayer.prototype._setMainTextureSize = function () {
  104397. if (this._effectLayerOptions.mainTextureFixedSize) {
  104398. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  104399. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  104400. }
  104401. else {
  104402. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  104403. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  104404. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  104405. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  104406. }
  104407. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  104408. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  104409. };
  104410. /**
  104411. * Creates the main texture for the effect layer.
  104412. */
  104413. EffectLayer.prototype._createMainTexture = function () {
  104414. var _this = this;
  104415. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  104416. width: this._mainTextureDesiredSize.width,
  104417. height: this._mainTextureDesiredSize.height
  104418. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104419. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  104420. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104421. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104422. this._mainTexture.anisotropicFilteringLevel = 1;
  104423. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104424. this._mainTexture.renderParticles = false;
  104425. this._mainTexture.renderList = null;
  104426. this._mainTexture.ignoreCameraViewport = true;
  104427. // Custom render function
  104428. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  104429. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  104430. var index;
  104431. var engine = _this._scene.getEngine();
  104432. if (depthOnlySubMeshes.length) {
  104433. engine.setColorWrite(false);
  104434. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  104435. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  104436. }
  104437. engine.setColorWrite(true);
  104438. }
  104439. for (index = 0; index < opaqueSubMeshes.length; index++) {
  104440. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  104441. }
  104442. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  104443. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  104444. }
  104445. for (index = 0; index < transparentSubMeshes.length; index++) {
  104446. _this._renderSubMesh(transparentSubMeshes.data[index]);
  104447. }
  104448. };
  104449. this._mainTexture.onClearObservable.add(function (engine) {
  104450. engine.clear(_this.neutralColor, true, true, true);
  104451. });
  104452. };
  104453. /**
  104454. * Checks for the readiness of the element composing the layer.
  104455. * @param subMesh the mesh to check for
  104456. * @param useInstances specify wether or not to use instances to render the mesh
  104457. * @param emissiveTexture the associated emissive texture used to generate the glow
  104458. * @return true if ready otherwise, false
  104459. */
  104460. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  104461. var material = subMesh.getMaterial();
  104462. if (!material) {
  104463. return false;
  104464. }
  104465. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  104466. return false;
  104467. }
  104468. var defines = [];
  104469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104470. var mesh = subMesh.getMesh();
  104471. var uv1 = false;
  104472. var uv2 = false;
  104473. // Alpha test
  104474. if (material && material.needAlphaTesting()) {
  104475. var alphaTexture = material.getAlphaTestTexture();
  104476. if (alphaTexture) {
  104477. defines.push("#define ALPHATEST");
  104478. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104479. alphaTexture.coordinatesIndex === 1) {
  104480. defines.push("#define DIFFUSEUV2");
  104481. uv2 = true;
  104482. }
  104483. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104484. defines.push("#define DIFFUSEUV1");
  104485. uv1 = true;
  104486. }
  104487. }
  104488. }
  104489. // Emissive
  104490. if (emissiveTexture) {
  104491. defines.push("#define EMISSIVE");
  104492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104493. emissiveTexture.coordinatesIndex === 1) {
  104494. defines.push("#define EMISSIVEUV2");
  104495. uv2 = true;
  104496. }
  104497. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104498. defines.push("#define EMISSIVEUV1");
  104499. uv1 = true;
  104500. }
  104501. }
  104502. if (uv1) {
  104503. attribs.push(BABYLON.VertexBuffer.UVKind);
  104504. defines.push("#define UV1");
  104505. }
  104506. if (uv2) {
  104507. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104508. defines.push("#define UV2");
  104509. }
  104510. // Bones
  104511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104514. if (mesh.numBoneInfluencers > 4) {
  104515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104517. }
  104518. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104519. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  104520. }
  104521. else {
  104522. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104523. }
  104524. // Morph targets
  104525. var manager = mesh.morphTargetManager;
  104526. var morphInfluencers = 0;
  104527. if (manager) {
  104528. if (manager.numInfluencers > 0) {
  104529. defines.push("#define MORPHTARGETS");
  104530. morphInfluencers = manager.numInfluencers;
  104531. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  104532. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  104533. }
  104534. }
  104535. // Instances
  104536. if (useInstances) {
  104537. defines.push("#define INSTANCES");
  104538. attribs.push("world0");
  104539. attribs.push("world1");
  104540. attribs.push("world2");
  104541. attribs.push("world3");
  104542. }
  104543. // Get correct effect
  104544. var join = defines.join("\n");
  104545. if (this._cachedDefines !== join) {
  104546. this._cachedDefines = join;
  104547. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  104548. }
  104549. return this._effectLayerMapGenerationEffect.isReady();
  104550. };
  104551. /**
  104552. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  104553. */
  104554. EffectLayer.prototype.render = function () {
  104555. var currentEffect = this._mergeEffect;
  104556. // Check
  104557. if (!currentEffect.isReady())
  104558. return;
  104559. for (var i = 0; i < this._postProcesses.length; i++) {
  104560. if (!this._postProcesses[i].isReady()) {
  104561. return;
  104562. }
  104563. }
  104564. var engine = this._scene.getEngine();
  104565. this.onBeforeComposeObservable.notifyObservers(this);
  104566. // Render
  104567. engine.enableEffect(currentEffect);
  104568. engine.setState(false);
  104569. // VBOs
  104570. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104571. // Cache
  104572. var previousAlphaMode = engine.getAlphaMode();
  104573. // Go Blend.
  104574. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  104575. // Blends the map on the main canvas.
  104576. this._internalRender(currentEffect);
  104577. // Restore Alpha
  104578. engine.setAlphaMode(previousAlphaMode);
  104579. this.onAfterComposeObservable.notifyObservers(this);
  104580. // Handle size changes.
  104581. var size = this._mainTexture.getSize();
  104582. this._setMainTextureSize();
  104583. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  104584. // Recreate RTT and post processes on size change.
  104585. this.onSizeChangedObservable.notifyObservers(this);
  104586. this._disposeTextureAndPostProcesses();
  104587. this._createMainTexture();
  104588. this._createTextureAndPostProcesses();
  104589. }
  104590. };
  104591. /**
  104592. * Determine if a given mesh will be used in the current effect.
  104593. * @param mesh mesh to test
  104594. * @returns true if the mesh will be used
  104595. */
  104596. EffectLayer.prototype.hasMesh = function (mesh) {
  104597. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  104598. return true;
  104599. }
  104600. return false;
  104601. };
  104602. /**
  104603. * Returns true if the layer contains information to display, otherwise false.
  104604. * @returns true if the glow layer should be rendered
  104605. */
  104606. EffectLayer.prototype.shouldRender = function () {
  104607. return this.isEnabled && this._shouldRender;
  104608. };
  104609. /**
  104610. * Returns true if the mesh should render, otherwise false.
  104611. * @param mesh The mesh to render
  104612. * @returns true if it should render otherwise false
  104613. */
  104614. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  104615. return true;
  104616. };
  104617. /**
  104618. * Returns true if the mesh should render, otherwise false.
  104619. * @param mesh The mesh to render
  104620. * @returns true if it should render otherwise false
  104621. */
  104622. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  104623. return true;
  104624. };
  104625. /**
  104626. * Renders the submesh passed in parameter to the generation map.
  104627. */
  104628. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  104629. var _this = this;
  104630. if (!this.shouldRender()) {
  104631. return;
  104632. }
  104633. var material = subMesh.getMaterial();
  104634. var mesh = subMesh.getRenderingMesh();
  104635. var scene = this._scene;
  104636. var engine = scene.getEngine();
  104637. if (!material) {
  104638. return;
  104639. }
  104640. // Do not block in blend mode.
  104641. if (material.needAlphaBlendingForMesh(mesh)) {
  104642. return;
  104643. }
  104644. // Culling
  104645. engine.setState(material.backFaceCulling);
  104646. // Managing instances
  104647. var batch = mesh._getInstancesRenderList(subMesh._id);
  104648. if (batch.mustReturn) {
  104649. return;
  104650. }
  104651. // Early Exit per mesh
  104652. if (!this._shouldRenderMesh(mesh)) {
  104653. return;
  104654. }
  104655. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104656. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  104657. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  104658. engine.enableEffect(this._effectLayerMapGenerationEffect);
  104659. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  104660. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  104661. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  104662. // Alpha test
  104663. if (material && material.needAlphaTesting()) {
  104664. var alphaTexture = material.getAlphaTestTexture();
  104665. if (alphaTexture) {
  104666. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  104667. var textureMatrix = alphaTexture.getTextureMatrix();
  104668. if (textureMatrix) {
  104669. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  104670. }
  104671. }
  104672. }
  104673. // Glow emissive only
  104674. if (this._emissiveTextureAndColor.texture) {
  104675. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  104676. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  104677. }
  104678. // Bones
  104679. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104680. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104681. }
  104682. // Morph targets
  104683. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  104684. // Draw
  104685. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  104686. }
  104687. else {
  104688. // Need to reset refresh rate of the main map
  104689. this._mainTexture.resetRefreshCounter();
  104690. }
  104691. };
  104692. /**
  104693. * Rebuild the required buffers.
  104694. * @hidden Internal use only.
  104695. */
  104696. EffectLayer.prototype._rebuild = function () {
  104697. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104698. if (vb) {
  104699. vb._rebuild();
  104700. }
  104701. this._generateIndexBuffer();
  104702. };
  104703. /**
  104704. * Dispose only the render target textures and post process.
  104705. */
  104706. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  104707. this._mainTexture.dispose();
  104708. for (var i = 0; i < this._postProcesses.length; i++) {
  104709. if (this._postProcesses[i]) {
  104710. this._postProcesses[i].dispose();
  104711. }
  104712. }
  104713. this._postProcesses = [];
  104714. for (var i = 0; i < this._textures.length; i++) {
  104715. if (this._textures[i]) {
  104716. this._textures[i].dispose();
  104717. }
  104718. }
  104719. this._textures = [];
  104720. };
  104721. /**
  104722. * Dispose the highlight layer and free resources.
  104723. */
  104724. EffectLayer.prototype.dispose = function () {
  104725. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104726. if (vertexBuffer) {
  104727. vertexBuffer.dispose();
  104728. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104729. }
  104730. if (this._indexBuffer) {
  104731. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104732. this._indexBuffer = null;
  104733. }
  104734. // Clean textures and post processes
  104735. this._disposeTextureAndPostProcesses();
  104736. // Remove from scene
  104737. var index = this._scene.effectLayers.indexOf(this, 0);
  104738. if (index > -1) {
  104739. this._scene.effectLayers.splice(index, 1);
  104740. }
  104741. // Callback
  104742. this.onDisposeObservable.notifyObservers(this);
  104743. this.onDisposeObservable.clear();
  104744. this.onBeforeRenderMainTextureObservable.clear();
  104745. this.onBeforeComposeObservable.clear();
  104746. this.onAfterComposeObservable.clear();
  104747. this.onSizeChangedObservable.clear();
  104748. };
  104749. /**
  104750. * Gets the class name of the effect layer
  104751. * @returns the string with the class name of the effect layer
  104752. */
  104753. EffectLayer.prototype.getClassName = function () {
  104754. return "EffectLayer";
  104755. };
  104756. /**
  104757. * Creates an effect layer from parsed effect layer data
  104758. * @param parsedEffectLayer defines effect layer data
  104759. * @param scene defines the current scene
  104760. * @param rootUrl defines the root URL containing the effect layer information
  104761. * @returns a parsed effect Layer
  104762. */
  104763. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  104764. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  104765. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  104766. };
  104767. __decorate([
  104768. BABYLON.serialize()
  104769. ], EffectLayer.prototype, "name", void 0);
  104770. __decorate([
  104771. BABYLON.serializeAsColor4()
  104772. ], EffectLayer.prototype, "neutralColor", void 0);
  104773. __decorate([
  104774. BABYLON.serialize()
  104775. ], EffectLayer.prototype, "isEnabled", void 0);
  104776. __decorate([
  104777. BABYLON.serializeAsCameraReference()
  104778. ], EffectLayer.prototype, "camera", null);
  104779. __decorate([
  104780. BABYLON.serialize()
  104781. ], EffectLayer.prototype, "renderingGroupId", null);
  104782. return EffectLayer;
  104783. }());
  104784. BABYLON.EffectLayer = EffectLayer;
  104785. })(BABYLON || (BABYLON = {}));
  104786. //# sourceMappingURL=babylon.effectLayer.js.map
  104787. var BABYLON;
  104788. (function (BABYLON) {
  104789. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  104790. for (var index = 0; index < this.effectLayers.length; index++) {
  104791. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  104792. return this.effectLayers[index];
  104793. }
  104794. }
  104795. return null;
  104796. };
  104797. /**
  104798. * Special Glow Blur post process only blurring the alpha channel
  104799. * It enforces keeping the most luminous color in the color channel.
  104800. */
  104801. var GlowBlurPostProcess = /** @class */ (function (_super) {
  104802. __extends(GlowBlurPostProcess, _super);
  104803. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  104804. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  104805. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  104806. _this.direction = direction;
  104807. _this.kernel = kernel;
  104808. _this.onApplyObservable.add(function (effect) {
  104809. effect.setFloat2("screenSize", _this.width, _this.height);
  104810. effect.setVector2("direction", _this.direction);
  104811. effect.setFloat("blurWidth", _this.kernel);
  104812. });
  104813. return _this;
  104814. }
  104815. return GlowBlurPostProcess;
  104816. }(BABYLON.PostProcess));
  104817. /**
  104818. * The highlight layer Helps adding a glow effect around a mesh.
  104819. *
  104820. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  104821. * glowy meshes to your scene.
  104822. *
  104823. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  104824. */
  104825. var HighlightLayer = /** @class */ (function (_super) {
  104826. __extends(HighlightLayer, _super);
  104827. /**
  104828. * Instantiates a new highlight Layer and references it to the scene..
  104829. * @param name The name of the layer
  104830. * @param scene The scene to use the layer in
  104831. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  104832. */
  104833. function HighlightLayer(name, scene, options) {
  104834. var _this = _super.call(this, name, scene) || this;
  104835. _this.name = name;
  104836. /**
  104837. * Specifies whether or not the inner glow is ACTIVE in the layer.
  104838. */
  104839. _this.innerGlow = true;
  104840. /**
  104841. * Specifies whether or not the outer glow is ACTIVE in the layer.
  104842. */
  104843. _this.outerGlow = true;
  104844. /**
  104845. * An event triggered when the highlight layer is being blurred.
  104846. */
  104847. _this.onBeforeBlurObservable = new BABYLON.Observable();
  104848. /**
  104849. * An event triggered when the highlight layer has been blurred.
  104850. */
  104851. _this.onAfterBlurObservable = new BABYLON.Observable();
  104852. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  104853. _this._meshes = {};
  104854. _this._excludedMeshes = {};
  104855. _this.neutralColor = HighlightLayer.NeutralColor;
  104856. // Warn on stencil
  104857. if (!_this._engine.isStencilEnable) {
  104858. 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 }");
  104859. }
  104860. // Adapt options
  104861. _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);
  104862. // Initialize the layer
  104863. _this._init({
  104864. alphaBlendingMode: _this._options.alphaBlendingMode,
  104865. camera: _this._options.camera,
  104866. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  104867. mainTextureRatio: _this._options.mainTextureRatio,
  104868. renderingGroupId: _this._options.renderingGroupId
  104869. });
  104870. // Do not render as long as no meshes have been added
  104871. _this._shouldRender = false;
  104872. return _this;
  104873. }
  104874. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  104875. /**
  104876. * Gets the horizontal size of the blur.
  104877. */
  104878. get: function () {
  104879. return this._horizontalBlurPostprocess.kernel;
  104880. },
  104881. /**
  104882. * Specifies the horizontal size of the blur.
  104883. */
  104884. set: function (value) {
  104885. this._horizontalBlurPostprocess.kernel = value;
  104886. },
  104887. enumerable: true,
  104888. configurable: true
  104889. });
  104890. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  104891. /**
  104892. * Gets the vertical size of the blur.
  104893. */
  104894. get: function () {
  104895. return this._verticalBlurPostprocess.kernel;
  104896. },
  104897. /**
  104898. * Specifies the vertical size of the blur.
  104899. */
  104900. set: function (value) {
  104901. this._verticalBlurPostprocess.kernel = value;
  104902. },
  104903. enumerable: true,
  104904. configurable: true
  104905. });
  104906. /**
  104907. * Get the effect name of the layer.
  104908. * @return The effect name
  104909. */
  104910. HighlightLayer.prototype.getEffectName = function () {
  104911. return HighlightLayer.EffectName;
  104912. };
  104913. /**
  104914. * Create the merge effect. This is the shader use to blit the information back
  104915. * to the main canvas at the end of the scene rendering.
  104916. */
  104917. HighlightLayer.prototype._createMergeEffect = function () {
  104918. // Effect
  104919. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  104920. };
  104921. /**
  104922. * Creates the render target textures and post processes used in the highlight layer.
  104923. */
  104924. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  104925. var _this = this;
  104926. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  104927. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  104928. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  104929. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  104930. var textureType = 0;
  104931. if (this._engine.getCaps().textureHalfFloatRender) {
  104932. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  104933. }
  104934. else {
  104935. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104936. }
  104937. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  104938. width: blurTextureWidth,
  104939. height: blurTextureHeight
  104940. }, this._scene, false, true, textureType);
  104941. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104942. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104943. this._blurTexture.anisotropicFilteringLevel = 16;
  104944. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  104945. this._blurTexture.renderParticles = false;
  104946. this._blurTexture.ignoreCameraViewport = true;
  104947. this._textures = [this._blurTexture];
  104948. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  104949. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104950. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  104951. effect.setTexture("textureSampler", _this._mainTexture);
  104952. });
  104953. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104954. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104955. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104956. });
  104957. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104958. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  104959. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104960. });
  104961. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104962. }
  104963. else {
  104964. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  104965. width: blurTextureWidth,
  104966. height: blurTextureHeight
  104967. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104968. this._horizontalBlurPostprocess.width = blurTextureWidth;
  104969. this._horizontalBlurPostprocess.height = blurTextureHeight;
  104970. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104971. effect.setTexture("textureSampler", _this._mainTexture);
  104972. });
  104973. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  104974. width: blurTextureWidth,
  104975. height: blurTextureHeight
  104976. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104977. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104978. }
  104979. this._mainTexture.onAfterUnbindObservable.add(function () {
  104980. _this.onBeforeBlurObservable.notifyObservers(_this);
  104981. var internalTexture = _this._blurTexture.getInternalTexture();
  104982. if (internalTexture) {
  104983. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  104984. }
  104985. _this.onAfterBlurObservable.notifyObservers(_this);
  104986. });
  104987. // Prevent autoClear.
  104988. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  104989. };
  104990. /**
  104991. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  104992. */
  104993. HighlightLayer.prototype.needStencil = function () {
  104994. return true;
  104995. };
  104996. /**
  104997. * Checks for the readiness of the element composing the layer.
  104998. * @param subMesh the mesh to check for
  104999. * @param useInstances specify wether or not to use instances to render the mesh
  105000. * @param emissiveTexture the associated emissive texture used to generate the glow
  105001. * @return true if ready otherwise, false
  105002. */
  105003. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105004. var material = subMesh.getMaterial();
  105005. var mesh = subMesh.getRenderingMesh();
  105006. if (!material || !mesh || !this._meshes) {
  105007. return false;
  105008. }
  105009. var emissiveTexture = null;
  105010. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105011. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105012. emissiveTexture = material.emissiveTexture;
  105013. }
  105014. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105015. };
  105016. /**
  105017. * Implementation specific of rendering the generating effect on the main canvas.
  105018. * @param effect The effect used to render through
  105019. */
  105020. HighlightLayer.prototype._internalRender = function (effect) {
  105021. // Texture
  105022. effect.setTexture("textureSampler", this._blurTexture);
  105023. // Cache
  105024. var engine = this._engine;
  105025. var previousStencilBuffer = engine.getStencilBuffer();
  105026. var previousStencilFunction = engine.getStencilFunction();
  105027. var previousStencilMask = engine.getStencilMask();
  105028. var previousStencilOperationPass = engine.getStencilOperationPass();
  105029. var previousStencilOperationFail = engine.getStencilOperationFail();
  105030. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105031. var previousStencilReference = engine.getStencilFunctionReference();
  105032. // Stencil operations
  105033. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105034. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105035. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105036. // Draw order
  105037. engine.setStencilMask(0x00);
  105038. engine.setStencilBuffer(true);
  105039. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105040. // 2 passes inner outer
  105041. if (this.outerGlow) {
  105042. effect.setFloat("offset", 0);
  105043. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105044. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105045. }
  105046. if (this.innerGlow) {
  105047. effect.setFloat("offset", 1);
  105048. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105050. }
  105051. // Restore Cache
  105052. engine.setStencilFunction(previousStencilFunction);
  105053. engine.setStencilMask(previousStencilMask);
  105054. engine.setStencilBuffer(previousStencilBuffer);
  105055. engine.setStencilOperationPass(previousStencilOperationPass);
  105056. engine.setStencilOperationFail(previousStencilOperationFail);
  105057. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105058. engine.setStencilFunctionReference(previousStencilReference);
  105059. };
  105060. /**
  105061. * Returns true if the layer contains information to display, otherwise false.
  105062. */
  105063. HighlightLayer.prototype.shouldRender = function () {
  105064. if (_super.prototype.shouldRender.call(this)) {
  105065. return this._meshes ? true : false;
  105066. }
  105067. return false;
  105068. };
  105069. /**
  105070. * Returns true if the mesh should render, otherwise false.
  105071. * @param mesh The mesh to render
  105072. * @returns true if it should render otherwise false
  105073. */
  105074. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105075. // Excluded Mesh
  105076. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105077. return false;
  105078. }
  105079. ;
  105080. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105081. return false;
  105082. }
  105083. return true;
  105084. };
  105085. /**
  105086. * Sets the required values for both the emissive texture and and the main color.
  105087. */
  105088. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105089. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105090. if (highlightLayerMesh) {
  105091. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105092. }
  105093. else {
  105094. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105095. }
  105096. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105097. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105098. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105099. }
  105100. else {
  105101. this._emissiveTextureAndColor.texture = null;
  105102. }
  105103. };
  105104. /**
  105105. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105106. * @param mesh The mesh to exclude from the highlight layer
  105107. */
  105108. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105109. if (!this._excludedMeshes) {
  105110. return;
  105111. }
  105112. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105113. if (!meshExcluded) {
  105114. this._excludedMeshes[mesh.uniqueId] = {
  105115. mesh: mesh,
  105116. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105117. mesh.getEngine().setStencilBuffer(false);
  105118. }),
  105119. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  105120. mesh.getEngine().setStencilBuffer(true);
  105121. }),
  105122. };
  105123. }
  105124. };
  105125. /**
  105126. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  105127. * @param mesh The mesh to highlight
  105128. */
  105129. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  105130. if (!this._excludedMeshes) {
  105131. return;
  105132. }
  105133. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105134. if (meshExcluded) {
  105135. if (meshExcluded.beforeRender) {
  105136. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  105137. }
  105138. if (meshExcluded.afterRender) {
  105139. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  105140. }
  105141. }
  105142. this._excludedMeshes[mesh.uniqueId] = null;
  105143. };
  105144. /**
  105145. * Determine if a given mesh will be highlighted by the current HighlightLayer
  105146. * @param mesh mesh to test
  105147. * @returns true if the mesh will be highlighted by the current HighlightLayer
  105148. */
  105149. HighlightLayer.prototype.hasMesh = function (mesh) {
  105150. if (!this._meshes) {
  105151. return false;
  105152. }
  105153. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105154. return false;
  105155. }
  105156. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  105157. };
  105158. /**
  105159. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  105160. * @param mesh The mesh to highlight
  105161. * @param color The color of the highlight
  105162. * @param glowEmissiveOnly Extract the glow from the emissive texture
  105163. */
  105164. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  105165. var _this = this;
  105166. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  105167. if (!this._meshes) {
  105168. return;
  105169. }
  105170. var meshHighlight = this._meshes[mesh.uniqueId];
  105171. if (meshHighlight) {
  105172. meshHighlight.color = color;
  105173. }
  105174. else {
  105175. this._meshes[mesh.uniqueId] = {
  105176. mesh: mesh,
  105177. color: color,
  105178. // Lambda required for capture due to Observable this context
  105179. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  105180. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  105181. _this._defaultStencilReference(mesh);
  105182. }
  105183. else {
  105184. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  105185. }
  105186. }),
  105187. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  105188. glowEmissiveOnly: glowEmissiveOnly
  105189. };
  105190. mesh.onDisposeObservable.add(function () {
  105191. _this._disposeMesh(mesh);
  105192. });
  105193. }
  105194. this._shouldRender = true;
  105195. };
  105196. /**
  105197. * Remove a mesh from the highlight layer in order to make it stop glowing.
  105198. * @param mesh The mesh to highlight
  105199. */
  105200. HighlightLayer.prototype.removeMesh = function (mesh) {
  105201. if (!this._meshes) {
  105202. return;
  105203. }
  105204. var meshHighlight = this._meshes[mesh.uniqueId];
  105205. if (meshHighlight) {
  105206. if (meshHighlight.observerHighlight) {
  105207. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  105208. }
  105209. if (meshHighlight.observerDefault) {
  105210. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  105211. }
  105212. delete this._meshes[mesh.uniqueId];
  105213. }
  105214. this._shouldRender = false;
  105215. for (var meshHighlightToCheck in this._meshes) {
  105216. if (this._meshes[meshHighlightToCheck]) {
  105217. this._shouldRender = true;
  105218. break;
  105219. }
  105220. }
  105221. };
  105222. /**
  105223. * Force the stencil to the normal expected value for none glowing parts
  105224. */
  105225. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  105226. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  105227. };
  105228. /**
  105229. * Free any resources and references associated to a mesh.
  105230. * Internal use
  105231. * @param mesh The mesh to free.
  105232. * @hidden
  105233. */
  105234. HighlightLayer.prototype._disposeMesh = function (mesh) {
  105235. this.removeMesh(mesh);
  105236. this.removeExcludedMesh(mesh);
  105237. };
  105238. /**
  105239. * Dispose the highlight layer and free resources.
  105240. */
  105241. HighlightLayer.prototype.dispose = function () {
  105242. if (this._meshes) {
  105243. // Clean mesh references
  105244. for (var id in this._meshes) {
  105245. var meshHighlight = this._meshes[id];
  105246. if (meshHighlight && meshHighlight.mesh) {
  105247. if (meshHighlight.observerHighlight) {
  105248. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  105249. }
  105250. if (meshHighlight.observerDefault) {
  105251. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  105252. }
  105253. }
  105254. }
  105255. this._meshes = null;
  105256. }
  105257. if (this._excludedMeshes) {
  105258. for (var id in this._excludedMeshes) {
  105259. var meshHighlight = this._excludedMeshes[id];
  105260. if (meshHighlight) {
  105261. if (meshHighlight.beforeRender) {
  105262. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  105263. }
  105264. if (meshHighlight.afterRender) {
  105265. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  105266. }
  105267. }
  105268. }
  105269. this._excludedMeshes = null;
  105270. }
  105271. _super.prototype.dispose.call(this);
  105272. };
  105273. /**
  105274. * Gets the class name of the effect layer
  105275. * @returns the string with the class name of the effect layer
  105276. */
  105277. HighlightLayer.prototype.getClassName = function () {
  105278. return "HighlightLayer";
  105279. };
  105280. /**
  105281. * Serializes this Highlight layer
  105282. * @returns a serialized Highlight layer object
  105283. */
  105284. HighlightLayer.prototype.serialize = function () {
  105285. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105286. serializationObject.customType = "BABYLON.HighlightLayer";
  105287. // Highlighted meshes
  105288. serializationObject.meshes = [];
  105289. if (this._meshes) {
  105290. for (var m in this._meshes) {
  105291. var mesh = this._meshes[m];
  105292. if (mesh) {
  105293. serializationObject.meshes.push({
  105294. glowEmissiveOnly: mesh.glowEmissiveOnly,
  105295. color: mesh.color.asArray(),
  105296. meshId: mesh.mesh.id
  105297. });
  105298. }
  105299. }
  105300. }
  105301. // Excluded meshes
  105302. serializationObject.excludedMeshes = [];
  105303. if (this._excludedMeshes) {
  105304. for (var e in this._excludedMeshes) {
  105305. var excludedMesh = this._excludedMeshes[e];
  105306. if (excludedMesh) {
  105307. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  105308. }
  105309. }
  105310. }
  105311. return serializationObject;
  105312. };
  105313. /**
  105314. * Creates a Highlight layer from parsed Highlight layer data
  105315. * @param parsedHightlightLayer defines the Highlight layer data
  105316. * @param scene defines the current scene
  105317. * @param rootUrl defines the root URL containing the Highlight layer information
  105318. * @returns a parsed Highlight layer
  105319. */
  105320. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  105321. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  105322. var index;
  105323. // Excluded meshes
  105324. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  105325. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  105326. if (mesh) {
  105327. hl.addExcludedMesh(mesh);
  105328. }
  105329. }
  105330. // Included meshes
  105331. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  105332. var highlightedMesh = parsedHightlightLayer.meshes[index];
  105333. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  105334. if (mesh) {
  105335. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  105336. }
  105337. }
  105338. return hl;
  105339. };
  105340. /**
  105341. * Effect Name of the highlight layer.
  105342. */
  105343. HighlightLayer.EffectName = "HighlightLayer";
  105344. /**
  105345. * The neutral color used during the preparation of the glow effect.
  105346. * This is black by default as the blend operation is a blend operation.
  105347. */
  105348. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  105349. /**
  105350. * Stencil value used for glowing meshes.
  105351. */
  105352. HighlightLayer.GlowingMeshStencilReference = 0x02;
  105353. /**
  105354. * Stencil value used for the other meshes in the scene.
  105355. */
  105356. HighlightLayer.NormalMeshStencilReference = 0x01;
  105357. __decorate([
  105358. BABYLON.serialize()
  105359. ], HighlightLayer.prototype, "innerGlow", void 0);
  105360. __decorate([
  105361. BABYLON.serialize()
  105362. ], HighlightLayer.prototype, "outerGlow", void 0);
  105363. __decorate([
  105364. BABYLON.serialize()
  105365. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  105366. __decorate([
  105367. BABYLON.serialize()
  105368. ], HighlightLayer.prototype, "blurVerticalSize", null);
  105369. __decorate([
  105370. BABYLON.serialize("options")
  105371. ], HighlightLayer.prototype, "_options", void 0);
  105372. return HighlightLayer;
  105373. }(BABYLON.EffectLayer));
  105374. BABYLON.HighlightLayer = HighlightLayer;
  105375. })(BABYLON || (BABYLON = {}));
  105376. //# sourceMappingURL=babylon.highlightLayer.js.map
  105377. var BABYLON;
  105378. (function (BABYLON) {
  105379. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  105380. for (var index = 0; index < this.effectLayers.length; index++) {
  105381. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  105382. return this.effectLayers[index];
  105383. }
  105384. }
  105385. return null;
  105386. };
  105387. /**
  105388. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  105389. *
  105390. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105391. * glowy meshes to your scene.
  105392. *
  105393. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  105394. */
  105395. var GlowLayer = /** @class */ (function (_super) {
  105396. __extends(GlowLayer, _super);
  105397. /**
  105398. * Instantiates a new glow Layer and references it to the scene.
  105399. * @param name The name of the layer
  105400. * @param scene The scene to use the layer in
  105401. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  105402. */
  105403. function GlowLayer(name, scene, options) {
  105404. var _this = _super.call(this, name, scene) || this;
  105405. _this._intensity = 1.0;
  105406. _this._includedOnlyMeshes = [];
  105407. _this._excludedMeshes = [];
  105408. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  105409. // Adapt options
  105410. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  105411. // Initialize the layer
  105412. _this._init({
  105413. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  105414. camera: _this._options.camera,
  105415. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105416. mainTextureRatio: _this._options.mainTextureRatio,
  105417. renderingGroupId: _this._options.renderingGroupId
  105418. });
  105419. return _this;
  105420. }
  105421. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  105422. /**
  105423. * Gets the kernel size of the blur.
  105424. */
  105425. get: function () {
  105426. return this._horizontalBlurPostprocess1.kernel;
  105427. },
  105428. /**
  105429. * Sets the kernel size of the blur.
  105430. */
  105431. set: function (value) {
  105432. this._horizontalBlurPostprocess1.kernel = value;
  105433. this._verticalBlurPostprocess1.kernel = value;
  105434. this._horizontalBlurPostprocess2.kernel = value;
  105435. this._verticalBlurPostprocess2.kernel = value;
  105436. },
  105437. enumerable: true,
  105438. configurable: true
  105439. });
  105440. Object.defineProperty(GlowLayer.prototype, "intensity", {
  105441. /**
  105442. * Gets the glow intensity.
  105443. */
  105444. get: function () {
  105445. return this._intensity;
  105446. },
  105447. /**
  105448. * Sets the glow intensity.
  105449. */
  105450. set: function (value) {
  105451. this._intensity = value;
  105452. },
  105453. enumerable: true,
  105454. configurable: true
  105455. });
  105456. /**
  105457. * Get the effect name of the layer.
  105458. * @return The effect name
  105459. */
  105460. GlowLayer.prototype.getEffectName = function () {
  105461. return GlowLayer.EffectName;
  105462. };
  105463. /**
  105464. * Create the merge effect. This is the shader use to blit the information back
  105465. * to the main canvas at the end of the scene rendering.
  105466. */
  105467. GlowLayer.prototype._createMergeEffect = function () {
  105468. // Effect
  105469. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  105470. };
  105471. /**
  105472. * Creates the render target textures and post processes used in the glow layer.
  105473. */
  105474. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  105475. var _this = this;
  105476. var blurTextureWidth = this._mainTextureDesiredSize.width;
  105477. var blurTextureHeight = this._mainTextureDesiredSize.height;
  105478. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105479. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105480. var textureType = 0;
  105481. if (this._engine.getCaps().textureHalfFloatRender) {
  105482. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105483. }
  105484. else {
  105485. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105486. }
  105487. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  105488. width: blurTextureWidth,
  105489. height: blurTextureHeight
  105490. }, this._scene, false, true, textureType);
  105491. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105492. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105493. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105494. this._blurTexture1.renderParticles = false;
  105495. this._blurTexture1.ignoreCameraViewport = true;
  105496. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  105497. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  105498. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  105499. width: blurTextureWidth2,
  105500. height: blurTextureHeight2
  105501. }, this._scene, false, true, textureType);
  105502. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105503. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105504. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105505. this._blurTexture2.renderParticles = false;
  105506. this._blurTexture2.ignoreCameraViewport = true;
  105507. this._textures = [this._blurTexture1, this._blurTexture2];
  105508. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105509. width: blurTextureWidth,
  105510. height: blurTextureHeight
  105511. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105512. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  105513. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  105514. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  105515. effect.setTexture("textureSampler", _this._mainTexture);
  105516. });
  105517. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105518. width: blurTextureWidth,
  105519. height: blurTextureHeight
  105520. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105521. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105522. width: blurTextureWidth2,
  105523. height: blurTextureHeight2
  105524. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105525. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  105526. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  105527. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  105528. effect.setTexture("textureSampler", _this._blurTexture1);
  105529. });
  105530. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105531. width: blurTextureWidth2,
  105532. height: blurTextureHeight2
  105533. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105534. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105535. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  105536. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105537. this._mainTexture.samples = this._options.mainTextureSamples;
  105538. this._mainTexture.onAfterUnbindObservable.add(function () {
  105539. var internalTexture = _this._blurTexture1.getInternalTexture();
  105540. if (internalTexture) {
  105541. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  105542. internalTexture = _this._blurTexture2.getInternalTexture();
  105543. if (internalTexture) {
  105544. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  105545. }
  105546. }
  105547. });
  105548. // Prevent autoClear.
  105549. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105550. };
  105551. /**
  105552. * Checks for the readiness of the element composing the layer.
  105553. * @param subMesh the mesh to check for
  105554. * @param useInstances specify wether or not to use instances to render the mesh
  105555. * @param emissiveTexture the associated emissive texture used to generate the glow
  105556. * @return true if ready otherwise, false
  105557. */
  105558. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  105559. var material = subMesh.getMaterial();
  105560. var mesh = subMesh.getRenderingMesh();
  105561. if (!material || !mesh) {
  105562. return false;
  105563. }
  105564. var emissiveTexture = material.emissiveTexture;
  105565. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105566. };
  105567. /**
  105568. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105569. */
  105570. GlowLayer.prototype.needStencil = function () {
  105571. return false;
  105572. };
  105573. /**
  105574. * Implementation specific of rendering the generating effect on the main canvas.
  105575. * @param effect The effect used to render through
  105576. */
  105577. GlowLayer.prototype._internalRender = function (effect) {
  105578. // Texture
  105579. effect.setTexture("textureSampler", this._blurTexture1);
  105580. effect.setTexture("textureSampler2", this._blurTexture2);
  105581. effect.setFloat("offset", this._intensity);
  105582. // Cache
  105583. var engine = this._engine;
  105584. var previousStencilBuffer = engine.getStencilBuffer();
  105585. // Draw order
  105586. engine.setStencilBuffer(false);
  105587. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105588. // Draw order
  105589. engine.setStencilBuffer(previousStencilBuffer);
  105590. };
  105591. /**
  105592. * Sets the required values for both the emissive texture and and the main color.
  105593. */
  105594. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105595. var textureLevel = 1.0;
  105596. if (this.customEmissiveTextureSelector) {
  105597. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  105598. }
  105599. else {
  105600. if (material) {
  105601. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105602. if (this._emissiveTextureAndColor.texture) {
  105603. textureLevel = this._emissiveTextureAndColor.texture.level;
  105604. }
  105605. }
  105606. else {
  105607. this._emissiveTextureAndColor.texture = null;
  105608. }
  105609. }
  105610. if (this.customEmissiveColorSelector) {
  105611. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  105612. }
  105613. else {
  105614. if (material.emissiveColor) {
  105615. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  105616. }
  105617. else {
  105618. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105619. }
  105620. }
  105621. };
  105622. /**
  105623. * Returns true if the mesh should render, otherwise false.
  105624. * @param mesh The mesh to render
  105625. * @returns true if it should render otherwise false
  105626. */
  105627. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  105628. return this.hasMesh(mesh);
  105629. };
  105630. /**
  105631. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  105632. * @param mesh The mesh to exclude from the glow layer
  105633. */
  105634. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  105635. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  105636. this._excludedMeshes.push(mesh.uniqueId);
  105637. }
  105638. };
  105639. /**
  105640. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  105641. * @param mesh The mesh to remove
  105642. */
  105643. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  105644. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  105645. if (index !== -1) {
  105646. this._excludedMeshes.splice(index, 1);
  105647. }
  105648. };
  105649. /**
  105650. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  105651. * @param mesh The mesh to include in the glow layer
  105652. */
  105653. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  105654. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  105655. this._includedOnlyMeshes.push(mesh.uniqueId);
  105656. }
  105657. };
  105658. /**
  105659. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  105660. * @param mesh The mesh to remove
  105661. */
  105662. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  105663. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  105664. if (index !== -1) {
  105665. this._includedOnlyMeshes.splice(index, 1);
  105666. }
  105667. };
  105668. /**
  105669. * Determine if a given mesh will be used in the glow layer
  105670. * @param mesh The mesh to test
  105671. * @returns true if the mesh will be highlighted by the current glow layer
  105672. */
  105673. GlowLayer.prototype.hasMesh = function (mesh) {
  105674. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105675. return false;
  105676. }
  105677. // Included Mesh
  105678. if (this._includedOnlyMeshes.length) {
  105679. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  105680. }
  105681. ;
  105682. // Excluded Mesh
  105683. if (this._excludedMeshes.length) {
  105684. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  105685. }
  105686. ;
  105687. return true;
  105688. };
  105689. /**
  105690. * Free any resources and references associated to a mesh.
  105691. * Internal use
  105692. * @param mesh The mesh to free.
  105693. * @hidden
  105694. */
  105695. GlowLayer.prototype._disposeMesh = function (mesh) {
  105696. this.removeIncludedOnlyMesh(mesh);
  105697. this.removeExcludedMesh(mesh);
  105698. };
  105699. /**
  105700. * Gets the class name of the effect layer
  105701. * @returns the string with the class name of the effect layer
  105702. */
  105703. GlowLayer.prototype.getClassName = function () {
  105704. return "GlowLayer";
  105705. };
  105706. /**
  105707. * Serializes this glow layer
  105708. * @returns a serialized glow layer object
  105709. */
  105710. GlowLayer.prototype.serialize = function () {
  105711. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105712. serializationObject.customType = "BABYLON.GlowLayer";
  105713. var index;
  105714. // Included meshes
  105715. serializationObject.includedMeshes = [];
  105716. if (this._includedOnlyMeshes.length) {
  105717. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  105718. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  105719. if (mesh) {
  105720. serializationObject.includedMeshes.push(mesh.id);
  105721. }
  105722. }
  105723. }
  105724. // Excluded meshes
  105725. serializationObject.excludedMeshes = [];
  105726. if (this._excludedMeshes.length) {
  105727. for (index = 0; index < this._excludedMeshes.length; index++) {
  105728. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  105729. if (mesh) {
  105730. serializationObject.excludedMeshes.push(mesh.id);
  105731. }
  105732. }
  105733. }
  105734. return serializationObject;
  105735. };
  105736. /**
  105737. * Creates a Glow Layer from parsed glow layer data
  105738. * @param parsedGlowLayer defines glow layer data
  105739. * @param scene defines the current scene
  105740. * @param rootUrl defines the root URL containing the glow layer information
  105741. * @returns a parsed Glow Layer
  105742. */
  105743. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  105744. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  105745. var index;
  105746. // Excluded meshes
  105747. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  105748. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  105749. if (mesh) {
  105750. gl.addExcludedMesh(mesh);
  105751. }
  105752. }
  105753. // Included meshes
  105754. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  105755. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  105756. if (mesh) {
  105757. gl.addIncludedOnlyMesh(mesh);
  105758. }
  105759. }
  105760. return gl;
  105761. };
  105762. /**
  105763. * Effect Name of the layer.
  105764. */
  105765. GlowLayer.EffectName = "GlowLayer";
  105766. /**
  105767. * The default blur kernel size used for the glow.
  105768. */
  105769. GlowLayer.DefaultBlurKernelSize = 32;
  105770. /**
  105771. * The default texture size ratio used for the glow.
  105772. */
  105773. GlowLayer.DefaultTextureRatio = 0.5;
  105774. __decorate([
  105775. BABYLON.serialize()
  105776. ], GlowLayer.prototype, "blurKernelSize", null);
  105777. __decorate([
  105778. BABYLON.serialize()
  105779. ], GlowLayer.prototype, "intensity", null);
  105780. __decorate([
  105781. BABYLON.serialize("options")
  105782. ], GlowLayer.prototype, "_options", void 0);
  105783. return GlowLayer;
  105784. }(BABYLON.EffectLayer));
  105785. BABYLON.GlowLayer = GlowLayer;
  105786. })(BABYLON || (BABYLON = {}));
  105787. //# sourceMappingURL=babylon.glowLayer.js.map
  105788. var BABYLON;
  105789. (function (BABYLON) {
  105790. /**
  105791. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  105792. */
  105793. var AssetTaskState;
  105794. (function (AssetTaskState) {
  105795. /**
  105796. * Initialization
  105797. */
  105798. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  105799. /**
  105800. * Running
  105801. */
  105802. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  105803. /**
  105804. * Done
  105805. */
  105806. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  105807. /**
  105808. * Error
  105809. */
  105810. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  105811. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  105812. /**
  105813. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  105814. */
  105815. var AbstractAssetTask = /** @class */ (function () {
  105816. /**
  105817. * Creates a new {BABYLON.AssetsManager}
  105818. * @param name defines the name of the task
  105819. */
  105820. function AbstractAssetTask(
  105821. /**
  105822. * Task name
  105823. */ name) {
  105824. this.name = name;
  105825. this._isCompleted = false;
  105826. this._taskState = AssetTaskState.INIT;
  105827. }
  105828. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  105829. /**
  105830. * Get if the task is completed
  105831. */
  105832. get: function () {
  105833. return this._isCompleted;
  105834. },
  105835. enumerable: true,
  105836. configurable: true
  105837. });
  105838. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  105839. /**
  105840. * Gets the current state of the task
  105841. */
  105842. get: function () {
  105843. return this._taskState;
  105844. },
  105845. enumerable: true,
  105846. configurable: true
  105847. });
  105848. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  105849. /**
  105850. * Gets the current error object (if task is in error)
  105851. */
  105852. get: function () {
  105853. return this._errorObject;
  105854. },
  105855. enumerable: true,
  105856. configurable: true
  105857. });
  105858. /**
  105859. * Internal only
  105860. * @hidden
  105861. */
  105862. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  105863. if (this._errorObject) {
  105864. return;
  105865. }
  105866. this._errorObject = {
  105867. message: message,
  105868. exception: exception
  105869. };
  105870. };
  105871. /**
  105872. * Execute the current task
  105873. * @param scene defines the scene where you want your assets to be loaded
  105874. * @param onSuccess is a callback called when the task is successfully executed
  105875. * @param onError is a callback called if an error occurs
  105876. */
  105877. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  105878. var _this = this;
  105879. this._taskState = AssetTaskState.RUNNING;
  105880. this.runTask(scene, function () {
  105881. _this.onDoneCallback(onSuccess, onError);
  105882. }, function (msg, exception) {
  105883. _this.onErrorCallback(onError, msg, exception);
  105884. });
  105885. };
  105886. /**
  105887. * Execute the current task
  105888. * @param scene defines the scene where you want your assets to be loaded
  105889. * @param onSuccess is a callback called when the task is successfully executed
  105890. * @param onError is a callback called if an error occurs
  105891. */
  105892. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105893. throw new Error("runTask is not implemented");
  105894. };
  105895. /**
  105896. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  105897. * This can be used with failed tasks that have the reason for failure fixed.
  105898. */
  105899. AbstractAssetTask.prototype.reset = function () {
  105900. this._taskState = AssetTaskState.INIT;
  105901. };
  105902. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  105903. this._taskState = AssetTaskState.ERROR;
  105904. this._errorObject = {
  105905. message: message,
  105906. exception: exception
  105907. };
  105908. if (this.onError) {
  105909. this.onError(this, message, exception);
  105910. }
  105911. onError();
  105912. };
  105913. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  105914. try {
  105915. this._taskState = AssetTaskState.DONE;
  105916. this._isCompleted = true;
  105917. if (this.onSuccess) {
  105918. this.onSuccess(this);
  105919. }
  105920. onSuccess();
  105921. }
  105922. catch (e) {
  105923. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  105924. }
  105925. };
  105926. return AbstractAssetTask;
  105927. }());
  105928. BABYLON.AbstractAssetTask = AbstractAssetTask;
  105929. /**
  105930. * Class used to share progress information about assets loading
  105931. */
  105932. var AssetsProgressEvent = /** @class */ (function () {
  105933. /**
  105934. * Creates a {BABYLON.AssetsProgressEvent}
  105935. * @param remainingCount defines the number of remaining tasks to process
  105936. * @param totalCount defines the total number of tasks
  105937. * @param task defines the task that was just processed
  105938. */
  105939. function AssetsProgressEvent(remainingCount, totalCount, task) {
  105940. this.remainingCount = remainingCount;
  105941. this.totalCount = totalCount;
  105942. this.task = task;
  105943. }
  105944. return AssetsProgressEvent;
  105945. }());
  105946. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  105947. /**
  105948. * Define a task used by {BABYLON.AssetsManager} to load meshes
  105949. */
  105950. var MeshAssetTask = /** @class */ (function (_super) {
  105951. __extends(MeshAssetTask, _super);
  105952. /**
  105953. * Creates a new {BABYLON.MeshAssetTask}
  105954. * @param name defines the name of the task
  105955. * @param meshesNames defines the list of mesh's names you want to load
  105956. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  105957. * @param sceneFilename defines the filename of the scene to load from
  105958. */
  105959. function MeshAssetTask(
  105960. /**
  105961. * Defines the name of the task
  105962. */
  105963. name,
  105964. /**
  105965. * Defines the list of mesh's names you want to load
  105966. */
  105967. meshesNames,
  105968. /**
  105969. * Defines the root url to use as a base to load your meshes and associated resources
  105970. */
  105971. rootUrl,
  105972. /**
  105973. * Defines the filename of the scene to load from
  105974. */
  105975. sceneFilename) {
  105976. var _this = _super.call(this, name) || this;
  105977. _this.name = name;
  105978. _this.meshesNames = meshesNames;
  105979. _this.rootUrl = rootUrl;
  105980. _this.sceneFilename = sceneFilename;
  105981. return _this;
  105982. }
  105983. /**
  105984. * Execute the current task
  105985. * @param scene defines the scene where you want your assets to be loaded
  105986. * @param onSuccess is a callback called when the task is successfully executed
  105987. * @param onError is a callback called if an error occurs
  105988. */
  105989. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105990. var _this = this;
  105991. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  105992. _this.loadedMeshes = meshes;
  105993. _this.loadedParticleSystems = particleSystems;
  105994. _this.loadedSkeletons = skeletons;
  105995. onSuccess();
  105996. }, null, function (scene, message, exception) {
  105997. onError(message, exception);
  105998. });
  105999. };
  106000. return MeshAssetTask;
  106001. }(AbstractAssetTask));
  106002. BABYLON.MeshAssetTask = MeshAssetTask;
  106003. /**
  106004. * Define a task used by {BABYLON.AssetsManager} to load text content
  106005. */
  106006. var TextFileAssetTask = /** @class */ (function (_super) {
  106007. __extends(TextFileAssetTask, _super);
  106008. /**
  106009. * Creates a new TextFileAssetTask object
  106010. * @param name defines the name of the task
  106011. * @param url defines the location of the file to load
  106012. */
  106013. function TextFileAssetTask(
  106014. /**
  106015. * Defines the name of the task
  106016. */
  106017. name,
  106018. /**
  106019. * Defines the location of the file to load
  106020. */
  106021. url) {
  106022. var _this = _super.call(this, name) || this;
  106023. _this.name = name;
  106024. _this.url = url;
  106025. return _this;
  106026. }
  106027. /**
  106028. * Execute the current task
  106029. * @param scene defines the scene where you want your assets to be loaded
  106030. * @param onSuccess is a callback called when the task is successfully executed
  106031. * @param onError is a callback called if an error occurs
  106032. */
  106033. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106034. var _this = this;
  106035. scene._loadFile(this.url, function (data) {
  106036. _this.text = data;
  106037. onSuccess();
  106038. }, undefined, false, false, function (request, exception) {
  106039. if (request) {
  106040. onError(request.status + " " + request.statusText, exception);
  106041. }
  106042. });
  106043. };
  106044. return TextFileAssetTask;
  106045. }(AbstractAssetTask));
  106046. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106047. /**
  106048. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106049. */
  106050. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106051. __extends(BinaryFileAssetTask, _super);
  106052. /**
  106053. * Creates a new BinaryFileAssetTask object
  106054. * @param name defines the name of the new task
  106055. * @param url defines the location of the file to load
  106056. */
  106057. function BinaryFileAssetTask(
  106058. /**
  106059. * Defines the name of the task
  106060. */
  106061. name,
  106062. /**
  106063. * Defines the location of the file to load
  106064. */
  106065. url) {
  106066. var _this = _super.call(this, name) || this;
  106067. _this.name = name;
  106068. _this.url = url;
  106069. return _this;
  106070. }
  106071. /**
  106072. * Execute the current task
  106073. * @param scene defines the scene where you want your assets to be loaded
  106074. * @param onSuccess is a callback called when the task is successfully executed
  106075. * @param onError is a callback called if an error occurs
  106076. */
  106077. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106078. var _this = this;
  106079. scene._loadFile(this.url, function (data) {
  106080. _this.data = data;
  106081. onSuccess();
  106082. }, undefined, true, true, function (request, exception) {
  106083. if (request) {
  106084. onError(request.status + " " + request.statusText, exception);
  106085. }
  106086. });
  106087. };
  106088. return BinaryFileAssetTask;
  106089. }(AbstractAssetTask));
  106090. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106091. /**
  106092. * Define a task used by {BABYLON.AssetsManager} to load images
  106093. */
  106094. var ImageAssetTask = /** @class */ (function (_super) {
  106095. __extends(ImageAssetTask, _super);
  106096. /**
  106097. * Creates a new ImageAssetTask
  106098. * @param name defines the name of the task
  106099. * @param url defines the location of the image to load
  106100. */
  106101. function ImageAssetTask(
  106102. /**
  106103. * Defines the name of the task
  106104. */
  106105. name,
  106106. /**
  106107. * Defines the location of the image to load
  106108. */
  106109. url) {
  106110. var _this = _super.call(this, name) || this;
  106111. _this.name = name;
  106112. _this.url = url;
  106113. return _this;
  106114. }
  106115. /**
  106116. * Execute the current task
  106117. * @param scene defines the scene where you want your assets to be loaded
  106118. * @param onSuccess is a callback called when the task is successfully executed
  106119. * @param onError is a callback called if an error occurs
  106120. */
  106121. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106122. var _this = this;
  106123. var img = new Image();
  106124. BABYLON.Tools.SetCorsBehavior(this.url, img);
  106125. img.onload = function () {
  106126. _this.image = img;
  106127. onSuccess();
  106128. };
  106129. img.onerror = function (err) {
  106130. onError("Error loading image", err);
  106131. };
  106132. img.src = this.url;
  106133. };
  106134. return ImageAssetTask;
  106135. }(AbstractAssetTask));
  106136. BABYLON.ImageAssetTask = ImageAssetTask;
  106137. /**
  106138. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  106139. */
  106140. var TextureAssetTask = /** @class */ (function (_super) {
  106141. __extends(TextureAssetTask, _super);
  106142. /**
  106143. * Creates a new TextureAssetTask object
  106144. * @param name defines the name of the task
  106145. * @param url defines the location of the file to load
  106146. * @param noMipmap defines if mipmap should not be generated (default is false)
  106147. * @param invertY defines if texture must be inverted on Y axis (default is false)
  106148. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  106149. */
  106150. function TextureAssetTask(
  106151. /**
  106152. * Defines the name of the task
  106153. */
  106154. name,
  106155. /**
  106156. * Defines the location of the file to load
  106157. */
  106158. url,
  106159. /**
  106160. * Defines if mipmap should not be generated (default is false)
  106161. */
  106162. noMipmap,
  106163. /**
  106164. * Defines if texture must be inverted on Y axis (default is false)
  106165. */
  106166. invertY,
  106167. /**
  106168. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  106169. */
  106170. samplingMode) {
  106171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106172. var _this = _super.call(this, name) || this;
  106173. _this.name = name;
  106174. _this.url = url;
  106175. _this.noMipmap = noMipmap;
  106176. _this.invertY = invertY;
  106177. _this.samplingMode = samplingMode;
  106178. return _this;
  106179. }
  106180. /**
  106181. * Execute the current task
  106182. * @param scene defines the scene where you want your assets to be loaded
  106183. * @param onSuccess is a callback called when the task is successfully executed
  106184. * @param onError is a callback called if an error occurs
  106185. */
  106186. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106187. var onload = function () {
  106188. onSuccess();
  106189. };
  106190. var onerror = function (message, exception) {
  106191. onError(message, exception);
  106192. };
  106193. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  106194. };
  106195. return TextureAssetTask;
  106196. }(AbstractAssetTask));
  106197. BABYLON.TextureAssetTask = TextureAssetTask;
  106198. /**
  106199. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  106200. */
  106201. var CubeTextureAssetTask = /** @class */ (function (_super) {
  106202. __extends(CubeTextureAssetTask, _super);
  106203. /**
  106204. * Creates a new CubeTextureAssetTask
  106205. * @param name defines the name of the task
  106206. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  106207. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  106208. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106209. * @param files defines the explicit list of files (undefined by default)
  106210. */
  106211. function CubeTextureAssetTask(
  106212. /**
  106213. * Defines the name of the task
  106214. */
  106215. name,
  106216. /**
  106217. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  106218. */
  106219. url,
  106220. /**
  106221. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  106222. */
  106223. extensions,
  106224. /**
  106225. * Defines if mipmaps should not be generated (default is false)
  106226. */
  106227. noMipmap,
  106228. /**
  106229. * Defines the explicit list of files (undefined by default)
  106230. */
  106231. files) {
  106232. var _this = _super.call(this, name) || this;
  106233. _this.name = name;
  106234. _this.url = url;
  106235. _this.extensions = extensions;
  106236. _this.noMipmap = noMipmap;
  106237. _this.files = files;
  106238. return _this;
  106239. }
  106240. /**
  106241. * Execute the current task
  106242. * @param scene defines the scene where you want your assets to be loaded
  106243. * @param onSuccess is a callback called when the task is successfully executed
  106244. * @param onError is a callback called if an error occurs
  106245. */
  106246. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106247. var onload = function () {
  106248. onSuccess();
  106249. };
  106250. var onerror = function (message, exception) {
  106251. onError(message, exception);
  106252. };
  106253. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  106254. };
  106255. return CubeTextureAssetTask;
  106256. }(AbstractAssetTask));
  106257. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  106258. /**
  106259. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  106260. */
  106261. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  106262. __extends(HDRCubeTextureAssetTask, _super);
  106263. /**
  106264. * Creates a new HDRCubeTextureAssetTask object
  106265. * @param name defines the name of the task
  106266. * @param url defines the location of the file to load
  106267. * @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.
  106268. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106269. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106270. * @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)
  106271. * @param reserved Internal use only
  106272. */
  106273. function HDRCubeTextureAssetTask(
  106274. /**
  106275. * Defines the name of the task
  106276. */
  106277. name,
  106278. /**
  106279. * Defines the location of the file to load
  106280. */
  106281. url,
  106282. /**
  106283. * Defines the desired size (the more it increases the longer the generation will be)
  106284. */
  106285. size,
  106286. /**
  106287. * Defines if mipmaps should not be generated (default is false)
  106288. */
  106289. noMipmap,
  106290. /**
  106291. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106292. */
  106293. generateHarmonics,
  106294. /**
  106295. * 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)
  106296. */
  106297. gammaSpace,
  106298. /**
  106299. * Internal Use Only
  106300. */
  106301. reserved) {
  106302. if (noMipmap === void 0) { noMipmap = false; }
  106303. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106304. if (gammaSpace === void 0) { gammaSpace = false; }
  106305. if (reserved === void 0) { reserved = false; }
  106306. var _this = _super.call(this, name) || this;
  106307. _this.name = name;
  106308. _this.url = url;
  106309. _this.size = size;
  106310. _this.noMipmap = noMipmap;
  106311. _this.generateHarmonics = generateHarmonics;
  106312. _this.gammaSpace = gammaSpace;
  106313. _this.reserved = reserved;
  106314. return _this;
  106315. }
  106316. /**
  106317. * Execute the current task
  106318. * @param scene defines the scene where you want your assets to be loaded
  106319. * @param onSuccess is a callback called when the task is successfully executed
  106320. * @param onError is a callback called if an error occurs
  106321. */
  106322. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106323. var onload = function () {
  106324. onSuccess();
  106325. };
  106326. var onerror = function (message, exception) {
  106327. onError(message, exception);
  106328. };
  106329. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  106330. };
  106331. return HDRCubeTextureAssetTask;
  106332. }(AbstractAssetTask));
  106333. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  106334. /**
  106335. * This class can be used to easily import assets into a scene
  106336. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  106337. */
  106338. var AssetsManager = /** @class */ (function () {
  106339. /**
  106340. * Creates a new AssetsManager
  106341. * @param scene defines the scene to work on
  106342. */
  106343. function AssetsManager(scene) {
  106344. this._isLoading = false;
  106345. this._tasks = new Array();
  106346. this._waitingTasksCount = 0;
  106347. this._totalTasksCount = 0;
  106348. /**
  106349. * Observable called when all tasks are processed
  106350. */
  106351. this.onTaskSuccessObservable = new BABYLON.Observable();
  106352. /**
  106353. * Observable called when a task had an error
  106354. */
  106355. this.onTaskErrorObservable = new BABYLON.Observable();
  106356. /**
  106357. * Observable called when a task is successful
  106358. */
  106359. this.onTasksDoneObservable = new BABYLON.Observable();
  106360. /**
  106361. * Observable called when a task is done (whatever the result is)
  106362. */
  106363. this.onProgressObservable = new BABYLON.Observable();
  106364. /**
  106365. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  106366. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  106367. */
  106368. this.useDefaultLoadingScreen = true;
  106369. this._scene = scene;
  106370. }
  106371. /**
  106372. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  106373. * @param taskName defines the name of the new task
  106374. * @param meshesNames defines the name of meshes to load
  106375. * @param rootUrl defines the root url to use to locate files
  106376. * @param sceneFilename defines the filename of the scene file
  106377. * @returns a new {BABYLON.MeshAssetTask} object
  106378. */
  106379. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  106380. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  106381. this._tasks.push(task);
  106382. return task;
  106383. };
  106384. /**
  106385. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  106386. * @param taskName defines the name of the new task
  106387. * @param url defines the url of the file to load
  106388. * @returns a new {BABYLON.TextFileAssetTask} object
  106389. */
  106390. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  106391. var task = new TextFileAssetTask(taskName, url);
  106392. this._tasks.push(task);
  106393. return task;
  106394. };
  106395. /**
  106396. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  106397. * @param taskName defines the name of the new task
  106398. * @param url defines the url of the file to load
  106399. * @returns a new {BABYLON.BinaryFileAssetTask} object
  106400. */
  106401. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  106402. var task = new BinaryFileAssetTask(taskName, url);
  106403. this._tasks.push(task);
  106404. return task;
  106405. };
  106406. /**
  106407. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  106408. * @param taskName defines the name of the new task
  106409. * @param url defines the url of the file to load
  106410. * @returns a new {BABYLON.ImageAssetTask} object
  106411. */
  106412. AssetsManager.prototype.addImageTask = function (taskName, url) {
  106413. var task = new ImageAssetTask(taskName, url);
  106414. this._tasks.push(task);
  106415. return task;
  106416. };
  106417. /**
  106418. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  106419. * @param taskName defines the name of the new task
  106420. * @param url defines the url of the file to load
  106421. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106422. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  106423. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  106424. * @returns a new {BABYLON.TextureAssetTask} object
  106425. */
  106426. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  106427. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106428. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  106429. this._tasks.push(task);
  106430. return task;
  106431. };
  106432. /**
  106433. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  106434. * @param taskName defines the name of the new task
  106435. * @param url defines the url of the file to load
  106436. * @param extensions defines the extension to use to load the cube map (can be null)
  106437. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106438. * @param files defines the list of files to load (can be null)
  106439. * @returns a new {BABYLON.CubeTextureAssetTask} object
  106440. */
  106441. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  106442. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  106443. this._tasks.push(task);
  106444. return task;
  106445. };
  106446. /**
  106447. *
  106448. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  106449. * @param taskName defines the name of the new task
  106450. * @param url defines the url of the file to load
  106451. * @param size defines the size you want for the cubemap (can be null)
  106452. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106453. * @param generateHarmonics defines if you want to automatically generate (true by default)
  106454. * @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)
  106455. * @param reserved Internal use only
  106456. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  106457. */
  106458. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  106459. if (noMipmap === void 0) { noMipmap = false; }
  106460. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106461. if (gammaSpace === void 0) { gammaSpace = false; }
  106462. if (reserved === void 0) { reserved = false; }
  106463. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  106464. this._tasks.push(task);
  106465. return task;
  106466. };
  106467. /**
  106468. * Remove a task from the assets manager.
  106469. * @param task the task to remove
  106470. */
  106471. AssetsManager.prototype.removeTask = function (task) {
  106472. var index = this._tasks.indexOf(task);
  106473. if (index > -1) {
  106474. this._tasks.splice(index, 1);
  106475. }
  106476. };
  106477. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  106478. this._waitingTasksCount--;
  106479. try {
  106480. if (this.onProgress) {
  106481. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  106482. }
  106483. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  106484. }
  106485. catch (e) {
  106486. BABYLON.Tools.Error("Error running progress callbacks.");
  106487. console.log(e);
  106488. }
  106489. if (this._waitingTasksCount === 0) {
  106490. try {
  106491. if (this.onFinish) {
  106492. this.onFinish(this._tasks);
  106493. }
  106494. // Let's remove successfull tasks
  106495. var currentTasks = this._tasks.slice();
  106496. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  106497. var task = currentTasks_1[_i];
  106498. if (task.taskState === AssetTaskState.DONE) {
  106499. var index = this._tasks.indexOf(task);
  106500. if (index > -1) {
  106501. this._tasks.splice(index, 1);
  106502. }
  106503. }
  106504. }
  106505. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106506. }
  106507. catch (e) {
  106508. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  106509. console.log(e);
  106510. }
  106511. this._isLoading = false;
  106512. this._scene.getEngine().hideLoadingUI();
  106513. }
  106514. };
  106515. AssetsManager.prototype._runTask = function (task) {
  106516. var _this = this;
  106517. var done = function () {
  106518. try {
  106519. if (_this.onTaskSuccess) {
  106520. _this.onTaskSuccess(task);
  106521. }
  106522. _this.onTaskSuccessObservable.notifyObservers(task);
  106523. _this._decreaseWaitingTasksCount(task);
  106524. }
  106525. catch (e) {
  106526. error("Error executing task success callbacks", e);
  106527. }
  106528. };
  106529. var error = function (message, exception) {
  106530. task._setErrorObject(message, exception);
  106531. if (_this.onTaskError) {
  106532. _this.onTaskError(task);
  106533. }
  106534. _this.onTaskErrorObservable.notifyObservers(task);
  106535. _this._decreaseWaitingTasksCount(task);
  106536. };
  106537. task.run(this._scene, done, error);
  106538. };
  106539. /**
  106540. * Reset the {BABYLON.AssetsManager} and remove all tasks
  106541. * @return the current instance of the {BABYLON.AssetsManager}
  106542. */
  106543. AssetsManager.prototype.reset = function () {
  106544. this._isLoading = false;
  106545. this._tasks = new Array();
  106546. return this;
  106547. };
  106548. /**
  106549. * Start the loading process
  106550. * @return the current instance of the {BABYLON.AssetsManager}
  106551. */
  106552. AssetsManager.prototype.load = function () {
  106553. if (this._isLoading) {
  106554. return this;
  106555. }
  106556. this._isLoading = true;
  106557. this._waitingTasksCount = this._tasks.length;
  106558. this._totalTasksCount = this._tasks.length;
  106559. if (this._waitingTasksCount === 0) {
  106560. this._isLoading = false;
  106561. if (this.onFinish) {
  106562. this.onFinish(this._tasks);
  106563. }
  106564. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106565. return this;
  106566. }
  106567. if (this.useDefaultLoadingScreen) {
  106568. this._scene.getEngine().displayLoadingUI();
  106569. }
  106570. for (var index = 0; index < this._tasks.length; index++) {
  106571. var task = this._tasks[index];
  106572. if (task.taskState === AssetTaskState.INIT) {
  106573. this._runTask(task);
  106574. }
  106575. }
  106576. return this;
  106577. };
  106578. return AssetsManager;
  106579. }());
  106580. BABYLON.AssetsManager = AssetsManager;
  106581. })(BABYLON || (BABYLON = {}));
  106582. //# sourceMappingURL=babylon.assetsManager.js.map
  106583. var BABYLON;
  106584. (function (BABYLON) {
  106585. var serializedGeometries = [];
  106586. var serializeGeometry = function (geometry, serializationGeometries) {
  106587. if (serializedGeometries[geometry.id]) {
  106588. return;
  106589. }
  106590. if (geometry.doNotSerialize) {
  106591. return;
  106592. }
  106593. if (geometry instanceof BABYLON.BoxGeometry) {
  106594. serializationGeometries.boxes.push(geometry.serialize());
  106595. }
  106596. else if (geometry instanceof BABYLON.SphereGeometry) {
  106597. serializationGeometries.spheres.push(geometry.serialize());
  106598. }
  106599. else if (geometry instanceof BABYLON.CylinderGeometry) {
  106600. serializationGeometries.cylinders.push(geometry.serialize());
  106601. }
  106602. else if (geometry instanceof BABYLON.TorusGeometry) {
  106603. serializationGeometries.toruses.push(geometry.serialize());
  106604. }
  106605. else if (geometry instanceof BABYLON.GroundGeometry) {
  106606. serializationGeometries.grounds.push(geometry.serialize());
  106607. }
  106608. else if (geometry instanceof BABYLON.Plane) {
  106609. serializationGeometries.planes.push(geometry.serialize());
  106610. }
  106611. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  106612. serializationGeometries.torusKnots.push(geometry.serialize());
  106613. }
  106614. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  106615. throw new Error("Unknown primitive type");
  106616. }
  106617. else {
  106618. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  106619. }
  106620. serializedGeometries[geometry.id] = true;
  106621. };
  106622. var serializeMesh = function (mesh, serializationScene) {
  106623. var serializationObject = {};
  106624. // Geometry
  106625. var geometry = mesh._geometry;
  106626. if (geometry) {
  106627. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  106628. // 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
  106629. serializeGeometry(geometry, serializationScene.geometries);
  106630. }
  106631. }
  106632. // Custom
  106633. if (mesh.serialize) {
  106634. mesh.serialize(serializationObject);
  106635. }
  106636. return serializationObject;
  106637. };
  106638. var finalizeSingleMesh = function (mesh, serializationObject) {
  106639. //only works if the mesh is already loaded
  106640. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106641. //serialize material
  106642. if (mesh.material) {
  106643. if (mesh.material instanceof BABYLON.MultiMaterial) {
  106644. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  106645. serializationObject.materials = serializationObject.materials || [];
  106646. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106647. serializationObject.multiMaterials.push(mesh.material.serialize());
  106648. var _loop_1 = function (submaterial) {
  106649. if (submaterial) {
  106650. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  106651. serializationObject.materials.push(submaterial.serialize());
  106652. }
  106653. }
  106654. };
  106655. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  106656. var submaterial = _a[_i];
  106657. _loop_1(submaterial);
  106658. }
  106659. }
  106660. }
  106661. else {
  106662. serializationObject.materials = serializationObject.materials || [];
  106663. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106664. serializationObject.materials.push(mesh.material.serialize());
  106665. }
  106666. }
  106667. }
  106668. //serialize geometry
  106669. var geometry = mesh._geometry;
  106670. if (geometry) {
  106671. if (!serializationObject.geometries) {
  106672. serializationObject.geometries = {};
  106673. serializationObject.geometries.boxes = [];
  106674. serializationObject.geometries.spheres = [];
  106675. serializationObject.geometries.cylinders = [];
  106676. serializationObject.geometries.toruses = [];
  106677. serializationObject.geometries.grounds = [];
  106678. serializationObject.geometries.planes = [];
  106679. serializationObject.geometries.torusKnots = [];
  106680. serializationObject.geometries.vertexData = [];
  106681. }
  106682. serializeGeometry(geometry, serializationObject.geometries);
  106683. }
  106684. // Skeletons
  106685. if (mesh.skeleton) {
  106686. serializationObject.skeletons = serializationObject.skeletons || [];
  106687. serializationObject.skeletons.push(mesh.skeleton.serialize());
  106688. }
  106689. //serialize the actual mesh
  106690. serializationObject.meshes = serializationObject.meshes || [];
  106691. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106692. }
  106693. };
  106694. var SceneSerializer = /** @class */ (function () {
  106695. function SceneSerializer() {
  106696. }
  106697. SceneSerializer.ClearCache = function () {
  106698. serializedGeometries = [];
  106699. };
  106700. SceneSerializer.Serialize = function (scene) {
  106701. var serializationObject = {};
  106702. SceneSerializer.ClearCache();
  106703. // Scene
  106704. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  106705. serializationObject.autoClear = scene.autoClear;
  106706. serializationObject.clearColor = scene.clearColor.asArray();
  106707. serializationObject.ambientColor = scene.ambientColor.asArray();
  106708. serializationObject.gravity = scene.gravity.asArray();
  106709. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  106710. serializationObject.workerCollisions = scene.workerCollisions;
  106711. // Fog
  106712. if (scene.fogMode && scene.fogMode !== 0) {
  106713. serializationObject.fogMode = scene.fogMode;
  106714. serializationObject.fogColor = scene.fogColor.asArray();
  106715. serializationObject.fogStart = scene.fogStart;
  106716. serializationObject.fogEnd = scene.fogEnd;
  106717. serializationObject.fogDensity = scene.fogDensity;
  106718. }
  106719. //Physics
  106720. if (scene.isPhysicsEnabled()) {
  106721. var physicEngine = scene.getPhysicsEngine();
  106722. if (physicEngine) {
  106723. serializationObject.physicsEnabled = true;
  106724. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  106725. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  106726. }
  106727. }
  106728. // Metadata
  106729. if (scene.metadata) {
  106730. serializationObject.metadata = scene.metadata;
  106731. }
  106732. // Morph targets
  106733. serializationObject.morphTargetManagers = [];
  106734. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  106735. var abstractMesh = _a[_i];
  106736. var manager = abstractMesh.morphTargetManager;
  106737. if (manager) {
  106738. serializationObject.morphTargetManagers.push(manager.serialize());
  106739. }
  106740. }
  106741. // Lights
  106742. serializationObject.lights = [];
  106743. var index;
  106744. var light;
  106745. for (index = 0; index < scene.lights.length; index++) {
  106746. light = scene.lights[index];
  106747. if (!light.doNotSerialize) {
  106748. serializationObject.lights.push(light.serialize());
  106749. }
  106750. }
  106751. // Cameras
  106752. serializationObject.cameras = [];
  106753. for (index = 0; index < scene.cameras.length; index++) {
  106754. var camera = scene.cameras[index];
  106755. if (!camera.doNotSerialize) {
  106756. serializationObject.cameras.push(camera.serialize());
  106757. }
  106758. }
  106759. if (scene.activeCamera) {
  106760. serializationObject.activeCameraID = scene.activeCamera.id;
  106761. }
  106762. // Animations
  106763. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  106764. // Materials
  106765. serializationObject.materials = [];
  106766. serializationObject.multiMaterials = [];
  106767. var material;
  106768. for (index = 0; index < scene.materials.length; index++) {
  106769. material = scene.materials[index];
  106770. if (!material.doNotSerialize) {
  106771. serializationObject.materials.push(material.serialize());
  106772. }
  106773. }
  106774. // MultiMaterials
  106775. serializationObject.multiMaterials = [];
  106776. for (index = 0; index < scene.multiMaterials.length; index++) {
  106777. var multiMaterial = scene.multiMaterials[index];
  106778. serializationObject.multiMaterials.push(multiMaterial.serialize());
  106779. }
  106780. // Environment texture
  106781. if (scene.environmentTexture) {
  106782. serializationObject.environmentTexture = scene.environmentTexture.name;
  106783. }
  106784. // Skeletons
  106785. serializationObject.skeletons = [];
  106786. for (index = 0; index < scene.skeletons.length; index++) {
  106787. var skeleton = scene.skeletons[index];
  106788. if (!skeleton.doNotSerialize) {
  106789. serializationObject.skeletons.push(skeleton.serialize());
  106790. }
  106791. }
  106792. // Transform nodes
  106793. serializationObject.transformNodes = [];
  106794. for (index = 0; index < scene.transformNodes.length; index++) {
  106795. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  106796. }
  106797. // Geometries
  106798. serializationObject.geometries = {};
  106799. serializationObject.geometries.boxes = [];
  106800. serializationObject.geometries.spheres = [];
  106801. serializationObject.geometries.cylinders = [];
  106802. serializationObject.geometries.toruses = [];
  106803. serializationObject.geometries.grounds = [];
  106804. serializationObject.geometries.planes = [];
  106805. serializationObject.geometries.torusKnots = [];
  106806. serializationObject.geometries.vertexData = [];
  106807. serializedGeometries = [];
  106808. var geometries = scene.getGeometries();
  106809. for (index = 0; index < geometries.length; index++) {
  106810. var geometry = geometries[index];
  106811. if (geometry.isReady()) {
  106812. serializeGeometry(geometry, serializationObject.geometries);
  106813. }
  106814. }
  106815. // Meshes
  106816. serializationObject.meshes = [];
  106817. for (index = 0; index < scene.meshes.length; index++) {
  106818. var abstractMesh = scene.meshes[index];
  106819. if (abstractMesh instanceof BABYLON.Mesh) {
  106820. var mesh = abstractMesh;
  106821. if (!mesh.doNotSerialize) {
  106822. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106823. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106824. }
  106825. }
  106826. }
  106827. }
  106828. // Particles Systems
  106829. serializationObject.particleSystems = [];
  106830. for (index = 0; index < scene.particleSystems.length; index++) {
  106831. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  106832. }
  106833. // Action Manager
  106834. if (scene.actionManager) {
  106835. serializationObject.actions = scene.actionManager.serialize("scene");
  106836. }
  106837. // Components
  106838. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  106839. var component = _c[_b];
  106840. component.serialize(serializationObject);
  106841. }
  106842. return serializationObject;
  106843. };
  106844. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  106845. if (withParents === void 0) { withParents = false; }
  106846. if (withChildren === void 0) { withChildren = false; }
  106847. var serializationObject = {};
  106848. SceneSerializer.ClearCache();
  106849. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  106850. if (withParents || withChildren) {
  106851. //deliberate for loop! not for each, appended should be processed as well.
  106852. for (var i = 0; i < toSerialize.length; ++i) {
  106853. if (withChildren) {
  106854. toSerialize[i].getDescendants().forEach(function (node) {
  106855. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  106856. toSerialize.push(node);
  106857. }
  106858. });
  106859. }
  106860. //make sure the array doesn't contain the object already
  106861. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  106862. toSerialize.push(toSerialize[i].parent);
  106863. }
  106864. }
  106865. }
  106866. toSerialize.forEach(function (mesh) {
  106867. finalizeSingleMesh(mesh, serializationObject);
  106868. });
  106869. return serializationObject;
  106870. };
  106871. return SceneSerializer;
  106872. }());
  106873. BABYLON.SceneSerializer = SceneSerializer;
  106874. })(BABYLON || (BABYLON = {}));
  106875. //# sourceMappingURL=babylon.sceneSerializer.js.map
  106876. var BABYLON;
  106877. (function (BABYLON) {
  106878. /**
  106879. * Class used to generate realtime reflection / refraction cube textures
  106880. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  106881. */
  106882. var ReflectionProbe = /** @class */ (function () {
  106883. /**
  106884. * Creates a new reflection probe
  106885. * @param name defines the name of the probe
  106886. * @param size defines the texture resolution (for each face)
  106887. * @param scene defines the hosting scene
  106888. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  106889. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  106890. */
  106891. function ReflectionProbe(
  106892. /** defines the name of the probe */
  106893. name, size, scene, generateMipMaps, useFloat) {
  106894. if (generateMipMaps === void 0) { generateMipMaps = true; }
  106895. if (useFloat === void 0) { useFloat = false; }
  106896. var _this = this;
  106897. this.name = name;
  106898. this._viewMatrix = BABYLON.Matrix.Identity();
  106899. this._target = BABYLON.Vector3.Zero();
  106900. this._add = BABYLON.Vector3.Zero();
  106901. this._invertYAxis = false;
  106902. /** Gets or sets probe position (center of the cube map) */
  106903. this.position = BABYLON.Vector3.Zero();
  106904. this._scene = scene;
  106905. // Create the scene field if not exist.
  106906. if (!this._scene.reflectionProbes) {
  106907. this._scene.reflectionProbes = new Array();
  106908. }
  106909. this._scene.reflectionProbes.push(this);
  106910. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  106911. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  106912. switch (faceIndex) {
  106913. case 0:
  106914. _this._add.copyFromFloats(1, 0, 0);
  106915. break;
  106916. case 1:
  106917. _this._add.copyFromFloats(-1, 0, 0);
  106918. break;
  106919. case 2:
  106920. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  106921. break;
  106922. case 3:
  106923. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  106924. break;
  106925. case 4:
  106926. _this._add.copyFromFloats(0, 0, 1);
  106927. break;
  106928. case 5:
  106929. _this._add.copyFromFloats(0, 0, -1);
  106930. break;
  106931. }
  106932. if (_this._attachedMesh) {
  106933. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  106934. }
  106935. _this.position.addToRef(_this._add, _this._target);
  106936. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  106937. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  106938. scene._forcedViewPosition = _this.position;
  106939. });
  106940. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  106941. scene._forcedViewPosition = null;
  106942. scene.updateTransformMatrix(true);
  106943. });
  106944. if (scene.activeCamera) {
  106945. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  106946. }
  106947. }
  106948. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  106949. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  106950. get: function () {
  106951. return this._renderTargetTexture.samples;
  106952. },
  106953. set: function (value) {
  106954. this._renderTargetTexture.samples = value;
  106955. },
  106956. enumerable: true,
  106957. configurable: true
  106958. });
  106959. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  106960. /** Gets or sets the refresh rate to use (on every frame by default) */
  106961. get: function () {
  106962. return this._renderTargetTexture.refreshRate;
  106963. },
  106964. set: function (value) {
  106965. this._renderTargetTexture.refreshRate = value;
  106966. },
  106967. enumerable: true,
  106968. configurable: true
  106969. });
  106970. /**
  106971. * Gets the hosting scene
  106972. * @returns a Scene
  106973. */
  106974. ReflectionProbe.prototype.getScene = function () {
  106975. return this._scene;
  106976. };
  106977. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  106978. /** Gets the internal CubeTexture used to render to */
  106979. get: function () {
  106980. return this._renderTargetTexture;
  106981. },
  106982. enumerable: true,
  106983. configurable: true
  106984. });
  106985. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  106986. /** Gets the list of meshes to render */
  106987. get: function () {
  106988. return this._renderTargetTexture.renderList;
  106989. },
  106990. enumerable: true,
  106991. configurable: true
  106992. });
  106993. /**
  106994. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  106995. * @param mesh defines the mesh to attach to
  106996. */
  106997. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  106998. this._attachedMesh = mesh;
  106999. };
  107000. /**
  107001. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107002. * @param renderingGroupId The rendering group id corresponding to its index
  107003. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107004. */
  107005. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107006. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107007. };
  107008. /**
  107009. * Clean all associated resources
  107010. */
  107011. ReflectionProbe.prototype.dispose = function () {
  107012. var index = this._scene.reflectionProbes.indexOf(this);
  107013. if (index !== -1) {
  107014. // Remove from the scene if found
  107015. this._scene.reflectionProbes.splice(index, 1);
  107016. }
  107017. if (this._renderTargetTexture) {
  107018. this._renderTargetTexture.dispose();
  107019. this._renderTargetTexture = null;
  107020. }
  107021. };
  107022. return ReflectionProbe;
  107023. }());
  107024. BABYLON.ReflectionProbe = ReflectionProbe;
  107025. })(BABYLON || (BABYLON = {}));
  107026. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107027. var BABYLON;
  107028. (function (BABYLON) {
  107029. /**
  107030. * Defines the layer scene component responsible to manage any layers
  107031. * in a given scene.
  107032. */
  107033. var LayerSceneComponent = /** @class */ (function () {
  107034. /**
  107035. * Creates a new instance of the component for the given scene
  107036. * @param scene Defines the scene to register the component in
  107037. */
  107038. function LayerSceneComponent(scene) {
  107039. /**
  107040. * The component name helpfull to identify the component in the list of scene components.
  107041. */
  107042. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107043. this.scene = scene;
  107044. this._engine = scene.getEngine();
  107045. scene.layers = new Array();
  107046. }
  107047. /**
  107048. * Registers the component in a given scene
  107049. */
  107050. LayerSceneComponent.prototype.register = function () {
  107051. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107052. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107053. };
  107054. /**
  107055. * Rebuilds the elements related to this component in case of
  107056. * context lost for instance.
  107057. */
  107058. LayerSceneComponent.prototype.rebuild = function () {
  107059. var layers = this.scene.layers;
  107060. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107061. var layer = layers_1[_i];
  107062. layer._rebuild();
  107063. }
  107064. };
  107065. /**
  107066. * Disposes the component and the associated ressources.
  107067. */
  107068. LayerSceneComponent.prototype.dispose = function () {
  107069. var layers = this.scene.layers;
  107070. while (layers.length) {
  107071. layers[0].dispose();
  107072. }
  107073. };
  107074. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107075. var layers = this.scene.layers;
  107076. if (layers.length) {
  107077. this._engine.setDepthBuffer(false);
  107078. var cameraLayerMask = camera.layerMask;
  107079. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107080. var layer = layers_2[_i];
  107081. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107082. layer.render();
  107083. }
  107084. }
  107085. this._engine.setDepthBuffer(true);
  107086. }
  107087. };
  107088. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107089. this._draw(camera, true);
  107090. };
  107091. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107092. this._draw(camera, false);
  107093. };
  107094. return LayerSceneComponent;
  107095. }());
  107096. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107097. })(BABYLON || (BABYLON = {}));
  107098. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107099. var BABYLON;
  107100. (function (BABYLON) {
  107101. var Layer = /** @class */ (function () {
  107102. function Layer(name, imgUrl, scene, isBackground, color) {
  107103. this.name = name;
  107104. this.scale = new BABYLON.Vector2(1, 1);
  107105. this.offset = new BABYLON.Vector2(0, 0);
  107106. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  107107. this.layerMask = 0x0FFFFFFF;
  107108. this._vertexBuffers = {};
  107109. // Events
  107110. /**
  107111. * An event triggered when the layer is disposed.
  107112. */
  107113. this.onDisposeObservable = new BABYLON.Observable();
  107114. /**
  107115. * An event triggered before rendering the scene
  107116. */
  107117. this.onBeforeRenderObservable = new BABYLON.Observable();
  107118. /**
  107119. * An event triggered after rendering the scene
  107120. */
  107121. this.onAfterRenderObservable = new BABYLON.Observable();
  107122. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  107123. this.isBackground = isBackground === undefined ? true : isBackground;
  107124. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  107125. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  107126. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  107127. if (!layerComponent) {
  107128. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  107129. this._scene._addComponent(layerComponent);
  107130. }
  107131. this._scene.layers.push(this);
  107132. var engine = this._scene.getEngine();
  107133. // VBO
  107134. var vertices = [];
  107135. vertices.push(1, 1);
  107136. vertices.push(-1, 1);
  107137. vertices.push(-1, -1);
  107138. vertices.push(1, -1);
  107139. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107140. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107141. this._createIndexBuffer();
  107142. // Effects
  107143. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  107144. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  107145. }
  107146. Object.defineProperty(Layer.prototype, "onDispose", {
  107147. set: function (callback) {
  107148. if (this._onDisposeObserver) {
  107149. this.onDisposeObservable.remove(this._onDisposeObserver);
  107150. }
  107151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  107152. },
  107153. enumerable: true,
  107154. configurable: true
  107155. });
  107156. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  107157. set: function (callback) {
  107158. if (this._onBeforeRenderObserver) {
  107159. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  107160. }
  107161. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  107162. },
  107163. enumerable: true,
  107164. configurable: true
  107165. });
  107166. Object.defineProperty(Layer.prototype, "onAfterRender", {
  107167. set: function (callback) {
  107168. if (this._onAfterRenderObserver) {
  107169. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107170. }
  107171. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  107172. },
  107173. enumerable: true,
  107174. configurable: true
  107175. });
  107176. Layer.prototype._createIndexBuffer = function () {
  107177. var engine = this._scene.getEngine();
  107178. // Indices
  107179. var indices = [];
  107180. indices.push(0);
  107181. indices.push(1);
  107182. indices.push(2);
  107183. indices.push(0);
  107184. indices.push(2);
  107185. indices.push(3);
  107186. this._indexBuffer = engine.createIndexBuffer(indices);
  107187. };
  107188. /** @hidden */
  107189. Layer.prototype._rebuild = function () {
  107190. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107191. if (vb) {
  107192. vb._rebuild();
  107193. }
  107194. this._createIndexBuffer();
  107195. };
  107196. Layer.prototype.render = function () {
  107197. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  107198. // Check
  107199. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  107200. return;
  107201. var engine = this._scene.getEngine();
  107202. this.onBeforeRenderObservable.notifyObservers(this);
  107203. // Render
  107204. engine.enableEffect(currentEffect);
  107205. engine.setState(false);
  107206. // Texture
  107207. currentEffect.setTexture("textureSampler", this.texture);
  107208. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  107209. // Color
  107210. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  107211. // Scale / offset
  107212. currentEffect.setVector2("offset", this.offset);
  107213. currentEffect.setVector2("scale", this.scale);
  107214. // VBOs
  107215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107216. // Draw order
  107217. if (!this.alphaTest) {
  107218. engine.setAlphaMode(this.alphaBlendingMode);
  107219. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107220. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107221. }
  107222. else {
  107223. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107224. }
  107225. this.onAfterRenderObservable.notifyObservers(this);
  107226. };
  107227. Layer.prototype.dispose = function () {
  107228. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107229. if (vertexBuffer) {
  107230. vertexBuffer.dispose();
  107231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107232. }
  107233. if (this._indexBuffer) {
  107234. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107235. this._indexBuffer = null;
  107236. }
  107237. if (this.texture) {
  107238. this.texture.dispose();
  107239. this.texture = null;
  107240. }
  107241. // Remove from scene
  107242. var index = this._scene.layers.indexOf(this);
  107243. this._scene.layers.splice(index, 1);
  107244. // Callback
  107245. this.onDisposeObservable.notifyObservers(this);
  107246. this.onDisposeObservable.clear();
  107247. this.onAfterRenderObservable.clear();
  107248. this.onBeforeRenderObservable.clear();
  107249. };
  107250. return Layer;
  107251. }());
  107252. BABYLON.Layer = Layer;
  107253. })(BABYLON || (BABYLON = {}));
  107254. //# sourceMappingURL=babylon.layer.js.map
  107255. var BABYLON;
  107256. (function (BABYLON) {
  107257. var TextureTools = /** @class */ (function () {
  107258. function TextureTools() {
  107259. }
  107260. /**
  107261. * Uses the GPU to create a copy texture rescaled at a given size
  107262. * @param texture Texture to copy from
  107263. * @param width Desired width
  107264. * @param height Desired height
  107265. * @return Generated texture
  107266. */
  107267. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  107268. if (useBilinearMode === void 0) { useBilinearMode = true; }
  107269. var scene = texture.getScene();
  107270. var engine = scene.getEngine();
  107271. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  107272. rtt.wrapU = texture.wrapU;
  107273. rtt.wrapV = texture.wrapV;
  107274. rtt.uOffset = texture.uOffset;
  107275. rtt.vOffset = texture.vOffset;
  107276. rtt.uScale = texture.uScale;
  107277. rtt.vScale = texture.vScale;
  107278. rtt.uAng = texture.uAng;
  107279. rtt.vAng = texture.vAng;
  107280. rtt.wAng = texture.wAng;
  107281. rtt.coordinatesIndex = texture.coordinatesIndex;
  107282. rtt.level = texture.level;
  107283. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  107284. rtt._texture.isReady = false;
  107285. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107286. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107287. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107288. passPostProcess.getEffect().executeWhenCompiled(function () {
  107289. passPostProcess.onApply = function (effect) {
  107290. effect.setTexture("textureSampler", texture);
  107291. };
  107292. var internalTexture = rtt.getInternalTexture();
  107293. if (internalTexture) {
  107294. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  107295. engine.unBindFramebuffer(internalTexture);
  107296. rtt.disposeFramebufferObjects();
  107297. passPostProcess.dispose();
  107298. internalTexture.isReady = true;
  107299. }
  107300. });
  107301. return rtt;
  107302. };
  107303. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  107304. if (!scene._environmentBRDFTexture) {
  107305. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107306. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107307. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107308. scene._environmentBRDFTexture = texture;
  107309. }
  107310. return scene._environmentBRDFTexture;
  107311. };
  107312. 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=";
  107313. return TextureTools;
  107314. }());
  107315. BABYLON.TextureTools = TextureTools;
  107316. })(BABYLON || (BABYLON = {}));
  107317. //# sourceMappingURL=babylon.textureTools.js.map
  107318. var BABYLON;
  107319. (function (BABYLON) {
  107320. /**
  107321. * 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.
  107322. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  107323. */
  107324. var FramingBehavior = /** @class */ (function () {
  107325. function FramingBehavior() {
  107326. this._mode = FramingBehavior.FitFrustumSidesMode;
  107327. this._radiusScale = 1.0;
  107328. this._positionScale = 0.5;
  107329. this._defaultElevation = 0.3;
  107330. this._elevationReturnTime = 1500;
  107331. this._elevationReturnWaitTime = 1000;
  107332. this._zoomStopsAnimation = false;
  107333. this._framingTime = 1500;
  107334. /**
  107335. * Define if the behavior should automatically change the configured
  107336. * camera limits and sensibilities.
  107337. */
  107338. this.autoCorrectCameraLimitsAndSensibility = true;
  107339. this._isPointerDown = false;
  107340. this._lastInteractionTime = -Infinity;
  107341. // Framing control
  107342. this._animatables = new Array();
  107343. this._betaIsAnimating = false;
  107344. }
  107345. Object.defineProperty(FramingBehavior.prototype, "name", {
  107346. /**
  107347. * Gets the name of the behavior.
  107348. */
  107349. get: function () {
  107350. return "Framing";
  107351. },
  107352. enumerable: true,
  107353. configurable: true
  107354. });
  107355. Object.defineProperty(FramingBehavior.prototype, "mode", {
  107356. /**
  107357. * Gets current mode used by the behavior.
  107358. */
  107359. get: function () {
  107360. return this._mode;
  107361. },
  107362. /**
  107363. * Sets the current mode used by the behavior
  107364. */
  107365. set: function (mode) {
  107366. this._mode = mode;
  107367. },
  107368. enumerable: true,
  107369. configurable: true
  107370. });
  107371. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  107372. /**
  107373. * Gets the scale applied to the radius
  107374. */
  107375. get: function () {
  107376. return this._radiusScale;
  107377. },
  107378. /**
  107379. * Sets the scale applied to the radius (1 by default)
  107380. */
  107381. set: function (radius) {
  107382. this._radiusScale = radius;
  107383. },
  107384. enumerable: true,
  107385. configurable: true
  107386. });
  107387. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  107388. /**
  107389. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107390. */
  107391. get: function () {
  107392. return this._positionScale;
  107393. },
  107394. /**
  107395. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107396. */
  107397. set: function (scale) {
  107398. this._positionScale = scale;
  107399. },
  107400. enumerable: true,
  107401. configurable: true
  107402. });
  107403. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  107404. /**
  107405. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107406. * behaviour is triggered, in radians.
  107407. */
  107408. get: function () {
  107409. return this._defaultElevation;
  107410. },
  107411. /**
  107412. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107413. * behaviour is triggered, in radians.
  107414. */
  107415. set: function (elevation) {
  107416. this._defaultElevation = elevation;
  107417. },
  107418. enumerable: true,
  107419. configurable: true
  107420. });
  107421. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  107422. /**
  107423. * Gets the time (in milliseconds) taken to return to the default beta position.
  107424. * Negative value indicates camera should not return to default.
  107425. */
  107426. get: function () {
  107427. return this._elevationReturnTime;
  107428. },
  107429. /**
  107430. * Sets the time (in milliseconds) taken to return to the default beta position.
  107431. * Negative value indicates camera should not return to default.
  107432. */
  107433. set: function (speed) {
  107434. this._elevationReturnTime = speed;
  107435. },
  107436. enumerable: true,
  107437. configurable: true
  107438. });
  107439. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  107440. /**
  107441. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107442. */
  107443. get: function () {
  107444. return this._elevationReturnWaitTime;
  107445. },
  107446. /**
  107447. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107448. */
  107449. set: function (time) {
  107450. this._elevationReturnWaitTime = time;
  107451. },
  107452. enumerable: true,
  107453. configurable: true
  107454. });
  107455. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  107456. /**
  107457. * Gets the flag that indicates if user zooming should stop animation.
  107458. */
  107459. get: function () {
  107460. return this._zoomStopsAnimation;
  107461. },
  107462. /**
  107463. * Sets the flag that indicates if user zooming should stop animation.
  107464. */
  107465. set: function (flag) {
  107466. this._zoomStopsAnimation = flag;
  107467. },
  107468. enumerable: true,
  107469. configurable: true
  107470. });
  107471. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  107472. /**
  107473. * Gets the transition time when framing the mesh, in milliseconds
  107474. */
  107475. get: function () {
  107476. return this._framingTime;
  107477. },
  107478. /**
  107479. * Sets the transition time when framing the mesh, in milliseconds
  107480. */
  107481. set: function (time) {
  107482. this._framingTime = time;
  107483. },
  107484. enumerable: true,
  107485. configurable: true
  107486. });
  107487. /**
  107488. * Initializes the behavior.
  107489. */
  107490. FramingBehavior.prototype.init = function () {
  107491. // Do notihng
  107492. };
  107493. /**
  107494. * Attaches the behavior to its arc rotate camera.
  107495. * @param camera Defines the camera to attach the behavior to
  107496. */
  107497. FramingBehavior.prototype.attach = function (camera) {
  107498. var _this = this;
  107499. this._attachedCamera = camera;
  107500. var scene = this._attachedCamera.getScene();
  107501. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  107502. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107503. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107504. _this._isPointerDown = true;
  107505. return;
  107506. }
  107507. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107508. _this._isPointerDown = false;
  107509. }
  107510. });
  107511. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107512. if (mesh) {
  107513. _this.zoomOnMesh(mesh);
  107514. }
  107515. });
  107516. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107517. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107518. _this._applyUserInteraction();
  107519. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  107520. // back to the default position after a given timeout
  107521. _this._maintainCameraAboveGround();
  107522. });
  107523. };
  107524. /**
  107525. * Detaches the behavior from its current arc rotate camera.
  107526. */
  107527. FramingBehavior.prototype.detach = function () {
  107528. if (!this._attachedCamera) {
  107529. return;
  107530. }
  107531. var scene = this._attachedCamera.getScene();
  107532. if (this._onPrePointerObservableObserver) {
  107533. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107534. }
  107535. if (this._onAfterCheckInputsObserver) {
  107536. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107537. }
  107538. if (this._onMeshTargetChangedObserver) {
  107539. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107540. }
  107541. this._attachedCamera = null;
  107542. };
  107543. /**
  107544. * Targets the given mesh and updates zoom level accordingly.
  107545. * @param mesh The mesh to target.
  107546. * @param radius Optional. If a cached radius position already exists, overrides default.
  107547. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107548. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107549. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107550. */
  107551. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107552. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107553. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107554. mesh.computeWorldMatrix(true);
  107555. var boundingBox = mesh.getBoundingInfo().boundingBox;
  107556. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  107557. };
  107558. /**
  107559. * Targets the given mesh with its children and updates zoom level accordingly.
  107560. * @param mesh The mesh to target.
  107561. * @param radius Optional. If a cached radius position already exists, overrides default.
  107562. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107563. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107564. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107565. */
  107566. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107567. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107568. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107569. mesh.computeWorldMatrix(true);
  107570. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  107571. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  107572. };
  107573. /**
  107574. * Targets the given meshes with their children and updates zoom level accordingly.
  107575. * @param meshes The mesh to target.
  107576. * @param radius Optional. If a cached radius position already exists, overrides default.
  107577. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107578. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107579. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107580. */
  107581. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  107582. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107583. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107584. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  107585. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  107586. for (var i = 0; i < meshes.length; i++) {
  107587. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  107588. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  107589. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  107590. }
  107591. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  107592. };
  107593. /**
  107594. * Targets the given mesh and updates zoom level accordingly.
  107595. * @param mesh The mesh to target.
  107596. * @param radius Optional. If a cached radius position already exists, overrides default.
  107597. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107598. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107599. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107600. */
  107601. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  107602. var _this = this;
  107603. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107604. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107605. var zoomTarget;
  107606. if (!this._attachedCamera) {
  107607. return;
  107608. }
  107609. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  107610. var bottom = minimumWorld.y;
  107611. var top = maximumWorld.y;
  107612. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  107613. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  107614. if (focusOnOriginXZ) {
  107615. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  107616. }
  107617. else {
  107618. var centerWorld = minimumWorld.add(radiusWorld);
  107619. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  107620. }
  107621. if (!this._vectorTransition) {
  107622. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  107623. }
  107624. this._betaIsAnimating = true;
  107625. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  107626. if (animatable) {
  107627. this._animatables.push(animatable);
  107628. }
  107629. // sets the radius and lower radius bounds
  107630. // Small delta ensures camera is not always at lower zoom limit.
  107631. var radius = 0;
  107632. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  107633. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107634. if (this.autoCorrectCameraLimitsAndSensibility) {
  107635. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  107636. }
  107637. radius = position;
  107638. }
  107639. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107640. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107641. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  107642. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  107643. }
  107644. }
  107645. // Set sensibilities
  107646. if (this.autoCorrectCameraLimitsAndSensibility) {
  107647. var extend = maximumWorld.subtract(minimumWorld).length();
  107648. this._attachedCamera.panningSensibility = 5000 / extend;
  107649. this._attachedCamera.wheelPrecision = 100 / radius;
  107650. }
  107651. // transition to new radius
  107652. if (!this._radiusTransition) {
  107653. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107654. }
  107655. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  107656. _this.stopAllAnimations();
  107657. if (onAnimationEnd) {
  107658. onAnimationEnd();
  107659. }
  107660. if (_this._attachedCamera) {
  107661. _this._attachedCamera.storeState();
  107662. }
  107663. });
  107664. if (animatable) {
  107665. this._animatables.push(animatable);
  107666. }
  107667. };
  107668. /**
  107669. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  107670. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  107671. * frustum width.
  107672. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  107673. * to fully enclose the mesh in the viewing frustum.
  107674. */
  107675. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  107676. var size = maximumWorld.subtract(minimumWorld);
  107677. var boxVectorGlobalDiagonal = size.length();
  107678. var frustumSlope = this._getFrustumSlope();
  107679. // Formula for setting distance
  107680. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  107681. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  107682. // Horizon distance
  107683. var radius = radiusWithoutFraming * this._radiusScale;
  107684. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  107685. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  107686. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  107687. var camera = this._attachedCamera;
  107688. if (!camera) {
  107689. return 0;
  107690. }
  107691. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107692. // Don't exceed the requested limit
  107693. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  107694. }
  107695. // Don't exceed the upper radius limit
  107696. if (camera.upperRadiusLimit) {
  107697. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  107698. }
  107699. return distance;
  107700. };
  107701. /**
  107702. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  107703. * is automatically returned to its default position (expected to be above ground plane).
  107704. */
  107705. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  107706. var _this = this;
  107707. if (this._elevationReturnTime < 0) {
  107708. return;
  107709. }
  107710. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  107711. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  107712. var limitBeta = Math.PI * 0.5;
  107713. // Bring the camera back up if below the ground plane
  107714. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  107715. this._betaIsAnimating = true;
  107716. //Transition to new position
  107717. this.stopAllAnimations();
  107718. if (!this._betaTransition) {
  107719. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107720. }
  107721. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  107722. _this._clearAnimationLocks();
  107723. _this.stopAllAnimations();
  107724. });
  107725. if (animatabe) {
  107726. this._animatables.push(animatabe);
  107727. }
  107728. }
  107729. };
  107730. /**
  107731. * Returns the frustum slope based on the canvas ratio and camera FOV
  107732. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  107733. */
  107734. FramingBehavior.prototype._getFrustumSlope = function () {
  107735. // Calculate the viewport ratio
  107736. // Aspect Ratio is Height/Width.
  107737. var camera = this._attachedCamera;
  107738. if (!camera) {
  107739. return BABYLON.Vector2.Zero();
  107740. }
  107741. var engine = camera.getScene().getEngine();
  107742. var aspectRatio = engine.getAspectRatio(camera);
  107743. // Camera FOV is the vertical field of view (top-bottom) in radians.
  107744. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  107745. var frustumSlopeY = Math.tan(camera.fov / 2);
  107746. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  107747. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  107748. // along the forward vector.
  107749. var frustumSlopeX = frustumSlopeY * aspectRatio;
  107750. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  107751. };
  107752. /**
  107753. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  107754. */
  107755. FramingBehavior.prototype._clearAnimationLocks = function () {
  107756. this._betaIsAnimating = false;
  107757. };
  107758. /**
  107759. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107760. */
  107761. FramingBehavior.prototype._applyUserInteraction = function () {
  107762. if (this.isUserIsMoving) {
  107763. this._lastInteractionTime = BABYLON.Tools.Now;
  107764. this.stopAllAnimations();
  107765. this._clearAnimationLocks();
  107766. }
  107767. };
  107768. /**
  107769. * Stops and removes all animations that have been applied to the camera
  107770. */
  107771. FramingBehavior.prototype.stopAllAnimations = function () {
  107772. if (this._attachedCamera) {
  107773. this._attachedCamera.animations = [];
  107774. }
  107775. while (this._animatables.length) {
  107776. if (this._animatables[0]) {
  107777. this._animatables[0].onAnimationEnd = null;
  107778. this._animatables[0].stop();
  107779. }
  107780. this._animatables.shift();
  107781. }
  107782. };
  107783. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  107784. /**
  107785. * Gets a value indicating if the user is moving the camera
  107786. */
  107787. get: function () {
  107788. if (!this._attachedCamera) {
  107789. return false;
  107790. }
  107791. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  107792. this._attachedCamera.inertialBetaOffset !== 0 ||
  107793. this._attachedCamera.inertialRadiusOffset !== 0 ||
  107794. this._attachedCamera.inertialPanningX !== 0 ||
  107795. this._attachedCamera.inertialPanningY !== 0 ||
  107796. this._isPointerDown;
  107797. },
  107798. enumerable: true,
  107799. configurable: true
  107800. });
  107801. /**
  107802. * The easing function used by animations
  107803. */
  107804. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  107805. /**
  107806. * The easing mode used by animations
  107807. */
  107808. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  107809. // Statics
  107810. /**
  107811. * The camera can move all the way towards the mesh.
  107812. */
  107813. FramingBehavior.IgnoreBoundsSizeMode = 0;
  107814. /**
  107815. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  107816. */
  107817. FramingBehavior.FitFrustumSidesMode = 1;
  107818. return FramingBehavior;
  107819. }());
  107820. BABYLON.FramingBehavior = FramingBehavior;
  107821. })(BABYLON || (BABYLON = {}));
  107822. //# sourceMappingURL=babylon.framingBehavior.js.map
  107823. var BABYLON;
  107824. (function (BABYLON) {
  107825. /**
  107826. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  107827. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  107828. */
  107829. var BouncingBehavior = /** @class */ (function () {
  107830. function BouncingBehavior() {
  107831. /**
  107832. * The duration of the animation, in milliseconds
  107833. */
  107834. this.transitionDuration = 450;
  107835. /**
  107836. * Length of the distance animated by the transition when lower radius is reached
  107837. */
  107838. this.lowerRadiusTransitionRange = 2;
  107839. /**
  107840. * Length of the distance animated by the transition when upper radius is reached
  107841. */
  107842. this.upperRadiusTransitionRange = -2;
  107843. this._autoTransitionRange = false;
  107844. // Animations
  107845. this._radiusIsAnimating = false;
  107846. this._radiusBounceTransition = null;
  107847. this._animatables = new Array();
  107848. }
  107849. Object.defineProperty(BouncingBehavior.prototype, "name", {
  107850. /**
  107851. * Gets the name of the behavior.
  107852. */
  107853. get: function () {
  107854. return "Bouncing";
  107855. },
  107856. enumerable: true,
  107857. configurable: true
  107858. });
  107859. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  107860. /**
  107861. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107862. */
  107863. get: function () {
  107864. return this._autoTransitionRange;
  107865. },
  107866. /**
  107867. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107868. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  107869. */
  107870. set: function (value) {
  107871. var _this = this;
  107872. if (this._autoTransitionRange === value) {
  107873. return;
  107874. }
  107875. this._autoTransitionRange = value;
  107876. var camera = this._attachedCamera;
  107877. if (!camera) {
  107878. return;
  107879. }
  107880. if (value) {
  107881. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107882. if (!mesh) {
  107883. return;
  107884. }
  107885. mesh.computeWorldMatrix(true);
  107886. var diagonal = mesh.getBoundingInfo().diagonalLength;
  107887. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  107888. _this.upperRadiusTransitionRange = diagonal * 0.05;
  107889. });
  107890. }
  107891. else if (this._onMeshTargetChangedObserver) {
  107892. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107893. }
  107894. },
  107895. enumerable: true,
  107896. configurable: true
  107897. });
  107898. /**
  107899. * Initializes the behavior.
  107900. */
  107901. BouncingBehavior.prototype.init = function () {
  107902. // Do notihng
  107903. };
  107904. /**
  107905. * Attaches the behavior to its arc rotate camera.
  107906. * @param camera Defines the camera to attach the behavior to
  107907. */
  107908. BouncingBehavior.prototype.attach = function (camera) {
  107909. var _this = this;
  107910. this._attachedCamera = camera;
  107911. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107912. if (!_this._attachedCamera) {
  107913. return;
  107914. }
  107915. // Add the bounce animation to the lower radius limit
  107916. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  107917. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  107918. }
  107919. // Add the bounce animation to the upper radius limit
  107920. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  107921. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  107922. }
  107923. });
  107924. };
  107925. /**
  107926. * Detaches the behavior from its current arc rotate camera.
  107927. */
  107928. BouncingBehavior.prototype.detach = function () {
  107929. if (!this._attachedCamera) {
  107930. return;
  107931. }
  107932. if (this._onAfterCheckInputsObserver) {
  107933. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107934. }
  107935. if (this._onMeshTargetChangedObserver) {
  107936. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107937. }
  107938. this._attachedCamera = null;
  107939. };
  107940. /**
  107941. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  107942. * @param radiusLimit The limit to check against.
  107943. * @return Bool to indicate if at limit.
  107944. */
  107945. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  107946. if (!this._attachedCamera) {
  107947. return false;
  107948. }
  107949. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  107950. return true;
  107951. }
  107952. return false;
  107953. };
  107954. /**
  107955. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  107956. * @param radiusDelta The delta by which to animate to. Can be negative.
  107957. */
  107958. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  107959. var _this = this;
  107960. if (!this._attachedCamera) {
  107961. return;
  107962. }
  107963. if (!this._radiusBounceTransition) {
  107964. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  107965. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  107966. }
  107967. // Prevent zoom until bounce has completed
  107968. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  107969. this._attachedCamera.wheelPrecision = Infinity;
  107970. this._attachedCamera.inertialRadiusOffset = 0;
  107971. // Animate to the radius limit
  107972. this.stopAllAnimations();
  107973. this._radiusIsAnimating = true;
  107974. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  107975. if (animatable) {
  107976. this._animatables.push(animatable);
  107977. }
  107978. };
  107979. /**
  107980. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  107981. */
  107982. BouncingBehavior.prototype._clearAnimationLocks = function () {
  107983. this._radiusIsAnimating = false;
  107984. if (this._attachedCamera) {
  107985. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  107986. }
  107987. };
  107988. /**
  107989. * Stops and removes all animations that have been applied to the camera
  107990. */
  107991. BouncingBehavior.prototype.stopAllAnimations = function () {
  107992. if (this._attachedCamera) {
  107993. this._attachedCamera.animations = [];
  107994. }
  107995. while (this._animatables.length) {
  107996. this._animatables[0].onAnimationEnd = null;
  107997. this._animatables[0].stop();
  107998. this._animatables.shift();
  107999. }
  108000. };
  108001. /**
  108002. * The easing function used by animations
  108003. */
  108004. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108005. /**
  108006. * The easing mode used by animations
  108007. */
  108008. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108009. return BouncingBehavior;
  108010. }());
  108011. BABYLON.BouncingBehavior = BouncingBehavior;
  108012. })(BABYLON || (BABYLON = {}));
  108013. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108014. var BABYLON;
  108015. (function (BABYLON) {
  108016. /**
  108017. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108018. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108019. */
  108020. var AutoRotationBehavior = /** @class */ (function () {
  108021. function AutoRotationBehavior() {
  108022. this._zoomStopsAnimation = false;
  108023. this._idleRotationSpeed = 0.05;
  108024. this._idleRotationWaitTime = 2000;
  108025. this._idleRotationSpinupTime = 2000;
  108026. this._isPointerDown = false;
  108027. this._lastFrameTime = null;
  108028. this._lastInteractionTime = -Infinity;
  108029. this._cameraRotationSpeed = 0;
  108030. this._lastFrameRadius = 0;
  108031. }
  108032. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108033. /**
  108034. * Gets the name of the behavior.
  108035. */
  108036. get: function () {
  108037. return "AutoRotation";
  108038. },
  108039. enumerable: true,
  108040. configurable: true
  108041. });
  108042. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108043. /**
  108044. * Gets the flag that indicates if user zooming should stop animation.
  108045. */
  108046. get: function () {
  108047. return this._zoomStopsAnimation;
  108048. },
  108049. /**
  108050. * Sets the flag that indicates if user zooming should stop animation.
  108051. */
  108052. set: function (flag) {
  108053. this._zoomStopsAnimation = flag;
  108054. },
  108055. enumerable: true,
  108056. configurable: true
  108057. });
  108058. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108059. /**
  108060. * Gets the default speed at which the camera rotates around the model.
  108061. */
  108062. get: function () {
  108063. return this._idleRotationSpeed;
  108064. },
  108065. /**
  108066. * Sets the default speed at which the camera rotates around the model.
  108067. */
  108068. set: function (speed) {
  108069. this._idleRotationSpeed = speed;
  108070. },
  108071. enumerable: true,
  108072. configurable: true
  108073. });
  108074. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  108075. /**
  108076. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  108077. */
  108078. get: function () {
  108079. return this._idleRotationWaitTime;
  108080. },
  108081. /**
  108082. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  108083. */
  108084. set: function (time) {
  108085. this._idleRotationWaitTime = time;
  108086. },
  108087. enumerable: true,
  108088. configurable: true
  108089. });
  108090. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  108091. /**
  108092. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108093. */
  108094. get: function () {
  108095. return this._idleRotationSpinupTime;
  108096. },
  108097. /**
  108098. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  108099. */
  108100. set: function (time) {
  108101. this._idleRotationSpinupTime = time;
  108102. },
  108103. enumerable: true,
  108104. configurable: true
  108105. });
  108106. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  108107. /**
  108108. * Gets a value indicating if the camera is currently rotating because of this behavior
  108109. */
  108110. get: function () {
  108111. return Math.abs(this._cameraRotationSpeed) > 0;
  108112. },
  108113. enumerable: true,
  108114. configurable: true
  108115. });
  108116. /**
  108117. * Initializes the behavior.
  108118. */
  108119. AutoRotationBehavior.prototype.init = function () {
  108120. // Do notihng
  108121. };
  108122. /**
  108123. * Attaches the behavior to its arc rotate camera.
  108124. * @param camera Defines the camera to attach the behavior to
  108125. */
  108126. AutoRotationBehavior.prototype.attach = function (camera) {
  108127. var _this = this;
  108128. this._attachedCamera = camera;
  108129. var scene = this._attachedCamera.getScene();
  108130. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108131. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108132. _this._isPointerDown = true;
  108133. return;
  108134. }
  108135. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108136. _this._isPointerDown = false;
  108137. }
  108138. });
  108139. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108140. var now = BABYLON.Tools.Now;
  108141. var dt = 0;
  108142. if (_this._lastFrameTime != null) {
  108143. dt = now - _this._lastFrameTime;
  108144. }
  108145. _this._lastFrameTime = now;
  108146. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108147. _this._applyUserInteraction();
  108148. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  108149. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  108150. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  108151. // Step camera rotation by rotation speed
  108152. if (_this._attachedCamera) {
  108153. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  108154. }
  108155. });
  108156. };
  108157. /**
  108158. * Detaches the behavior from its current arc rotate camera.
  108159. */
  108160. AutoRotationBehavior.prototype.detach = function () {
  108161. if (!this._attachedCamera) {
  108162. return;
  108163. }
  108164. var scene = this._attachedCamera.getScene();
  108165. if (this._onPrePointerObservableObserver) {
  108166. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108167. }
  108168. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108169. this._attachedCamera = null;
  108170. };
  108171. /**
  108172. * Returns true if user is scrolling.
  108173. * @return true if user is scrolling.
  108174. */
  108175. AutoRotationBehavior.prototype._userIsZooming = function () {
  108176. if (!this._attachedCamera) {
  108177. return false;
  108178. }
  108179. return this._attachedCamera.inertialRadiusOffset !== 0;
  108180. };
  108181. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  108182. if (!this._attachedCamera) {
  108183. return false;
  108184. }
  108185. var zoomHasHitLimit = false;
  108186. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  108187. zoomHasHitLimit = true;
  108188. }
  108189. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  108190. this._lastFrameRadius = this._attachedCamera.radius;
  108191. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  108192. };
  108193. /**
  108194. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108195. */
  108196. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  108197. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  108198. this._lastInteractionTime = BABYLON.Tools.Now;
  108199. }
  108200. };
  108201. // Tools
  108202. AutoRotationBehavior.prototype._userIsMoving = function () {
  108203. if (!this._attachedCamera) {
  108204. return false;
  108205. }
  108206. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108207. this._attachedCamera.inertialBetaOffset !== 0 ||
  108208. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108209. this._attachedCamera.inertialPanningX !== 0 ||
  108210. this._attachedCamera.inertialPanningY !== 0 ||
  108211. this._isPointerDown;
  108212. };
  108213. return AutoRotationBehavior;
  108214. }());
  108215. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  108216. })(BABYLON || (BABYLON = {}));
  108217. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  108218. var BABYLON;
  108219. (function (BABYLON) {
  108220. var NullEngineOptions = /** @class */ (function () {
  108221. function NullEngineOptions() {
  108222. this.renderWidth = 512;
  108223. this.renderHeight = 256;
  108224. this.textureSize = 512;
  108225. this.deterministicLockstep = false;
  108226. this.lockstepMaxSteps = 4;
  108227. }
  108228. return NullEngineOptions;
  108229. }());
  108230. BABYLON.NullEngineOptions = NullEngineOptions;
  108231. /**
  108232. * The null engine class provides support for headless version of babylon.js.
  108233. * This can be used in server side scenario or for testing purposes
  108234. */
  108235. var NullEngine = /** @class */ (function (_super) {
  108236. __extends(NullEngine, _super);
  108237. function NullEngine(options) {
  108238. if (options === void 0) { options = new NullEngineOptions(); }
  108239. var _this = _super.call(this, null) || this;
  108240. if (options.deterministicLockstep === undefined) {
  108241. options.deterministicLockstep = false;
  108242. }
  108243. if (options.lockstepMaxSteps === undefined) {
  108244. options.lockstepMaxSteps = 4;
  108245. }
  108246. _this._options = options;
  108247. // Init caps
  108248. // We consider we are on a webgl1 capable device
  108249. _this._caps = new BABYLON.EngineCapabilities();
  108250. _this._caps.maxTexturesImageUnits = 16;
  108251. _this._caps.maxVertexTextureImageUnits = 16;
  108252. _this._caps.maxTextureSize = 512;
  108253. _this._caps.maxCubemapTextureSize = 512;
  108254. _this._caps.maxRenderTextureSize = 512;
  108255. _this._caps.maxVertexAttribs = 16;
  108256. _this._caps.maxVaryingVectors = 16;
  108257. _this._caps.maxFragmentUniformVectors = 16;
  108258. _this._caps.maxVertexUniformVectors = 16;
  108259. // Extensions
  108260. _this._caps.standardDerivatives = false;
  108261. _this._caps.astc = null;
  108262. _this._caps.s3tc = null;
  108263. _this._caps.pvrtc = null;
  108264. _this._caps.etc1 = null;
  108265. _this._caps.etc2 = null;
  108266. _this._caps.textureAnisotropicFilterExtension = null;
  108267. _this._caps.maxAnisotropy = 0;
  108268. _this._caps.uintIndices = false;
  108269. _this._caps.fragmentDepthSupported = false;
  108270. _this._caps.highPrecisionShaderSupported = true;
  108271. _this._caps.colorBufferFloat = false;
  108272. _this._caps.textureFloat = false;
  108273. _this._caps.textureFloatLinearFiltering = false;
  108274. _this._caps.textureFloatRender = false;
  108275. _this._caps.textureHalfFloat = false;
  108276. _this._caps.textureHalfFloatLinearFiltering = false;
  108277. _this._caps.textureHalfFloatRender = false;
  108278. _this._caps.textureLOD = false;
  108279. _this._caps.drawBuffersExtension = false;
  108280. _this._caps.depthTextureExtension = false;
  108281. _this._caps.vertexArrayObject = false;
  108282. _this._caps.instancedArrays = false;
  108283. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  108284. // Wrappers
  108285. if (typeof URL === "undefined") {
  108286. URL = {
  108287. createObjectURL: function () { },
  108288. revokeObjectURL: function () { }
  108289. };
  108290. }
  108291. if (typeof Blob === "undefined") {
  108292. Blob = function () { };
  108293. }
  108294. return _this;
  108295. }
  108296. NullEngine.prototype.isDeterministicLockStep = function () {
  108297. return this._options.deterministicLockstep;
  108298. };
  108299. NullEngine.prototype.getLockstepMaxSteps = function () {
  108300. return this._options.lockstepMaxSteps;
  108301. };
  108302. NullEngine.prototype.getHardwareScalingLevel = function () {
  108303. return 1.0;
  108304. };
  108305. NullEngine.prototype.createVertexBuffer = function (vertices) {
  108306. return {
  108307. capacity: 0,
  108308. references: 1,
  108309. is32Bits: false
  108310. };
  108311. };
  108312. NullEngine.prototype.createIndexBuffer = function (indices) {
  108313. return {
  108314. capacity: 0,
  108315. references: 1,
  108316. is32Bits: false
  108317. };
  108318. };
  108319. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  108320. if (stencil === void 0) { stencil = false; }
  108321. };
  108322. NullEngine.prototype.getRenderWidth = function (useScreen) {
  108323. if (useScreen === void 0) { useScreen = false; }
  108324. if (!useScreen && this._currentRenderTarget) {
  108325. return this._currentRenderTarget.width;
  108326. }
  108327. return this._options.renderWidth;
  108328. };
  108329. NullEngine.prototype.getRenderHeight = function (useScreen) {
  108330. if (useScreen === void 0) { useScreen = false; }
  108331. if (!useScreen && this._currentRenderTarget) {
  108332. return this._currentRenderTarget.height;
  108333. }
  108334. return this._options.renderHeight;
  108335. };
  108336. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  108337. this._cachedViewport = viewport;
  108338. };
  108339. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  108340. return {
  108341. transformFeedback: null,
  108342. __SPECTOR_rebuildProgram: null
  108343. };
  108344. };
  108345. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  108346. return [];
  108347. };
  108348. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  108349. return [];
  108350. };
  108351. NullEngine.prototype.bindSamplers = function (effect) {
  108352. this._currentEffect = null;
  108353. };
  108354. NullEngine.prototype.enableEffect = function (effect) {
  108355. this._currentEffect = effect;
  108356. if (effect.onBind) {
  108357. effect.onBind(effect);
  108358. }
  108359. if (effect._onBindObservable) {
  108360. effect._onBindObservable.notifyObservers(effect);
  108361. }
  108362. };
  108363. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  108364. if (zOffset === void 0) { zOffset = 0; }
  108365. if (reverseSide === void 0) { reverseSide = false; }
  108366. };
  108367. NullEngine.prototype.setIntArray = function (uniform, array) {
  108368. };
  108369. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  108370. };
  108371. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  108372. };
  108373. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  108374. };
  108375. NullEngine.prototype.setFloatArray = function (uniform, array) {
  108376. };
  108377. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  108378. };
  108379. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  108380. };
  108381. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  108382. };
  108383. NullEngine.prototype.setArray = function (uniform, array) {
  108384. };
  108385. NullEngine.prototype.setArray2 = function (uniform, array) {
  108386. };
  108387. NullEngine.prototype.setArray3 = function (uniform, array) {
  108388. };
  108389. NullEngine.prototype.setArray4 = function (uniform, array) {
  108390. };
  108391. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  108392. };
  108393. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  108394. };
  108395. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  108396. };
  108397. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  108398. };
  108399. NullEngine.prototype.setFloat = function (uniform, value) {
  108400. };
  108401. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  108402. };
  108403. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  108404. };
  108405. NullEngine.prototype.setBool = function (uniform, bool) {
  108406. };
  108407. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  108408. };
  108409. NullEngine.prototype.setColor3 = function (uniform, color3) {
  108410. };
  108411. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  108412. };
  108413. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  108414. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  108415. if (this._alphaMode === mode) {
  108416. return;
  108417. }
  108418. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  108419. if (!noDepthWriteChange) {
  108420. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  108421. }
  108422. this._alphaMode = mode;
  108423. };
  108424. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  108425. };
  108426. NullEngine.prototype.wipeCaches = function (bruteForce) {
  108427. if (this.preventCacheWipeBetweenFrames) {
  108428. return;
  108429. }
  108430. this.resetTextureCache();
  108431. this._currentEffect = null;
  108432. if (bruteForce) {
  108433. this._currentProgram = null;
  108434. this._stencilState.reset();
  108435. this._depthCullingState.reset();
  108436. this._alphaState.reset();
  108437. }
  108438. this._cachedVertexBuffers = null;
  108439. this._cachedIndexBuffer = null;
  108440. this._cachedEffectForVertexBuffers = null;
  108441. };
  108442. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  108443. };
  108444. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  108445. };
  108446. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  108447. };
  108448. /** @hidden */
  108449. NullEngine.prototype._createTexture = function () {
  108450. return {};
  108451. };
  108452. /** @hidden */
  108453. NullEngine.prototype._releaseTexture = function (texture) {
  108454. };
  108455. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  108456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108457. if (onLoad === void 0) { onLoad = null; }
  108458. if (onError === void 0) { onError = null; }
  108459. if (buffer === void 0) { buffer = null; }
  108460. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  108461. var url = String(urlArg);
  108462. texture.url = url;
  108463. texture.generateMipMaps = !noMipmap;
  108464. texture.samplingMode = samplingMode;
  108465. texture.invertY = invertY;
  108466. texture.baseWidth = this._options.textureSize;
  108467. texture.baseHeight = this._options.textureSize;
  108468. texture.width = this._options.textureSize;
  108469. texture.height = this._options.textureSize;
  108470. if (format) {
  108471. texture.format = format;
  108472. }
  108473. texture.isReady = true;
  108474. if (onLoad) {
  108475. onLoad();
  108476. }
  108477. this._internalTexturesCache.push(texture);
  108478. return texture;
  108479. };
  108480. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  108481. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  108482. if (options !== undefined && typeof options === "object") {
  108483. fullOptions.generateMipMaps = options.generateMipMaps;
  108484. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  108485. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  108486. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  108487. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  108488. }
  108489. else {
  108490. fullOptions.generateMipMaps = options;
  108491. fullOptions.generateDepthBuffer = true;
  108492. fullOptions.generateStencilBuffer = false;
  108493. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108494. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108495. }
  108496. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  108497. var width = size.width || size;
  108498. var height = size.height || size;
  108499. texture._depthStencilBuffer = {};
  108500. texture._framebuffer = {};
  108501. texture.baseWidth = width;
  108502. texture.baseHeight = height;
  108503. texture.width = width;
  108504. texture.height = height;
  108505. texture.isReady = true;
  108506. texture.samples = 1;
  108507. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  108508. texture.samplingMode = fullOptions.samplingMode;
  108509. texture.type = fullOptions.type;
  108510. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  108511. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  108512. this._internalTexturesCache.push(texture);
  108513. return texture;
  108514. };
  108515. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  108516. texture.samplingMode = samplingMode;
  108517. };
  108518. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  108519. if (this._currentRenderTarget) {
  108520. this.unBindFramebuffer(this._currentRenderTarget);
  108521. }
  108522. this._currentRenderTarget = texture;
  108523. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  108524. if (this._cachedViewport && !forceFullscreenViewport) {
  108525. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  108526. }
  108527. };
  108528. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  108529. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  108530. this._currentRenderTarget = null;
  108531. if (onBeforeUnbind) {
  108532. if (texture._MSAAFramebuffer) {
  108533. this._currentFramebuffer = texture._framebuffer;
  108534. }
  108535. onBeforeUnbind();
  108536. }
  108537. this._currentFramebuffer = null;
  108538. };
  108539. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  108540. var vbo = {
  108541. capacity: 1,
  108542. references: 1,
  108543. is32Bits: false
  108544. };
  108545. return vbo;
  108546. };
  108547. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  108548. if (premulAlpha === void 0) { premulAlpha = false; }
  108549. };
  108550. /**
  108551. * @hidden
  108552. * Get the current error code of the webGL context
  108553. * @returns the error code
  108554. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  108555. */
  108556. NullEngine.prototype.getError = function () {
  108557. return 0;
  108558. };
  108559. /** @hidden */
  108560. NullEngine.prototype._getUnpackAlignement = function () {
  108561. return 1;
  108562. };
  108563. /** @hidden */
  108564. NullEngine.prototype._unpackFlipY = function (value) {
  108565. };
  108566. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  108567. if (offset === void 0) { offset = 0; }
  108568. };
  108569. /**
  108570. * Updates a dynamic vertex buffer.
  108571. * @param vertexBuffer the vertex buffer to update
  108572. * @param data the data used to update the vertex buffer
  108573. * @param byteOffset the byte offset of the data (optional)
  108574. * @param byteLength the byte length of the data (optional)
  108575. */
  108576. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  108577. };
  108578. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  108579. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  108580. this._boundTexturesCache[this._activeChannel] = texture;
  108581. return true;
  108582. }
  108583. return false;
  108584. };
  108585. /** @hidden */
  108586. NullEngine.prototype._bindTexture = function (channel, texture) {
  108587. if (channel < 0) {
  108588. return;
  108589. }
  108590. this._bindTextureDirectly(0, texture);
  108591. };
  108592. /** @hidden */
  108593. NullEngine.prototype._releaseBuffer = function (buffer) {
  108594. buffer.references--;
  108595. if (buffer.references === 0) {
  108596. return true;
  108597. }
  108598. return false;
  108599. };
  108600. NullEngine.prototype.releaseEffects = function () {
  108601. };
  108602. NullEngine.prototype.displayLoadingUI = function () {
  108603. };
  108604. NullEngine.prototype.hideLoadingUI = function () {
  108605. };
  108606. /** @hidden */
  108607. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  108608. if (faceIndex === void 0) { faceIndex = 0; }
  108609. if (lod === void 0) { lod = 0; }
  108610. };
  108611. /** @hidden */
  108612. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  108613. if (faceIndex === void 0) { faceIndex = 0; }
  108614. if (lod === void 0) { lod = 0; }
  108615. };
  108616. /** @hidden */
  108617. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  108618. if (faceIndex === void 0) { faceIndex = 0; }
  108619. if (lod === void 0) { lod = 0; }
  108620. };
  108621. /** @hidden */
  108622. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  108623. if (faceIndex === void 0) { faceIndex = 0; }
  108624. if (lod === void 0) { lod = 0; }
  108625. };
  108626. return NullEngine;
  108627. }(BABYLON.Engine));
  108628. BABYLON.NullEngine = NullEngine;
  108629. })(BABYLON || (BABYLON = {}));
  108630. //# sourceMappingURL=babylon.nullEngine.js.map
  108631. var BABYLON;
  108632. (function (BABYLON) {
  108633. /**
  108634. * This class can be used to get instrumentation data from a Babylon engine
  108635. */
  108636. var EngineInstrumentation = /** @class */ (function () {
  108637. function EngineInstrumentation(engine) {
  108638. this.engine = engine;
  108639. this._captureGPUFrameTime = false;
  108640. this._gpuFrameTime = new BABYLON.PerfCounter();
  108641. this._captureShaderCompilationTime = false;
  108642. this._shaderCompilationTime = new BABYLON.PerfCounter();
  108643. // Observers
  108644. this._onBeginFrameObserver = null;
  108645. this._onEndFrameObserver = null;
  108646. this._onBeforeShaderCompilationObserver = null;
  108647. this._onAfterShaderCompilationObserver = null;
  108648. }
  108649. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  108650. // Properties
  108651. /**
  108652. * Gets the perf counter used for GPU frame time
  108653. */
  108654. get: function () {
  108655. return this._gpuFrameTime;
  108656. },
  108657. enumerable: true,
  108658. configurable: true
  108659. });
  108660. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  108661. /**
  108662. * Gets the GPU frame time capture status
  108663. */
  108664. get: function () {
  108665. return this._captureGPUFrameTime;
  108666. },
  108667. /**
  108668. * Enable or disable the GPU frame time capture
  108669. */
  108670. set: function (value) {
  108671. var _this = this;
  108672. if (value === this._captureGPUFrameTime) {
  108673. return;
  108674. }
  108675. this._captureGPUFrameTime = value;
  108676. if (value) {
  108677. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  108678. if (!_this._gpuFrameTimeToken) {
  108679. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  108680. }
  108681. });
  108682. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  108683. if (!_this._gpuFrameTimeToken) {
  108684. return;
  108685. }
  108686. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  108687. if (time > -1) {
  108688. _this._gpuFrameTimeToken = null;
  108689. _this._gpuFrameTime.fetchNewFrame();
  108690. _this._gpuFrameTime.addCount(time, true);
  108691. }
  108692. });
  108693. }
  108694. else {
  108695. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108696. this._onBeginFrameObserver = null;
  108697. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108698. this._onEndFrameObserver = null;
  108699. }
  108700. },
  108701. enumerable: true,
  108702. configurable: true
  108703. });
  108704. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  108705. /**
  108706. * Gets the perf counter used for shader compilation time
  108707. */
  108708. get: function () {
  108709. return this._shaderCompilationTime;
  108710. },
  108711. enumerable: true,
  108712. configurable: true
  108713. });
  108714. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  108715. /**
  108716. * Gets the shader compilation time capture status
  108717. */
  108718. get: function () {
  108719. return this._captureShaderCompilationTime;
  108720. },
  108721. /**
  108722. * Enable or disable the shader compilation time capture
  108723. */
  108724. set: function (value) {
  108725. var _this = this;
  108726. if (value === this._captureShaderCompilationTime) {
  108727. return;
  108728. }
  108729. this._captureShaderCompilationTime = value;
  108730. if (value) {
  108731. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  108732. _this._shaderCompilationTime.fetchNewFrame();
  108733. _this._shaderCompilationTime.beginMonitoring();
  108734. });
  108735. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  108736. _this._shaderCompilationTime.endMonitoring();
  108737. });
  108738. }
  108739. else {
  108740. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108741. this._onBeforeShaderCompilationObserver = null;
  108742. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108743. this._onAfterShaderCompilationObserver = null;
  108744. }
  108745. },
  108746. enumerable: true,
  108747. configurable: true
  108748. });
  108749. EngineInstrumentation.prototype.dispose = function () {
  108750. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108751. this._onBeginFrameObserver = null;
  108752. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108753. this._onEndFrameObserver = null;
  108754. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108755. this._onBeforeShaderCompilationObserver = null;
  108756. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108757. this._onAfterShaderCompilationObserver = null;
  108758. this.engine = null;
  108759. };
  108760. return EngineInstrumentation;
  108761. }());
  108762. BABYLON.EngineInstrumentation = EngineInstrumentation;
  108763. })(BABYLON || (BABYLON = {}));
  108764. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  108765. var BABYLON;
  108766. (function (BABYLON) {
  108767. /**
  108768. * This class can be used to get instrumentation data from a Babylon engine
  108769. */
  108770. var SceneInstrumentation = /** @class */ (function () {
  108771. function SceneInstrumentation(scene) {
  108772. var _this = this;
  108773. this.scene = scene;
  108774. this._captureActiveMeshesEvaluationTime = false;
  108775. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  108776. this._captureRenderTargetsRenderTime = false;
  108777. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  108778. this._captureFrameTime = false;
  108779. this._frameTime = new BABYLON.PerfCounter();
  108780. this._captureRenderTime = false;
  108781. this._renderTime = new BABYLON.PerfCounter();
  108782. this._captureInterFrameTime = false;
  108783. this._interFrameTime = new BABYLON.PerfCounter();
  108784. this._captureParticlesRenderTime = false;
  108785. this._particlesRenderTime = new BABYLON.PerfCounter();
  108786. this._captureSpritesRenderTime = false;
  108787. this._spritesRenderTime = new BABYLON.PerfCounter();
  108788. this._capturePhysicsTime = false;
  108789. this._physicsTime = new BABYLON.PerfCounter();
  108790. this._captureAnimationsTime = false;
  108791. this._animationsTime = new BABYLON.PerfCounter();
  108792. this._captureCameraRenderTime = false;
  108793. this._cameraRenderTime = new BABYLON.PerfCounter();
  108794. // Observers
  108795. this._onBeforeActiveMeshesEvaluationObserver = null;
  108796. this._onAfterActiveMeshesEvaluationObserver = null;
  108797. this._onBeforeRenderTargetsRenderObserver = null;
  108798. this._onAfterRenderTargetsRenderObserver = null;
  108799. this._onAfterRenderObserver = null;
  108800. this._onBeforeDrawPhaseObserver = null;
  108801. this._onAfterDrawPhaseObserver = null;
  108802. this._onBeforeAnimationsObserver = null;
  108803. this._onBeforeParticlesRenderingObserver = null;
  108804. this._onAfterParticlesRenderingObserver = null;
  108805. this._onBeforeSpritesRenderingObserver = null;
  108806. this._onAfterSpritesRenderingObserver = null;
  108807. this._onBeforePhysicsObserver = null;
  108808. this._onAfterPhysicsObserver = null;
  108809. this._onAfterAnimationsObserver = null;
  108810. this._onBeforeCameraRenderObserver = null;
  108811. this._onAfterCameraRenderObserver = null;
  108812. // Before render
  108813. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  108814. if (_this._captureActiveMeshesEvaluationTime) {
  108815. _this._activeMeshesEvaluationTime.fetchNewFrame();
  108816. }
  108817. if (_this._captureRenderTargetsRenderTime) {
  108818. _this._renderTargetsRenderTime.fetchNewFrame();
  108819. }
  108820. if (_this._captureFrameTime) {
  108821. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  108822. _this._frameTime.beginMonitoring();
  108823. }
  108824. if (_this._captureInterFrameTime) {
  108825. _this._interFrameTime.endMonitoring();
  108826. }
  108827. if (_this._captureParticlesRenderTime) {
  108828. _this._particlesRenderTime.fetchNewFrame();
  108829. }
  108830. if (_this._captureSpritesRenderTime) {
  108831. _this._spritesRenderTime.fetchNewFrame();
  108832. }
  108833. if (_this._captureAnimationsTime) {
  108834. _this._animationsTime.beginMonitoring();
  108835. }
  108836. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  108837. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  108838. });
  108839. // After render
  108840. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  108841. if (_this._captureFrameTime) {
  108842. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  108843. _this._frameTime.endMonitoring();
  108844. }
  108845. if (_this._captureRenderTime) {
  108846. _this._renderTime.endMonitoring(false);
  108847. }
  108848. if (_this._captureInterFrameTime) {
  108849. _this._interFrameTime.beginMonitoring();
  108850. }
  108851. });
  108852. }
  108853. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  108854. // Properties
  108855. /**
  108856. * Gets the perf counter used for active meshes evaluation time
  108857. */
  108858. get: function () {
  108859. return this._activeMeshesEvaluationTime;
  108860. },
  108861. enumerable: true,
  108862. configurable: true
  108863. });
  108864. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  108865. /**
  108866. * Gets the active meshes evaluation time capture status
  108867. */
  108868. get: function () {
  108869. return this._captureActiveMeshesEvaluationTime;
  108870. },
  108871. /**
  108872. * Enable or disable the active meshes evaluation time capture
  108873. */
  108874. set: function (value) {
  108875. var _this = this;
  108876. if (value === this._captureActiveMeshesEvaluationTime) {
  108877. return;
  108878. }
  108879. this._captureActiveMeshesEvaluationTime = value;
  108880. if (value) {
  108881. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  108882. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  108883. _this._activeMeshesEvaluationTime.beginMonitoring();
  108884. });
  108885. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  108886. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  108887. _this._activeMeshesEvaluationTime.endMonitoring();
  108888. });
  108889. }
  108890. else {
  108891. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  108892. this._onBeforeActiveMeshesEvaluationObserver = null;
  108893. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  108894. this._onAfterActiveMeshesEvaluationObserver = null;
  108895. }
  108896. },
  108897. enumerable: true,
  108898. configurable: true
  108899. });
  108900. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  108901. /**
  108902. * Gets the perf counter used for render targets render time
  108903. */
  108904. get: function () {
  108905. return this._renderTargetsRenderTime;
  108906. },
  108907. enumerable: true,
  108908. configurable: true
  108909. });
  108910. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  108911. /**
  108912. * Gets the render targets render time capture status
  108913. */
  108914. get: function () {
  108915. return this._captureRenderTargetsRenderTime;
  108916. },
  108917. /**
  108918. * Enable or disable the render targets render time capture
  108919. */
  108920. set: function (value) {
  108921. var _this = this;
  108922. if (value === this._captureRenderTargetsRenderTime) {
  108923. return;
  108924. }
  108925. this._captureRenderTargetsRenderTime = value;
  108926. if (value) {
  108927. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  108928. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  108929. _this._renderTargetsRenderTime.beginMonitoring();
  108930. });
  108931. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  108932. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  108933. _this._renderTargetsRenderTime.endMonitoring(false);
  108934. });
  108935. }
  108936. else {
  108937. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  108938. this._onBeforeRenderTargetsRenderObserver = null;
  108939. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  108940. this._onAfterRenderTargetsRenderObserver = null;
  108941. }
  108942. },
  108943. enumerable: true,
  108944. configurable: true
  108945. });
  108946. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  108947. /**
  108948. * Gets the perf counter used for particles render time
  108949. */
  108950. get: function () {
  108951. return this._particlesRenderTime;
  108952. },
  108953. enumerable: true,
  108954. configurable: true
  108955. });
  108956. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  108957. /**
  108958. * Gets the particles render time capture status
  108959. */
  108960. get: function () {
  108961. return this._captureParticlesRenderTime;
  108962. },
  108963. /**
  108964. * Enable or disable the particles render time capture
  108965. */
  108966. set: function (value) {
  108967. var _this = this;
  108968. if (value === this._captureParticlesRenderTime) {
  108969. return;
  108970. }
  108971. this._captureParticlesRenderTime = value;
  108972. if (value) {
  108973. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  108974. BABYLON.Tools.StartPerformanceCounter("Particles");
  108975. _this._particlesRenderTime.beginMonitoring();
  108976. });
  108977. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  108978. BABYLON.Tools.EndPerformanceCounter("Particles");
  108979. _this._particlesRenderTime.endMonitoring(false);
  108980. });
  108981. }
  108982. else {
  108983. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  108984. this._onBeforeParticlesRenderingObserver = null;
  108985. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  108986. this._onAfterParticlesRenderingObserver = null;
  108987. }
  108988. },
  108989. enumerable: true,
  108990. configurable: true
  108991. });
  108992. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  108993. /**
  108994. * Gets the perf counter used for sprites render time
  108995. */
  108996. get: function () {
  108997. return this._spritesRenderTime;
  108998. },
  108999. enumerable: true,
  109000. configurable: true
  109001. });
  109002. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109003. /**
  109004. * Gets the sprites render time capture status
  109005. */
  109006. get: function () {
  109007. return this._captureSpritesRenderTime;
  109008. },
  109009. /**
  109010. * Enable or disable the sprites render time capture
  109011. */
  109012. set: function (value) {
  109013. var _this = this;
  109014. if (value === this._captureSpritesRenderTime) {
  109015. return;
  109016. }
  109017. this._captureSpritesRenderTime = value;
  109018. if (!this.scene.spriteManagers) {
  109019. return;
  109020. }
  109021. if (value) {
  109022. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109023. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109024. _this._spritesRenderTime.beginMonitoring();
  109025. });
  109026. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109027. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109028. _this._spritesRenderTime.endMonitoring(false);
  109029. });
  109030. }
  109031. else {
  109032. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109033. this._onBeforeSpritesRenderingObserver = null;
  109034. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109035. this._onAfterSpritesRenderingObserver = null;
  109036. }
  109037. },
  109038. enumerable: true,
  109039. configurable: true
  109040. });
  109041. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109042. /**
  109043. * Gets the perf counter used for physics time
  109044. */
  109045. get: function () {
  109046. return this._physicsTime;
  109047. },
  109048. enumerable: true,
  109049. configurable: true
  109050. });
  109051. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  109052. /**
  109053. * Gets the physics time capture status
  109054. */
  109055. get: function () {
  109056. return this._capturePhysicsTime;
  109057. },
  109058. /**
  109059. * Enable or disable the physics time capture
  109060. */
  109061. set: function (value) {
  109062. var _this = this;
  109063. if (value === this._capturePhysicsTime) {
  109064. return;
  109065. }
  109066. if (!this.scene.onBeforePhysicsObservable) {
  109067. return;
  109068. }
  109069. this._capturePhysicsTime = value;
  109070. if (value) {
  109071. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  109072. BABYLON.Tools.StartPerformanceCounter("Physics");
  109073. _this._physicsTime.beginMonitoring();
  109074. });
  109075. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  109076. BABYLON.Tools.EndPerformanceCounter("Physics");
  109077. _this._physicsTime.endMonitoring();
  109078. });
  109079. }
  109080. else {
  109081. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109082. this._onBeforePhysicsObserver = null;
  109083. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109084. this._onAfterPhysicsObserver = null;
  109085. }
  109086. },
  109087. enumerable: true,
  109088. configurable: true
  109089. });
  109090. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  109091. /**
  109092. * Gets the perf counter used for animations time
  109093. */
  109094. get: function () {
  109095. return this._animationsTime;
  109096. },
  109097. enumerable: true,
  109098. configurable: true
  109099. });
  109100. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  109101. /**
  109102. * Gets the animations time capture status
  109103. */
  109104. get: function () {
  109105. return this._captureAnimationsTime;
  109106. },
  109107. /**
  109108. * Enable or disable the animations time capture
  109109. */
  109110. set: function (value) {
  109111. var _this = this;
  109112. if (value === this._captureAnimationsTime) {
  109113. return;
  109114. }
  109115. this._captureAnimationsTime = value;
  109116. if (value) {
  109117. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  109118. _this._animationsTime.endMonitoring();
  109119. });
  109120. }
  109121. else {
  109122. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109123. this._onAfterAnimationsObserver = null;
  109124. }
  109125. },
  109126. enumerable: true,
  109127. configurable: true
  109128. });
  109129. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  109130. /**
  109131. * Gets the perf counter used for frame time capture
  109132. */
  109133. get: function () {
  109134. return this._frameTime;
  109135. },
  109136. enumerable: true,
  109137. configurable: true
  109138. });
  109139. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  109140. /**
  109141. * Gets the frame time capture status
  109142. */
  109143. get: function () {
  109144. return this._captureFrameTime;
  109145. },
  109146. /**
  109147. * Enable or disable the frame time capture
  109148. */
  109149. set: function (value) {
  109150. this._captureFrameTime = value;
  109151. },
  109152. enumerable: true,
  109153. configurable: true
  109154. });
  109155. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  109156. /**
  109157. * Gets the perf counter used for inter-frames time capture
  109158. */
  109159. get: function () {
  109160. return this._interFrameTime;
  109161. },
  109162. enumerable: true,
  109163. configurable: true
  109164. });
  109165. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  109166. /**
  109167. * Gets the inter-frames time capture status
  109168. */
  109169. get: function () {
  109170. return this._captureInterFrameTime;
  109171. },
  109172. /**
  109173. * Enable or disable the inter-frames time capture
  109174. */
  109175. set: function (value) {
  109176. this._captureInterFrameTime = value;
  109177. },
  109178. enumerable: true,
  109179. configurable: true
  109180. });
  109181. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  109182. /**
  109183. * Gets the perf counter used for render time capture
  109184. */
  109185. get: function () {
  109186. return this._renderTime;
  109187. },
  109188. enumerable: true,
  109189. configurable: true
  109190. });
  109191. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  109192. /**
  109193. * Gets the render time capture status
  109194. */
  109195. get: function () {
  109196. return this._captureRenderTime;
  109197. },
  109198. /**
  109199. * Enable or disable the render time capture
  109200. */
  109201. set: function (value) {
  109202. var _this = this;
  109203. if (value === this._captureRenderTime) {
  109204. return;
  109205. }
  109206. this._captureRenderTime = value;
  109207. if (value) {
  109208. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  109209. _this._renderTime.beginMonitoring();
  109210. BABYLON.Tools.StartPerformanceCounter("Main render");
  109211. });
  109212. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  109213. _this._renderTime.endMonitoring(false);
  109214. BABYLON.Tools.EndPerformanceCounter("Main render");
  109215. });
  109216. }
  109217. else {
  109218. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109219. this._onBeforeDrawPhaseObserver = null;
  109220. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109221. this._onAfterDrawPhaseObserver = null;
  109222. }
  109223. },
  109224. enumerable: true,
  109225. configurable: true
  109226. });
  109227. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  109228. /**
  109229. * Gets the perf counter used for camera render time capture
  109230. */
  109231. get: function () {
  109232. return this._cameraRenderTime;
  109233. },
  109234. enumerable: true,
  109235. configurable: true
  109236. });
  109237. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  109238. /**
  109239. * Gets the camera render time capture status
  109240. */
  109241. get: function () {
  109242. return this._captureCameraRenderTime;
  109243. },
  109244. /**
  109245. * Enable or disable the camera render time capture
  109246. */
  109247. set: function (value) {
  109248. var _this = this;
  109249. if (value === this._captureCameraRenderTime) {
  109250. return;
  109251. }
  109252. this._captureCameraRenderTime = value;
  109253. if (value) {
  109254. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  109255. _this._cameraRenderTime.beginMonitoring();
  109256. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  109257. });
  109258. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  109259. _this._cameraRenderTime.endMonitoring(false);
  109260. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  109261. });
  109262. }
  109263. else {
  109264. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109265. this._onBeforeCameraRenderObserver = null;
  109266. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109267. this._onAfterCameraRenderObserver = null;
  109268. }
  109269. },
  109270. enumerable: true,
  109271. configurable: true
  109272. });
  109273. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  109274. /**
  109275. * Gets the perf counter used for draw calls
  109276. */
  109277. get: function () {
  109278. return this.scene.getEngine()._drawCalls;
  109279. },
  109280. enumerable: true,
  109281. configurable: true
  109282. });
  109283. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  109284. /**
  109285. * Gets the perf counter used for texture collisions
  109286. */
  109287. get: function () {
  109288. return this.scene.getEngine()._textureCollisions;
  109289. },
  109290. enumerable: true,
  109291. configurable: true
  109292. });
  109293. SceneInstrumentation.prototype.dispose = function () {
  109294. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109295. this._onAfterRenderObserver = null;
  109296. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109297. this._onBeforeActiveMeshesEvaluationObserver = null;
  109298. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109299. this._onAfterActiveMeshesEvaluationObserver = null;
  109300. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109301. this._onBeforeRenderTargetsRenderObserver = null;
  109302. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109303. this._onAfterRenderTargetsRenderObserver = null;
  109304. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  109305. this._onBeforeAnimationsObserver = null;
  109306. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109307. this._onBeforeParticlesRenderingObserver = null;
  109308. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109309. this._onAfterParticlesRenderingObserver = null;
  109310. if (this._onBeforeSpritesRenderingObserver) {
  109311. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109312. this._onBeforeSpritesRenderingObserver = null;
  109313. }
  109314. if (this._onAfterSpritesRenderingObserver) {
  109315. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109316. this._onAfterSpritesRenderingObserver = null;
  109317. }
  109318. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109319. this._onBeforeDrawPhaseObserver = null;
  109320. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109321. this._onAfterDrawPhaseObserver = null;
  109322. if (this._onBeforePhysicsObserver) {
  109323. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109324. this._onBeforePhysicsObserver = null;
  109325. }
  109326. if (this._onAfterPhysicsObserver) {
  109327. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109328. this._onAfterPhysicsObserver = null;
  109329. }
  109330. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109331. this._onAfterAnimationsObserver = null;
  109332. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109333. this._onBeforeCameraRenderObserver = null;
  109334. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109335. this._onAfterCameraRenderObserver = null;
  109336. this.scene = null;
  109337. };
  109338. return SceneInstrumentation;
  109339. }());
  109340. BABYLON.SceneInstrumentation = SceneInstrumentation;
  109341. })(BABYLON || (BABYLON = {}));
  109342. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  109343. var BABYLON;
  109344. (function (BABYLON) {
  109345. /**
  109346. * @hidden
  109347. **/
  109348. var _TimeToken = /** @class */ (function () {
  109349. function _TimeToken() {
  109350. this._timeElapsedQueryEnded = false;
  109351. }
  109352. return _TimeToken;
  109353. }());
  109354. BABYLON._TimeToken = _TimeToken;
  109355. })(BABYLON || (BABYLON = {}));
  109356. //# sourceMappingURL=babylon.timeToken.js.map
  109357. var BABYLON;
  109358. (function (BABYLON) {
  109359. /**
  109360. * Background material defines definition.
  109361. * @hidden Mainly internal Use
  109362. */
  109363. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  109364. __extends(BackgroundMaterialDefines, _super);
  109365. /**
  109366. * Constructor of the defines.
  109367. */
  109368. function BackgroundMaterialDefines() {
  109369. var _this = _super.call(this) || this;
  109370. /**
  109371. * True if the diffuse texture is in use.
  109372. */
  109373. _this.DIFFUSE = false;
  109374. /**
  109375. * The direct UV channel to use.
  109376. */
  109377. _this.DIFFUSEDIRECTUV = 0;
  109378. /**
  109379. * True if the diffuse texture is in gamma space.
  109380. */
  109381. _this.GAMMADIFFUSE = false;
  109382. /**
  109383. * True if the diffuse texture has opacity in the alpha channel.
  109384. */
  109385. _this.DIFFUSEHASALPHA = false;
  109386. /**
  109387. * True if you want the material to fade to transparent at grazing angle.
  109388. */
  109389. _this.OPACITYFRESNEL = false;
  109390. /**
  109391. * True if an extra blur needs to be added in the reflection.
  109392. */
  109393. _this.REFLECTIONBLUR = false;
  109394. /**
  109395. * True if you want the material to fade to reflection at grazing angle.
  109396. */
  109397. _this.REFLECTIONFRESNEL = false;
  109398. /**
  109399. * True if you want the material to falloff as far as you move away from the scene center.
  109400. */
  109401. _this.REFLECTIONFALLOFF = false;
  109402. /**
  109403. * False if the current Webgl implementation does not support the texture lod extension.
  109404. */
  109405. _this.TEXTURELODSUPPORT = false;
  109406. /**
  109407. * True to ensure the data are premultiplied.
  109408. */
  109409. _this.PREMULTIPLYALPHA = false;
  109410. /**
  109411. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  109412. */
  109413. _this.USERGBCOLOR = false;
  109414. /**
  109415. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  109416. * stays aligned with the desired configuration.
  109417. */
  109418. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  109419. /**
  109420. * True to add noise in order to reduce the banding effect.
  109421. */
  109422. _this.NOISE = false;
  109423. /**
  109424. * is the reflection texture in BGR color scheme?
  109425. * Mainly used to solve a bug in ios10 video tag
  109426. */
  109427. _this.REFLECTIONBGR = false;
  109428. _this.IMAGEPROCESSING = false;
  109429. _this.VIGNETTE = false;
  109430. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  109431. _this.VIGNETTEBLENDMODEOPAQUE = false;
  109432. _this.TONEMAPPING = false;
  109433. _this.TONEMAPPING_ACES = false;
  109434. _this.CONTRAST = false;
  109435. _this.COLORCURVES = false;
  109436. _this.COLORGRADING = false;
  109437. _this.COLORGRADING3D = false;
  109438. _this.SAMPLER3DGREENDEPTH = false;
  109439. _this.SAMPLER3DBGRMAP = false;
  109440. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  109441. _this.EXPOSURE = false;
  109442. // Reflection.
  109443. _this.REFLECTION = false;
  109444. _this.REFLECTIONMAP_3D = false;
  109445. _this.REFLECTIONMAP_SPHERICAL = false;
  109446. _this.REFLECTIONMAP_PLANAR = false;
  109447. _this.REFLECTIONMAP_CUBIC = false;
  109448. _this.REFLECTIONMAP_PROJECTION = false;
  109449. _this.REFLECTIONMAP_SKYBOX = false;
  109450. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109451. _this.REFLECTIONMAP_EXPLICIT = false;
  109452. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109453. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109454. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109455. _this.INVERTCUBICMAP = false;
  109456. _this.REFLECTIONMAP_OPPOSITEZ = false;
  109457. _this.LODINREFLECTIONALPHA = false;
  109458. _this.GAMMAREFLECTION = false;
  109459. _this.RGBDREFLECTION = false;
  109460. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  109461. // Default BJS.
  109462. _this.MAINUV1 = false;
  109463. _this.MAINUV2 = false;
  109464. _this.UV1 = false;
  109465. _this.UV2 = false;
  109466. _this.CLIPPLANE = false;
  109467. _this.CLIPPLANE2 = false;
  109468. _this.CLIPPLANE3 = false;
  109469. _this.CLIPPLANE4 = false;
  109470. _this.POINTSIZE = false;
  109471. _this.FOG = false;
  109472. _this.NORMAL = false;
  109473. _this.NUM_BONE_INFLUENCERS = 0;
  109474. _this.BonesPerMesh = 0;
  109475. _this.INSTANCES = false;
  109476. _this.SHADOWFLOAT = false;
  109477. _this.rebuild();
  109478. return _this;
  109479. }
  109480. return BackgroundMaterialDefines;
  109481. }(BABYLON.MaterialDefines));
  109482. /**
  109483. * Background material used to create an efficient environement around your scene.
  109484. */
  109485. var BackgroundMaterial = /** @class */ (function (_super) {
  109486. __extends(BackgroundMaterial, _super);
  109487. /**
  109488. * Instantiates a Background Material in the given scene
  109489. * @param name The friendly name of the material
  109490. * @param scene The scene to add the material to
  109491. */
  109492. function BackgroundMaterial(name, scene) {
  109493. var _this = _super.call(this, name, scene) || this;
  109494. /**
  109495. * Key light Color (multiply against the environement texture)
  109496. */
  109497. _this.primaryColor = BABYLON.Color3.White();
  109498. _this._primaryColorShadowLevel = 0;
  109499. _this._primaryColorHighlightLevel = 0;
  109500. /**
  109501. * Reflection Texture used in the material.
  109502. * Should be author in a specific way for the best result (refer to the documentation).
  109503. */
  109504. _this.reflectionTexture = null;
  109505. /**
  109506. * Reflection Texture level of blur.
  109507. *
  109508. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  109509. * texture twice.
  109510. */
  109511. _this.reflectionBlur = 0;
  109512. /**
  109513. * Diffuse Texture used in the material.
  109514. * Should be author in a specific way for the best result (refer to the documentation).
  109515. */
  109516. _this.diffuseTexture = null;
  109517. _this._shadowLights = null;
  109518. /**
  109519. * Specify the list of lights casting shadow on the material.
  109520. * All scene shadow lights will be included if null.
  109521. */
  109522. _this.shadowLights = null;
  109523. /**
  109524. * Helps adjusting the shadow to a softer level if required.
  109525. * 0 means black shadows and 1 means no shadows.
  109526. */
  109527. _this.shadowLevel = 0;
  109528. /**
  109529. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  109530. * It is usually zero but might be interesting to modify according to your setup.
  109531. */
  109532. _this.sceneCenter = BABYLON.Vector3.Zero();
  109533. /**
  109534. * This helps specifying that the material is falling off to the sky box at grazing angle.
  109535. * This helps ensuring a nice transition when the camera goes under the ground.
  109536. */
  109537. _this.opacityFresnel = true;
  109538. /**
  109539. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  109540. * This helps adding a mirror texture on the ground.
  109541. */
  109542. _this.reflectionFresnel = false;
  109543. /**
  109544. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  109545. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  109546. */
  109547. _this.reflectionFalloffDistance = 0.0;
  109548. /**
  109549. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  109550. */
  109551. _this.reflectionAmount = 1.0;
  109552. /**
  109553. * This specifies the weight of the reflection at grazing angle.
  109554. */
  109555. _this.reflectionReflectance0 = 0.05;
  109556. /**
  109557. * This specifies the weight of the reflection at a perpendicular point of view.
  109558. */
  109559. _this.reflectionReflectance90 = 0.5;
  109560. /**
  109561. * Helps to directly use the maps channels instead of their level.
  109562. */
  109563. _this.useRGBColor = true;
  109564. /**
  109565. * This helps reducing the banding effect that could occur on the background.
  109566. */
  109567. _this.enableNoise = false;
  109568. _this._fovMultiplier = 1.0;
  109569. /**
  109570. * Enable the FOV adjustment feature controlled by fovMultiplier.
  109571. */
  109572. _this.useEquirectangularFOV = false;
  109573. _this._maxSimultaneousLights = 4;
  109574. /**
  109575. * Number of Simultaneous lights allowed on the material.
  109576. */
  109577. _this.maxSimultaneousLights = 4;
  109578. /**
  109579. * Keep track of the image processing observer to allow dispose and replace.
  109580. */
  109581. _this._imageProcessingObserver = null;
  109582. /**
  109583. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  109584. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  109585. */
  109586. _this.switchToBGR = false;
  109587. // Temp values kept as cache in the material.
  109588. _this._renderTargets = new BABYLON.SmartArray(16);
  109589. _this._reflectionControls = BABYLON.Vector4.Zero();
  109590. _this._white = BABYLON.Color3.White();
  109591. _this._primaryShadowColor = BABYLON.Color3.Black();
  109592. _this._primaryHighlightColor = BABYLON.Color3.Black();
  109593. // Setup the default processing configuration to the scene.
  109594. _this._attachImageProcessingConfiguration(null);
  109595. _this.getRenderTargetTextures = function () {
  109596. _this._renderTargets.reset();
  109597. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  109598. _this._renderTargets.push(_this._diffuseTexture);
  109599. }
  109600. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  109601. _this._renderTargets.push(_this._reflectionTexture);
  109602. }
  109603. return _this._renderTargets;
  109604. };
  109605. return _this;
  109606. }
  109607. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  109608. /**
  109609. * Experimental Internal Use Only.
  109610. *
  109611. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  109612. * This acts as a helper to set the primary color to a more "human friendly" value.
  109613. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  109614. * output color as close as possible from the chosen value.
  109615. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  109616. * part of lighting setup.)
  109617. */
  109618. get: function () {
  109619. return this.__perceptualColor;
  109620. },
  109621. set: function (value) {
  109622. this.__perceptualColor = value;
  109623. this._computePrimaryColorFromPerceptualColor();
  109624. this._markAllSubMeshesAsLightsDirty();
  109625. },
  109626. enumerable: true,
  109627. configurable: true
  109628. });
  109629. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  109630. /**
  109631. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  109632. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  109633. */
  109634. get: function () {
  109635. return this._primaryColorShadowLevel;
  109636. },
  109637. set: function (value) {
  109638. this._primaryColorShadowLevel = value;
  109639. this._computePrimaryColors();
  109640. this._markAllSubMeshesAsLightsDirty();
  109641. },
  109642. enumerable: true,
  109643. configurable: true
  109644. });
  109645. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  109646. /**
  109647. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  109648. * The primary color is used at the level chosen to define what the white area would look.
  109649. */
  109650. get: function () {
  109651. return this._primaryColorHighlightLevel;
  109652. },
  109653. set: function (value) {
  109654. this._primaryColorHighlightLevel = value;
  109655. this._computePrimaryColors();
  109656. this._markAllSubMeshesAsLightsDirty();
  109657. },
  109658. enumerable: true,
  109659. configurable: true
  109660. });
  109661. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  109662. /**
  109663. * Sets the reflection reflectance fresnel values according to the default standard
  109664. * empirically know to work well :-)
  109665. */
  109666. set: function (value) {
  109667. var reflectionWeight = value;
  109668. if (reflectionWeight < 0.5) {
  109669. reflectionWeight = reflectionWeight * 2.0;
  109670. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  109671. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  109672. }
  109673. else {
  109674. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  109675. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  109676. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  109677. }
  109678. },
  109679. enumerable: true,
  109680. configurable: true
  109681. });
  109682. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  109683. /**
  109684. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109685. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  109686. * Recommended to be keep at 1.0 except for special cases.
  109687. */
  109688. get: function () {
  109689. return this._fovMultiplier;
  109690. },
  109691. set: function (value) {
  109692. if (isNaN(value)) {
  109693. value = 1.0;
  109694. }
  109695. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  109696. },
  109697. enumerable: true,
  109698. configurable: true
  109699. });
  109700. /**
  109701. * Attaches a new image processing configuration to the PBR Material.
  109702. * @param configuration (if null the scene configuration will be use)
  109703. */
  109704. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  109705. var _this = this;
  109706. if (configuration === this._imageProcessingConfiguration) {
  109707. return;
  109708. }
  109709. // Detaches observer.
  109710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  109711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  109712. }
  109713. // Pick the scene configuration if needed.
  109714. if (!configuration) {
  109715. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  109716. }
  109717. else {
  109718. this._imageProcessingConfiguration = configuration;
  109719. }
  109720. // Attaches observer.
  109721. if (this._imageProcessingConfiguration) {
  109722. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  109723. _this._computePrimaryColorFromPerceptualColor();
  109724. _this._markAllSubMeshesAsImageProcessingDirty();
  109725. });
  109726. }
  109727. };
  109728. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  109729. /**
  109730. * Gets the image processing configuration used either in this material.
  109731. */
  109732. get: function () {
  109733. return this._imageProcessingConfiguration;
  109734. },
  109735. /**
  109736. * Sets the Default image processing configuration used either in the this material.
  109737. *
  109738. * If sets to null, the scene one is in use.
  109739. */
  109740. set: function (value) {
  109741. this._attachImageProcessingConfiguration(value);
  109742. // Ensure the effect will be rebuilt.
  109743. this._markAllSubMeshesAsTexturesDirty();
  109744. },
  109745. enumerable: true,
  109746. configurable: true
  109747. });
  109748. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  109749. /**
  109750. * Gets wether the color curves effect is enabled.
  109751. */
  109752. get: function () {
  109753. return this.imageProcessingConfiguration.colorCurvesEnabled;
  109754. },
  109755. /**
  109756. * Sets wether the color curves effect is enabled.
  109757. */
  109758. set: function (value) {
  109759. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  109760. },
  109761. enumerable: true,
  109762. configurable: true
  109763. });
  109764. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  109765. /**
  109766. * Gets wether the color grading effect is enabled.
  109767. */
  109768. get: function () {
  109769. return this.imageProcessingConfiguration.colorGradingEnabled;
  109770. },
  109771. /**
  109772. * Gets wether the color grading effect is enabled.
  109773. */
  109774. set: function (value) {
  109775. this.imageProcessingConfiguration.colorGradingEnabled = value;
  109776. },
  109777. enumerable: true,
  109778. configurable: true
  109779. });
  109780. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  109781. /**
  109782. * Gets wether tonemapping is enabled or not.
  109783. */
  109784. get: function () {
  109785. return this._imageProcessingConfiguration.toneMappingEnabled;
  109786. },
  109787. /**
  109788. * Sets wether tonemapping is enabled or not
  109789. */
  109790. set: function (value) {
  109791. this._imageProcessingConfiguration.toneMappingEnabled = value;
  109792. },
  109793. enumerable: true,
  109794. configurable: true
  109795. });
  109796. ;
  109797. ;
  109798. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  109799. /**
  109800. * The camera exposure used on this material.
  109801. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109802. * This corresponds to a photographic exposure.
  109803. */
  109804. get: function () {
  109805. return this._imageProcessingConfiguration.exposure;
  109806. },
  109807. /**
  109808. * The camera exposure used on this material.
  109809. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109810. * This corresponds to a photographic exposure.
  109811. */
  109812. set: function (value) {
  109813. this._imageProcessingConfiguration.exposure = value;
  109814. },
  109815. enumerable: true,
  109816. configurable: true
  109817. });
  109818. ;
  109819. ;
  109820. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  109821. /**
  109822. * Gets The camera contrast used on this material.
  109823. */
  109824. get: function () {
  109825. return this._imageProcessingConfiguration.contrast;
  109826. },
  109827. /**
  109828. * Sets The camera contrast used on this material.
  109829. */
  109830. set: function (value) {
  109831. this._imageProcessingConfiguration.contrast = value;
  109832. },
  109833. enumerable: true,
  109834. configurable: true
  109835. });
  109836. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  109837. /**
  109838. * Gets the Color Grading 2D Lookup Texture.
  109839. */
  109840. get: function () {
  109841. return this._imageProcessingConfiguration.colorGradingTexture;
  109842. },
  109843. /**
  109844. * Sets the Color Grading 2D Lookup Texture.
  109845. */
  109846. set: function (value) {
  109847. this.imageProcessingConfiguration.colorGradingTexture = value;
  109848. },
  109849. enumerable: true,
  109850. configurable: true
  109851. });
  109852. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  109853. /**
  109854. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109855. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109856. * 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;
  109857. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109858. */
  109859. get: function () {
  109860. return this.imageProcessingConfiguration.colorCurves;
  109861. },
  109862. /**
  109863. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109864. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109865. * 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;
  109866. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109867. */
  109868. set: function (value) {
  109869. this.imageProcessingConfiguration.colorCurves = value;
  109870. },
  109871. enumerable: true,
  109872. configurable: true
  109873. });
  109874. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  109875. /**
  109876. * Gets a boolean indicating that current material needs to register RTT
  109877. */
  109878. get: function () {
  109879. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  109880. return true;
  109881. }
  109882. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  109883. return true;
  109884. }
  109885. return false;
  109886. },
  109887. enumerable: true,
  109888. configurable: true
  109889. });
  109890. /**
  109891. * The entire material has been created in order to prevent overdraw.
  109892. * @returns false
  109893. */
  109894. BackgroundMaterial.prototype.needAlphaTesting = function () {
  109895. return true;
  109896. };
  109897. /**
  109898. * The entire material has been created in order to prevent overdraw.
  109899. * @returns true if blending is enable
  109900. */
  109901. BackgroundMaterial.prototype.needAlphaBlending = function () {
  109902. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  109903. };
  109904. /**
  109905. * Checks wether the material is ready to be rendered for a given mesh.
  109906. * @param mesh The mesh to render
  109907. * @param subMesh The submesh to check against
  109908. * @param useInstances Specify wether or not the material is used with instances
  109909. * @returns true if all the dependencies are ready (Textures, Effects...)
  109910. */
  109911. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  109912. var _this = this;
  109913. if (useInstances === void 0) { useInstances = false; }
  109914. if (subMesh.effect && this.isFrozen) {
  109915. if (this._wasPreviouslyReady) {
  109916. return true;
  109917. }
  109918. }
  109919. if (!subMesh._materialDefines) {
  109920. subMesh._materialDefines = new BackgroundMaterialDefines();
  109921. }
  109922. var scene = this.getScene();
  109923. var defines = subMesh._materialDefines;
  109924. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  109925. if (defines._renderId === scene.getRenderId()) {
  109926. return true;
  109927. }
  109928. }
  109929. var engine = scene.getEngine();
  109930. // Lights
  109931. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  109932. defines._needNormals = true;
  109933. // Textures
  109934. if (defines._areTexturesDirty) {
  109935. defines._needUVs = false;
  109936. if (scene.texturesEnabled) {
  109937. if (scene.getEngine().getCaps().textureLOD) {
  109938. defines.TEXTURELODSUPPORT = true;
  109939. }
  109940. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109941. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  109942. return false;
  109943. }
  109944. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  109945. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  109946. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  109947. defines.OPACITYFRESNEL = this._opacityFresnel;
  109948. }
  109949. else {
  109950. defines.DIFFUSE = false;
  109951. defines.DIFFUSEHASALPHA = false;
  109952. defines.GAMMADIFFUSE = false;
  109953. defines.OPACITYFRESNEL = false;
  109954. }
  109955. var reflectionTexture = this._reflectionTexture;
  109956. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  109957. if (!reflectionTexture.isReadyOrNotBlocking()) {
  109958. return false;
  109959. }
  109960. defines.REFLECTION = true;
  109961. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  109962. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  109963. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  109964. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  109965. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  109966. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  109967. defines.REFLECTIONBGR = this.switchToBGR;
  109968. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  109969. defines.INVERTCUBICMAP = true;
  109970. }
  109971. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  109972. switch (reflectionTexture.coordinatesMode) {
  109973. case BABYLON.Texture.EXPLICIT_MODE:
  109974. defines.REFLECTIONMAP_EXPLICIT = true;
  109975. break;
  109976. case BABYLON.Texture.PLANAR_MODE:
  109977. defines.REFLECTIONMAP_PLANAR = true;
  109978. break;
  109979. case BABYLON.Texture.PROJECTION_MODE:
  109980. defines.REFLECTIONMAP_PROJECTION = true;
  109981. break;
  109982. case BABYLON.Texture.SKYBOX_MODE:
  109983. defines.REFLECTIONMAP_SKYBOX = true;
  109984. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  109985. break;
  109986. case BABYLON.Texture.SPHERICAL_MODE:
  109987. defines.REFLECTIONMAP_SPHERICAL = true;
  109988. break;
  109989. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  109990. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  109991. break;
  109992. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  109993. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  109994. break;
  109995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  109996. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  109997. break;
  109998. case BABYLON.Texture.CUBIC_MODE:
  109999. case BABYLON.Texture.INVCUBIC_MODE:
  110000. default:
  110001. defines.REFLECTIONMAP_CUBIC = true;
  110002. break;
  110003. }
  110004. if (this.reflectionFresnel) {
  110005. defines.REFLECTIONFRESNEL = true;
  110006. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110007. this._reflectionControls.x = this.reflectionAmount;
  110008. this._reflectionControls.y = this.reflectionReflectance0;
  110009. this._reflectionControls.z = this.reflectionReflectance90;
  110010. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110011. }
  110012. else {
  110013. defines.REFLECTIONFRESNEL = false;
  110014. defines.REFLECTIONFALLOFF = false;
  110015. }
  110016. }
  110017. else {
  110018. defines.REFLECTION = false;
  110019. defines.REFLECTIONFRESNEL = false;
  110020. defines.REFLECTIONFALLOFF = false;
  110021. defines.REFLECTIONBLUR = false;
  110022. defines.REFLECTIONMAP_3D = false;
  110023. defines.REFLECTIONMAP_SPHERICAL = false;
  110024. defines.REFLECTIONMAP_PLANAR = false;
  110025. defines.REFLECTIONMAP_CUBIC = false;
  110026. defines.REFLECTIONMAP_PROJECTION = false;
  110027. defines.REFLECTIONMAP_SKYBOX = false;
  110028. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110029. defines.REFLECTIONMAP_EXPLICIT = false;
  110030. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110031. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110032. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110033. defines.INVERTCUBICMAP = false;
  110034. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110035. defines.LODINREFLECTIONALPHA = false;
  110036. defines.GAMMAREFLECTION = false;
  110037. defines.RGBDREFLECTION = false;
  110038. }
  110039. }
  110040. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110041. defines.USERGBCOLOR = this._useRGBColor;
  110042. defines.NOISE = this._enableNoise;
  110043. }
  110044. if (defines._areLightsDirty) {
  110045. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  110046. }
  110047. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  110048. if (!this._imageProcessingConfiguration.isReady()) {
  110049. return false;
  110050. }
  110051. this._imageProcessingConfiguration.prepareDefines(defines);
  110052. }
  110053. // Misc.
  110054. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  110055. // Values that need to be evaluated on every frame
  110056. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  110057. // Attribs
  110058. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  110059. if (mesh) {
  110060. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  110061. mesh.createNormals(true);
  110062. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  110063. }
  110064. }
  110065. }
  110066. // Get correct effect
  110067. if (defines.isDirty) {
  110068. defines.markAsProcessed();
  110069. scene.resetCachedMaterial();
  110070. // Fallbacks
  110071. var fallbacks = new BABYLON.EffectFallbacks();
  110072. if (defines.FOG) {
  110073. fallbacks.addFallback(0, "FOG");
  110074. }
  110075. if (defines.POINTSIZE) {
  110076. fallbacks.addFallback(1, "POINTSIZE");
  110077. }
  110078. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  110079. if (defines.NUM_BONE_INFLUENCERS > 0) {
  110080. fallbacks.addCPUSkinningFallback(0, mesh);
  110081. }
  110082. //Attributes
  110083. var attribs = [BABYLON.VertexBuffer.PositionKind];
  110084. if (defines.NORMAL) {
  110085. attribs.push(BABYLON.VertexBuffer.NormalKind);
  110086. }
  110087. if (defines.UV1) {
  110088. attribs.push(BABYLON.VertexBuffer.UVKind);
  110089. }
  110090. if (defines.UV2) {
  110091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110092. }
  110093. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  110094. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  110095. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  110096. "vFogInfos", "vFogColor", "pointSize",
  110097. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  110098. "vPrimaryColor", "vPrimaryColorShadow",
  110099. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  110100. "shadowLevel", "alpha",
  110101. "vBackgroundCenter", "vReflectionControl",
  110102. "vDiffuseInfos", "diffuseMatrix",
  110103. ];
  110104. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  110105. var uniformBuffers = ["Material", "Scene"];
  110106. if (BABYLON.ImageProcessingConfiguration) {
  110107. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  110108. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  110109. }
  110110. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  110111. uniformsNames: uniforms,
  110112. uniformBuffersNames: uniformBuffers,
  110113. samplers: samplers,
  110114. defines: defines,
  110115. maxSimultaneousLights: this._maxSimultaneousLights
  110116. });
  110117. var onCompiled = function (effect) {
  110118. if (_this.onCompiled) {
  110119. _this.onCompiled(effect);
  110120. }
  110121. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  110122. };
  110123. var join = defines.toString();
  110124. subMesh.setEffect(scene.getEngine().createEffect("background", {
  110125. attributes: attribs,
  110126. uniformsNames: uniforms,
  110127. uniformBuffersNames: uniformBuffers,
  110128. samplers: samplers,
  110129. defines: join,
  110130. fallbacks: fallbacks,
  110131. onCompiled: onCompiled,
  110132. onError: this.onError,
  110133. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  110134. }, engine), defines);
  110135. this.buildUniformLayout();
  110136. }
  110137. if (!subMesh.effect || !subMesh.effect.isReady()) {
  110138. return false;
  110139. }
  110140. defines._renderId = scene.getRenderId();
  110141. this._wasPreviouslyReady = true;
  110142. return true;
  110143. };
  110144. /**
  110145. * Compute the primary color according to the chosen perceptual color.
  110146. */
  110147. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  110148. if (!this.__perceptualColor) {
  110149. return;
  110150. }
  110151. this._primaryColor.copyFrom(this.__perceptualColor);
  110152. // Revert gamma space.
  110153. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  110154. // Revert image processing configuration.
  110155. if (this._imageProcessingConfiguration) {
  110156. // Revert Exposure.
  110157. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  110158. }
  110159. this._computePrimaryColors();
  110160. };
  110161. /**
  110162. * Compute the highlights and shadow colors according to their chosen levels.
  110163. */
  110164. BackgroundMaterial.prototype._computePrimaryColors = function () {
  110165. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  110166. return;
  110167. }
  110168. // Find the highlight color based on the configuration.
  110169. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  110170. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  110171. // Find the shadow color based on the configuration.
  110172. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  110173. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  110174. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  110175. };
  110176. /**
  110177. * Build the uniform buffer used in the material.
  110178. */
  110179. BackgroundMaterial.prototype.buildUniformLayout = function () {
  110180. // Order is important !
  110181. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  110182. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  110183. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  110184. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  110185. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  110186. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  110187. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  110188. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  110189. this._uniformBuffer.addUniform("pointSize", 1);
  110190. this._uniformBuffer.addUniform("shadowLevel", 1);
  110191. this._uniformBuffer.addUniform("alpha", 1);
  110192. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  110193. this._uniformBuffer.addUniform("vReflectionControl", 4);
  110194. this._uniformBuffer.create();
  110195. };
  110196. /**
  110197. * Unbind the material.
  110198. */
  110199. BackgroundMaterial.prototype.unbind = function () {
  110200. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110201. this._uniformBuffer.setTexture("diffuseSampler", null);
  110202. }
  110203. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110204. this._uniformBuffer.setTexture("reflectionSampler", null);
  110205. }
  110206. _super.prototype.unbind.call(this);
  110207. };
  110208. /**
  110209. * Bind only the world matrix to the material.
  110210. * @param world The world matrix to bind.
  110211. */
  110212. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  110213. this._activeEffect.setMatrix("world", world);
  110214. };
  110215. /**
  110216. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  110217. * @param world The world matrix to bind.
  110218. * @param subMesh The submesh to bind for.
  110219. */
  110220. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  110221. var scene = this.getScene();
  110222. var defines = subMesh._materialDefines;
  110223. if (!defines) {
  110224. return;
  110225. }
  110226. var effect = subMesh.effect;
  110227. if (!effect) {
  110228. return;
  110229. }
  110230. this._activeEffect = effect;
  110231. // Matrices
  110232. this.bindOnlyWorldMatrix(world);
  110233. // Bones
  110234. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  110235. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  110236. if (mustRebind) {
  110237. this._uniformBuffer.bindToEffect(effect, "Material");
  110238. this.bindViewProjection(effect);
  110239. var reflectionTexture = this._reflectionTexture;
  110240. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  110241. // Texture uniforms
  110242. if (scene.texturesEnabled) {
  110243. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110244. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  110245. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  110246. }
  110247. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110248. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  110249. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  110250. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  110251. }
  110252. }
  110253. if (this.shadowLevel > 0) {
  110254. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  110255. }
  110256. this._uniformBuffer.updateFloat("alpha", this.alpha);
  110257. // Point size
  110258. if (this.pointsCloud) {
  110259. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  110260. }
  110261. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  110262. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  110263. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  110264. }
  110265. else {
  110266. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  110267. }
  110268. }
  110269. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  110270. // Textures
  110271. if (scene.texturesEnabled) {
  110272. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110273. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  110274. }
  110275. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110276. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  110277. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110278. }
  110279. else if (!defines.REFLECTIONBLUR) {
  110280. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110281. }
  110282. else {
  110283. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  110284. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  110285. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  110286. }
  110287. if (defines.REFLECTIONFRESNEL) {
  110288. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  110289. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  110290. }
  110291. }
  110292. }
  110293. // Clip plane
  110294. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  110295. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  110296. }
  110297. if (mustRebind || !this.isFrozen) {
  110298. if (scene.lightsEnabled) {
  110299. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  110300. }
  110301. // View
  110302. this.bindView(effect);
  110303. // Fog
  110304. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  110305. // image processing
  110306. if (this._imageProcessingConfiguration) {
  110307. this._imageProcessingConfiguration.bind(this._activeEffect);
  110308. }
  110309. }
  110310. this._uniformBuffer.update();
  110311. this._afterBind(mesh, this._activeEffect);
  110312. };
  110313. /**
  110314. * Dispose the material.
  110315. * @param forceDisposeEffect Force disposal of the associated effect.
  110316. * @param forceDisposeTextures Force disposal of the associated textures.
  110317. */
  110318. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  110319. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  110320. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  110321. if (forceDisposeTextures) {
  110322. if (this.diffuseTexture) {
  110323. this.diffuseTexture.dispose();
  110324. }
  110325. if (this.reflectionTexture) {
  110326. this.reflectionTexture.dispose();
  110327. }
  110328. }
  110329. this._renderTargets.dispose();
  110330. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110331. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110332. }
  110333. _super.prototype.dispose.call(this, forceDisposeEffect);
  110334. };
  110335. /**
  110336. * Clones the material.
  110337. * @param name The cloned name.
  110338. * @returns The cloned material.
  110339. */
  110340. BackgroundMaterial.prototype.clone = function (name) {
  110341. var _this = this;
  110342. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  110343. };
  110344. /**
  110345. * Serializes the current material to its JSON representation.
  110346. * @returns The JSON representation.
  110347. */
  110348. BackgroundMaterial.prototype.serialize = function () {
  110349. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110350. serializationObject.customType = "BABYLON.BackgroundMaterial";
  110351. return serializationObject;
  110352. };
  110353. /**
  110354. * Gets the class name of the material
  110355. * @returns "BackgroundMaterial"
  110356. */
  110357. BackgroundMaterial.prototype.getClassName = function () {
  110358. return "BackgroundMaterial";
  110359. };
  110360. /**
  110361. * Parse a JSON input to create back a background material.
  110362. * @param source The JSON data to parse
  110363. * @param scene The scene to create the parsed material in
  110364. * @param rootUrl The root url of the assets the material depends upon
  110365. * @returns the instantiated BackgroundMaterial.
  110366. */
  110367. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  110368. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  110369. };
  110370. /**
  110371. * Standard reflectance value at parallel view angle.
  110372. */
  110373. BackgroundMaterial.StandardReflectance0 = 0.05;
  110374. /**
  110375. * Standard reflectance value at grazing angle.
  110376. */
  110377. BackgroundMaterial.StandardReflectance90 = 0.5;
  110378. __decorate([
  110379. BABYLON.serializeAsColor3()
  110380. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  110381. __decorate([
  110382. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110383. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  110384. __decorate([
  110385. BABYLON.serializeAsColor3()
  110386. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  110387. __decorate([
  110388. BABYLON.serialize()
  110389. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  110390. __decorate([
  110391. BABYLON.serialize()
  110392. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  110393. __decorate([
  110394. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110395. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  110396. __decorate([
  110397. BABYLON.serializeAsTexture()
  110398. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  110399. __decorate([
  110400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110401. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  110402. __decorate([
  110403. BABYLON.serialize()
  110404. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  110405. __decorate([
  110406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110407. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  110408. __decorate([
  110409. BABYLON.serializeAsTexture()
  110410. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  110411. __decorate([
  110412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110413. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  110414. __decorate([
  110415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110416. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  110417. __decorate([
  110418. BABYLON.serialize()
  110419. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  110420. __decorate([
  110421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110422. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  110423. __decorate([
  110424. BABYLON.serializeAsVector3()
  110425. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  110426. __decorate([
  110427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110428. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  110429. __decorate([
  110430. BABYLON.serialize()
  110431. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  110432. __decorate([
  110433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110434. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  110435. __decorate([
  110436. BABYLON.serialize()
  110437. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  110438. __decorate([
  110439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110440. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  110441. __decorate([
  110442. BABYLON.serialize()
  110443. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  110444. __decorate([
  110445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110446. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  110447. __decorate([
  110448. BABYLON.serialize()
  110449. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  110450. __decorate([
  110451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110452. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  110453. __decorate([
  110454. BABYLON.serialize()
  110455. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  110456. __decorate([
  110457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110458. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  110459. __decorate([
  110460. BABYLON.serialize()
  110461. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  110462. __decorate([
  110463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110464. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  110465. __decorate([
  110466. BABYLON.serialize()
  110467. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  110468. __decorate([
  110469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110470. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  110471. __decorate([
  110472. BABYLON.serialize()
  110473. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  110474. __decorate([
  110475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110476. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  110477. __decorate([
  110478. BABYLON.serialize()
  110479. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  110480. __decorate([
  110481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110482. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  110483. __decorate([
  110484. BABYLON.serializeAsImageProcessingConfiguration()
  110485. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  110486. return BackgroundMaterial;
  110487. }(BABYLON.PushMaterial));
  110488. BABYLON.BackgroundMaterial = BackgroundMaterial;
  110489. })(BABYLON || (BABYLON = {}));
  110490. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  110491. var __assign = (this && this.__assign) || function () {
  110492. __assign = Object.assign || function(t) {
  110493. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110494. s = arguments[i];
  110495. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110496. t[p] = s[p];
  110497. }
  110498. return t;
  110499. };
  110500. return __assign.apply(this, arguments);
  110501. };
  110502. var BABYLON;
  110503. (function (BABYLON) {
  110504. /**
  110505. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  110506. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  110507. * It also helps with the default setup of your imageProcessing configuration.
  110508. */
  110509. var EnvironmentHelper = /** @class */ (function () {
  110510. /**
  110511. * constructor
  110512. * @param options
  110513. * @param scene The scene to add the material to
  110514. */
  110515. function EnvironmentHelper(options, scene) {
  110516. var _this = this;
  110517. this._errorHandler = function (message, exception) {
  110518. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  110519. };
  110520. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  110521. this._scene = scene;
  110522. this.onErrorObservable = new BABYLON.Observable();
  110523. this._setupBackground();
  110524. this._setupImageProcessing();
  110525. }
  110526. /**
  110527. * Creates the default options for the helper.
  110528. */
  110529. EnvironmentHelper._getDefaultOptions = function () {
  110530. return {
  110531. createGround: true,
  110532. groundSize: 15,
  110533. groundTexture: this._groundTextureCDNUrl,
  110534. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110535. groundOpacity: 0.9,
  110536. enableGroundShadow: true,
  110537. groundShadowLevel: 0.5,
  110538. enableGroundMirror: false,
  110539. groundMirrorSizeRatio: 0.3,
  110540. groundMirrorBlurKernel: 64,
  110541. groundMirrorAmount: 1,
  110542. groundMirrorFresnelWeight: 1,
  110543. groundMirrorFallOffDistance: 0,
  110544. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  110545. groundYBias: 0.00001,
  110546. createSkybox: true,
  110547. skyboxSize: 20,
  110548. skyboxTexture: this._skyboxTextureCDNUrl,
  110549. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110550. backgroundYRotation: 0,
  110551. sizeAuto: true,
  110552. rootPosition: BABYLON.Vector3.Zero(),
  110553. setupImageProcessing: true,
  110554. environmentTexture: this._environmentTextureCDNUrl,
  110555. cameraExposure: 0.8,
  110556. cameraContrast: 1.2,
  110557. toneMappingEnabled: true,
  110558. };
  110559. };
  110560. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  110561. /**
  110562. * Gets the root mesh created by the helper.
  110563. */
  110564. get: function () {
  110565. return this._rootMesh;
  110566. },
  110567. enumerable: true,
  110568. configurable: true
  110569. });
  110570. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  110571. /**
  110572. * Gets the skybox created by the helper.
  110573. */
  110574. get: function () {
  110575. return this._skybox;
  110576. },
  110577. enumerable: true,
  110578. configurable: true
  110579. });
  110580. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  110581. /**
  110582. * Gets the skybox texture created by the helper.
  110583. */
  110584. get: function () {
  110585. return this._skyboxTexture;
  110586. },
  110587. enumerable: true,
  110588. configurable: true
  110589. });
  110590. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  110591. /**
  110592. * Gets the skybox material created by the helper.
  110593. */
  110594. get: function () {
  110595. return this._skyboxMaterial;
  110596. },
  110597. enumerable: true,
  110598. configurable: true
  110599. });
  110600. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  110601. /**
  110602. * Gets the ground mesh created by the helper.
  110603. */
  110604. get: function () {
  110605. return this._ground;
  110606. },
  110607. enumerable: true,
  110608. configurable: true
  110609. });
  110610. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  110611. /**
  110612. * Gets the ground texture created by the helper.
  110613. */
  110614. get: function () {
  110615. return this._groundTexture;
  110616. },
  110617. enumerable: true,
  110618. configurable: true
  110619. });
  110620. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  110621. /**
  110622. * Gets the ground mirror created by the helper.
  110623. */
  110624. get: function () {
  110625. return this._groundMirror;
  110626. },
  110627. enumerable: true,
  110628. configurable: true
  110629. });
  110630. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  110631. /**
  110632. * Gets the ground mirror render list to helps pushing the meshes
  110633. * you wish in the ground reflection.
  110634. */
  110635. get: function () {
  110636. if (this._groundMirror) {
  110637. return this._groundMirror.renderList;
  110638. }
  110639. return null;
  110640. },
  110641. enumerable: true,
  110642. configurable: true
  110643. });
  110644. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  110645. /**
  110646. * Gets the ground material created by the helper.
  110647. */
  110648. get: function () {
  110649. return this._groundMaterial;
  110650. },
  110651. enumerable: true,
  110652. configurable: true
  110653. });
  110654. /**
  110655. * Updates the background according to the new options
  110656. * @param options
  110657. */
  110658. EnvironmentHelper.prototype.updateOptions = function (options) {
  110659. var newOptions = __assign({}, this._options, options);
  110660. if (this._ground && !newOptions.createGround) {
  110661. this._ground.dispose();
  110662. this._ground = null;
  110663. }
  110664. if (this._groundMaterial && !newOptions.createGround) {
  110665. this._groundMaterial.dispose();
  110666. this._groundMaterial = null;
  110667. }
  110668. if (this._groundTexture) {
  110669. if (this._options.groundTexture != newOptions.groundTexture) {
  110670. this._groundTexture.dispose();
  110671. this._groundTexture = null;
  110672. }
  110673. }
  110674. if (this._skybox && !newOptions.createSkybox) {
  110675. this._skybox.dispose();
  110676. this._skybox = null;
  110677. }
  110678. if (this._skyboxMaterial && !newOptions.createSkybox) {
  110679. this._skyboxMaterial.dispose();
  110680. this._skyboxMaterial = null;
  110681. }
  110682. if (this._skyboxTexture) {
  110683. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  110684. this._skyboxTexture.dispose();
  110685. this._skyboxTexture = null;
  110686. }
  110687. }
  110688. if (this._groundMirror && !newOptions.enableGroundMirror) {
  110689. this._groundMirror.dispose();
  110690. this._groundMirror = null;
  110691. }
  110692. if (this._scene.environmentTexture) {
  110693. if (this._options.environmentTexture != newOptions.environmentTexture) {
  110694. this._scene.environmentTexture.dispose();
  110695. }
  110696. }
  110697. this._options = newOptions;
  110698. this._setupBackground();
  110699. this._setupImageProcessing();
  110700. };
  110701. /**
  110702. * Sets the primary color of all the available elements.
  110703. * @param color the main color to affect to the ground and the background
  110704. */
  110705. EnvironmentHelper.prototype.setMainColor = function (color) {
  110706. if (this.groundMaterial) {
  110707. this.groundMaterial.primaryColor = color;
  110708. }
  110709. if (this.skyboxMaterial) {
  110710. this.skyboxMaterial.primaryColor = color;
  110711. }
  110712. if (this.groundMirror) {
  110713. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  110714. }
  110715. };
  110716. /**
  110717. * Setup the image processing according to the specified options.
  110718. */
  110719. EnvironmentHelper.prototype._setupImageProcessing = function () {
  110720. if (this._options.setupImageProcessing) {
  110721. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  110722. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  110723. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  110724. this._setupEnvironmentTexture();
  110725. }
  110726. };
  110727. /**
  110728. * Setup the environment texture according to the specified options.
  110729. */
  110730. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  110731. if (this._scene.environmentTexture) {
  110732. return;
  110733. }
  110734. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  110735. this._scene.environmentTexture = this._options.environmentTexture;
  110736. return;
  110737. }
  110738. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  110739. this._scene.environmentTexture = environmentTexture;
  110740. };
  110741. /**
  110742. * Setup the background according to the specified options.
  110743. */
  110744. EnvironmentHelper.prototype._setupBackground = function () {
  110745. if (!this._rootMesh) {
  110746. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  110747. }
  110748. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  110749. var sceneSize = this._getSceneSize();
  110750. if (this._options.createGround) {
  110751. this._setupGround(sceneSize);
  110752. this._setupGroundMaterial();
  110753. this._setupGroundDiffuseTexture();
  110754. if (this._options.enableGroundMirror) {
  110755. this._setupGroundMirrorTexture(sceneSize);
  110756. }
  110757. this._setupMirrorInGroundMaterial();
  110758. }
  110759. if (this._options.createSkybox) {
  110760. this._setupSkybox(sceneSize);
  110761. this._setupSkyboxMaterial();
  110762. this._setupSkyboxReflectionTexture();
  110763. }
  110764. this._rootMesh.position.x = sceneSize.rootPosition.x;
  110765. this._rootMesh.position.z = sceneSize.rootPosition.z;
  110766. this._rootMesh.position.y = sceneSize.rootPosition.y;
  110767. };
  110768. /**
  110769. * Get the scene sizes according to the setup.
  110770. */
  110771. EnvironmentHelper.prototype._getSceneSize = function () {
  110772. var _this = this;
  110773. var groundSize = this._options.groundSize;
  110774. var skyboxSize = this._options.skyboxSize;
  110775. var rootPosition = this._options.rootPosition;
  110776. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  110777. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110778. }
  110779. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  110780. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  110781. });
  110782. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110783. if (this._options.sizeAuto) {
  110784. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  110785. this._scene.activeCamera.upperRadiusLimit) {
  110786. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  110787. skyboxSize = groundSize;
  110788. }
  110789. var sceneDiagonalLenght = sceneDiagonal.length();
  110790. if (sceneDiagonalLenght > groundSize) {
  110791. groundSize = sceneDiagonalLenght * 2;
  110792. skyboxSize = groundSize;
  110793. }
  110794. // 10 % bigger.
  110795. groundSize *= 1.1;
  110796. skyboxSize *= 1.5;
  110797. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  110798. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  110799. }
  110800. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110801. };
  110802. /**
  110803. * Setup the ground according to the specified options.
  110804. */
  110805. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  110806. var _this = this;
  110807. if (!this._ground || this._ground.isDisposed()) {
  110808. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  110809. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  110810. this._ground.parent = this._rootMesh;
  110811. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  110812. }
  110813. this._ground.receiveShadows = this._options.enableGroundShadow;
  110814. };
  110815. /**
  110816. * Setup the ground material according to the specified options.
  110817. */
  110818. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  110819. if (!this._groundMaterial) {
  110820. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  110821. }
  110822. this._groundMaterial.alpha = this._options.groundOpacity;
  110823. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  110824. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  110825. this._groundMaterial.primaryColor = this._options.groundColor;
  110826. this._groundMaterial.useRGBColor = false;
  110827. this._groundMaterial.enableNoise = true;
  110828. if (this._ground) {
  110829. this._ground.material = this._groundMaterial;
  110830. }
  110831. };
  110832. /**
  110833. * Setup the ground diffuse texture according to the specified options.
  110834. */
  110835. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  110836. if (!this._groundMaterial) {
  110837. return;
  110838. }
  110839. if (this._groundTexture) {
  110840. return;
  110841. }
  110842. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  110843. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  110844. return;
  110845. }
  110846. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110847. diffuseTexture.gammaSpace = false;
  110848. diffuseTexture.hasAlpha = true;
  110849. this._groundMaterial.diffuseTexture = diffuseTexture;
  110850. };
  110851. /**
  110852. * Setup the ground mirror texture according to the specified options.
  110853. */
  110854. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  110855. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110856. if (!this._groundMirror) {
  110857. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  110858. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  110859. this._groundMirror.anisotropicFilteringLevel = 1;
  110860. this._groundMirror.wrapU = wrapping;
  110861. this._groundMirror.wrapV = wrapping;
  110862. this._groundMirror.gammaSpace = false;
  110863. if (this._groundMirror.renderList) {
  110864. for (var i = 0; i < this._scene.meshes.length; i++) {
  110865. var mesh = this._scene.meshes[i];
  110866. if (mesh !== this._ground &&
  110867. mesh !== this._skybox &&
  110868. mesh !== this._rootMesh) {
  110869. this._groundMirror.renderList.push(mesh);
  110870. }
  110871. }
  110872. }
  110873. }
  110874. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  110875. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  110876. };
  110877. /**
  110878. * Setup the ground to receive the mirror texture.
  110879. */
  110880. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  110881. if (this._groundMaterial) {
  110882. this._groundMaterial.reflectionTexture = this._groundMirror;
  110883. this._groundMaterial.reflectionFresnel = true;
  110884. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  110885. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  110886. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  110887. }
  110888. };
  110889. /**
  110890. * Setup the skybox according to the specified options.
  110891. */
  110892. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  110893. var _this = this;
  110894. if (!this._skybox || this._skybox.isDisposed()) {
  110895. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  110896. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  110897. }
  110898. this._skybox.parent = this._rootMesh;
  110899. };
  110900. /**
  110901. * Setup the skybox material according to the specified options.
  110902. */
  110903. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  110904. if (!this._skybox) {
  110905. return;
  110906. }
  110907. if (!this._skyboxMaterial) {
  110908. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  110909. }
  110910. this._skyboxMaterial.useRGBColor = false;
  110911. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  110912. this._skyboxMaterial.enableNoise = true;
  110913. this._skybox.material = this._skyboxMaterial;
  110914. };
  110915. /**
  110916. * Setup the skybox reflection texture according to the specified options.
  110917. */
  110918. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  110919. if (!this._skyboxMaterial) {
  110920. return;
  110921. }
  110922. if (this._skyboxTexture) {
  110923. return;
  110924. }
  110925. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  110926. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  110927. return;
  110928. }
  110929. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110930. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110931. this._skyboxTexture.gammaSpace = false;
  110932. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  110933. };
  110934. /**
  110935. * Dispose all the elements created by the Helper.
  110936. */
  110937. EnvironmentHelper.prototype.dispose = function () {
  110938. if (this._groundMaterial) {
  110939. this._groundMaterial.dispose(true, true);
  110940. }
  110941. if (this._skyboxMaterial) {
  110942. this._skyboxMaterial.dispose(true, true);
  110943. }
  110944. this._rootMesh.dispose(false);
  110945. };
  110946. /**
  110947. * Default ground texture URL.
  110948. */
  110949. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  110950. /**
  110951. * Default skybox texture URL.
  110952. */
  110953. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  110954. /**
  110955. * Default environment texture URL.
  110956. */
  110957. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  110958. return EnvironmentHelper;
  110959. }());
  110960. BABYLON.EnvironmentHelper = EnvironmentHelper;
  110961. })(BABYLON || (BABYLON = {}));
  110962. //# sourceMappingURL=babylon.environmentHelper.js.map
  110963. var BABYLON;
  110964. (function (BABYLON) {
  110965. /** Internal class used to store shapes for emitters */
  110966. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  110967. function ParticleSystemSetEmitterCreationOptions() {
  110968. }
  110969. return ParticleSystemSetEmitterCreationOptions;
  110970. }());
  110971. /**
  110972. * Represents a set of particle systems working together to create a specific effect
  110973. */
  110974. var ParticleSystemSet = /** @class */ (function () {
  110975. function ParticleSystemSet() {
  110976. /**
  110977. * Gets the particle system list
  110978. */
  110979. this.systems = new Array();
  110980. }
  110981. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  110982. /**
  110983. * Gets the emitter node used with this set
  110984. */
  110985. get: function () {
  110986. return this._emitterNode;
  110987. },
  110988. enumerable: true,
  110989. configurable: true
  110990. });
  110991. /**
  110992. * Creates a new emitter mesh as a sphere
  110993. * @param options defines the options used to create the sphere
  110994. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  110995. * @param scene defines the hosting scene
  110996. */
  110997. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  110998. if (this._emitterNode) {
  110999. this._emitterNode.dispose();
  111000. }
  111001. this._emitterCreationOptions = {
  111002. kind: "Sphere",
  111003. options: options,
  111004. renderingGroupId: renderingGroupId
  111005. };
  111006. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111007. emitterMesh.renderingGroupId = renderingGroupId;
  111008. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111009. material.emissiveColor = options.color;
  111010. emitterMesh.material = material;
  111011. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111012. var system = _a[_i];
  111013. system.emitter = emitterMesh;
  111014. }
  111015. this._emitterNode = emitterMesh;
  111016. };
  111017. /**
  111018. * Starts all particle systems of the set
  111019. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111020. */
  111021. ParticleSystemSet.prototype.start = function (emitter) {
  111022. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111023. var system = _a[_i];
  111024. if (emitter) {
  111025. system.emitter = emitter;
  111026. }
  111027. system.start();
  111028. }
  111029. };
  111030. /**
  111031. * Release all associated resources
  111032. */
  111033. ParticleSystemSet.prototype.dispose = function () {
  111034. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111035. var system = _a[_i];
  111036. system.dispose();
  111037. }
  111038. this.systems = [];
  111039. if (this._emitterNode) {
  111040. this._emitterNode.dispose();
  111041. this._emitterNode = null;
  111042. }
  111043. };
  111044. /**
  111045. * Serialize the set into a JSON compatible object
  111046. * @returns a JSON compatible representation of the set
  111047. */
  111048. ParticleSystemSet.prototype.serialize = function () {
  111049. var result = {};
  111050. result.systems = [];
  111051. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111052. var system = _a[_i];
  111053. result.systems.push(system.serialize());
  111054. }
  111055. if (this._emitterNode) {
  111056. result.emitter = this._emitterCreationOptions;
  111057. }
  111058. return result;
  111059. };
  111060. /**
  111061. * Parse a new ParticleSystemSet from a serialized source
  111062. * @param data defines a JSON compatible representation of the set
  111063. * @param scene defines the hosting scene
  111064. * @param gpu defines if we want GPU particles or CPU particles
  111065. * @returns a new ParticleSystemSet
  111066. */
  111067. ParticleSystemSet.Parse = function (data, scene, gpu) {
  111068. if (gpu === void 0) { gpu = false; }
  111069. var result = new ParticleSystemSet();
  111070. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  111071. scene = scene || BABYLON.Engine.LastCreatedScene;
  111072. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  111073. var system = _a[_i];
  111074. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  111075. }
  111076. if (data.emitter) {
  111077. var options = data.emitter.options;
  111078. switch (data.emitter.kind) {
  111079. case "Sphere":
  111080. result.setEmitterAsSphere({
  111081. diameter: options.diameter,
  111082. segments: options.segments,
  111083. color: BABYLON.Color3.FromArray(options.color)
  111084. }, data.emitter.renderingGroupId, scene);
  111085. break;
  111086. }
  111087. }
  111088. return result;
  111089. };
  111090. return ParticleSystemSet;
  111091. }());
  111092. BABYLON.ParticleSystemSet = ParticleSystemSet;
  111093. })(BABYLON || (BABYLON = {}));
  111094. //# sourceMappingURL=babylon.particleSystemSet.js.map
  111095. var BABYLON;
  111096. (function (BABYLON) {
  111097. /**
  111098. * This class is made for on one-liner static method to help creating particle system set.
  111099. */
  111100. var ParticleHelper = /** @class */ (function () {
  111101. function ParticleHelper() {
  111102. }
  111103. /**
  111104. * Create a default particle system that you can tweak
  111105. * @param emitter defines the emitter to use
  111106. * @param capacity defines the system capacity (default is 500 particles)
  111107. * @param scene defines the hosting scene
  111108. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  111109. * @returns the new Particle system
  111110. */
  111111. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  111112. if (capacity === void 0) { capacity = 500; }
  111113. if (useGPU === void 0) { useGPU = false; }
  111114. var system;
  111115. if (useGPU) {
  111116. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  111117. }
  111118. else {
  111119. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  111120. }
  111121. system.emitter = emitter;
  111122. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  111123. system.createConeEmitter(0.1, Math.PI / 4);
  111124. // Particle color
  111125. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  111126. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  111127. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  111128. // Particle Size
  111129. system.minSize = 0.1;
  111130. system.maxSize = 0.1;
  111131. // Emission speed
  111132. system.minEmitPower = 2;
  111133. system.maxEmitPower = 2;
  111134. // Update speed
  111135. system.updateSpeed = 1 / 60;
  111136. system.emitRate = 30;
  111137. return system;
  111138. };
  111139. /**
  111140. * This is the main static method (one-liner) of this helper to create different particle systems
  111141. * @param type This string represents the type to the particle system to create
  111142. * @param scene The scene where the particle system should live
  111143. * @param gpu If the system will use gpu
  111144. * @returns the ParticleSystemSet created
  111145. */
  111146. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  111147. if (gpu === void 0) { gpu = false; }
  111148. if (!scene) {
  111149. scene = BABYLON.Engine.LastCreatedScene;
  111150. ;
  111151. }
  111152. var token = {};
  111153. scene._addPendingData(token);
  111154. return new Promise(function (resolve, reject) {
  111155. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  111156. scene._removePendingData(token);
  111157. return reject("Particle system with GPU is not supported.");
  111158. }
  111159. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  111160. scene._removePendingData(token);
  111161. var newData = JSON.parse(data.toString());
  111162. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  111163. }, undefined, undefined, undefined, function (req, exception) {
  111164. scene._removePendingData(token);
  111165. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  111166. });
  111167. });
  111168. };
  111169. /**
  111170. * Static function used to export a particle system to a ParticleSystemSet variable.
  111171. * Please note that the emitter shape is not exported
  111172. * @param system defines the particle systems to export
  111173. */
  111174. ParticleHelper.ExportSet = function (systems) {
  111175. var set = new BABYLON.ParticleSystemSet();
  111176. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  111177. var system = systems_1[_i];
  111178. set.systems.push(system);
  111179. }
  111180. return set;
  111181. };
  111182. /**
  111183. * Gets or sets base Assets URL
  111184. */
  111185. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  111186. return ParticleHelper;
  111187. }());
  111188. BABYLON.ParticleHelper = ParticleHelper;
  111189. })(BABYLON || (BABYLON = {}));
  111190. //# sourceMappingURL=babylon.particleHelper.js.map
  111191. var BABYLON;
  111192. (function (BABYLON) {
  111193. /**
  111194. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  111195. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  111196. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  111197. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111198. */
  111199. var VideoDome = /** @class */ (function (_super) {
  111200. __extends(VideoDome, _super);
  111201. /**
  111202. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  111203. * @param name Element's name, child elements will append suffixes for their own names.
  111204. * @param urlsOrVideo defines the url(s) or the video element to use
  111205. * @param options An object containing optional or exposed sub element properties
  111206. */
  111207. function VideoDome(name, urlsOrVideo, options, scene) {
  111208. var _this = _super.call(this, name, scene) || this;
  111209. _this._useDirectMapping = false;
  111210. // set defaults and manage values
  111211. name = name || "videoDome";
  111212. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111213. options.clickToPlay = Boolean(options.clickToPlay);
  111214. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  111215. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  111216. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111217. if (options.useDirectMapping === undefined) {
  111218. _this._useDirectMapping = true;
  111219. }
  111220. else {
  111221. _this._useDirectMapping = options.useDirectMapping;
  111222. }
  111223. _this._setReady(false);
  111224. // create
  111225. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  111226. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111227. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  111228. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111229. texture.onLoadObservable.addOnce(function () {
  111230. _this._setReady(true);
  111231. });
  111232. // configure material
  111233. material.useEquirectangularFOV = true;
  111234. material.fovMultiplier = 1.0;
  111235. material.opacityFresnel = false;
  111236. if (_this._useDirectMapping) {
  111237. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111238. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111239. material.diffuseTexture = texture;
  111240. }
  111241. else {
  111242. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111243. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111244. material.reflectionTexture = texture;
  111245. }
  111246. // configure mesh
  111247. _this._mesh.material = material;
  111248. _this._mesh.parent = _this;
  111249. // optional configuration
  111250. if (options.clickToPlay) {
  111251. scene.onPointerUp = function () {
  111252. _this._videoTexture.video.play();
  111253. };
  111254. }
  111255. return _this;
  111256. }
  111257. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  111258. /**
  111259. * Gets the video texture being displayed on the sphere
  111260. */
  111261. get: function () {
  111262. return this._videoTexture;
  111263. },
  111264. enumerable: true,
  111265. configurable: true
  111266. });
  111267. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  111268. /**
  111269. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111270. * Also see the options.resolution property.
  111271. */
  111272. get: function () {
  111273. return this._material.fovMultiplier;
  111274. },
  111275. set: function (value) {
  111276. this._material.fovMultiplier = value;
  111277. },
  111278. enumerable: true,
  111279. configurable: true
  111280. });
  111281. /**
  111282. * Releases resources associated with this node.
  111283. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111284. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111285. */
  111286. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111287. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111288. this._videoTexture.dispose();
  111289. this._mesh.dispose();
  111290. this._material.dispose();
  111291. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111292. };
  111293. return VideoDome;
  111294. }(BABYLON.TransformNode));
  111295. BABYLON.VideoDome = VideoDome;
  111296. })(BABYLON || (BABYLON = {}));
  111297. //# sourceMappingURL=babylon.videoDome.js.map
  111298. var BABYLON;
  111299. (function (BABYLON) {
  111300. /**
  111301. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  111302. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  111303. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  111304. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111305. */
  111306. var PhotoDome = /** @class */ (function (_super) {
  111307. __extends(PhotoDome, _super);
  111308. /**
  111309. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  111310. * @param name Element's name, child elements will append suffixes for their own names.
  111311. * @param urlsOfPhoto defines the url of the photo to display
  111312. * @param options defines an object containing optional or exposed sub element properties
  111313. * @param onError defines a callback called when an error occured while loading the texture
  111314. */
  111315. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  111316. if (onError === void 0) { onError = null; }
  111317. var _this = _super.call(this, name, scene) || this;
  111318. _this._useDirectMapping = false;
  111319. /**
  111320. * Observable raised when an error occured while loading the 360 image
  111321. */
  111322. _this.onLoadErrorObservable = new BABYLON.Observable();
  111323. // set defaults and manage values
  111324. name = name || "photoDome";
  111325. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111326. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111327. if (options.useDirectMapping === undefined) {
  111328. _this._useDirectMapping = true;
  111329. }
  111330. else {
  111331. _this._useDirectMapping = options.useDirectMapping;
  111332. }
  111333. _this._setReady(false);
  111334. // create
  111335. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111336. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111337. // configure material
  111338. material.opacityFresnel = false;
  111339. material.useEquirectangularFOV = true;
  111340. material.fovMultiplier = 1.0;
  111341. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  111342. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  111343. if (onError) {
  111344. onError(message, exception);
  111345. }
  111346. });
  111347. _this.photoTexture.onLoadObservable.addOnce(function () {
  111348. _this._setReady(true);
  111349. });
  111350. // configure mesh
  111351. _this._mesh.material = material;
  111352. _this._mesh.parent = _this;
  111353. return _this;
  111354. }
  111355. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  111356. /**
  111357. * Gets or sets the texture being displayed on the sphere
  111358. */
  111359. get: function () {
  111360. return this._photoTexture;
  111361. },
  111362. set: function (value) {
  111363. if (this._photoTexture === value) {
  111364. return;
  111365. }
  111366. this._photoTexture = value;
  111367. if (this._useDirectMapping) {
  111368. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111369. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111370. this._material.diffuseTexture = this._photoTexture;
  111371. }
  111372. else {
  111373. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111374. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111375. this._material.reflectionTexture = this._photoTexture;
  111376. }
  111377. },
  111378. enumerable: true,
  111379. configurable: true
  111380. });
  111381. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  111382. /**
  111383. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111384. * Also see the options.resolution property.
  111385. */
  111386. get: function () {
  111387. return this._material.fovMultiplier;
  111388. },
  111389. set: function (value) {
  111390. this._material.fovMultiplier = value;
  111391. },
  111392. enumerable: true,
  111393. configurable: true
  111394. });
  111395. /**
  111396. * Releases resources associated with this node.
  111397. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111398. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111399. */
  111400. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111401. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111402. this._photoTexture.dispose();
  111403. this._mesh.dispose();
  111404. this._material.dispose();
  111405. this.onLoadErrorObservable.clear();
  111406. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111407. };
  111408. return PhotoDome;
  111409. }(BABYLON.TransformNode));
  111410. BABYLON.PhotoDome = PhotoDome;
  111411. })(BABYLON || (BABYLON = {}));
  111412. //# sourceMappingURL=babylon.photoDome.js.map
  111413. var BABYLON;
  111414. (function (BABYLON) {
  111415. BABYLON.Engine.prototype.createQuery = function () {
  111416. return this._gl.createQuery();
  111417. };
  111418. BABYLON.Engine.prototype.deleteQuery = function (query) {
  111419. this._gl.deleteQuery(query);
  111420. return this;
  111421. };
  111422. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  111423. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  111424. };
  111425. BABYLON.Engine.prototype.getQueryResult = function (query) {
  111426. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  111427. };
  111428. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  111429. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111430. this._gl.beginQuery(glAlgorithm, query);
  111431. return this;
  111432. };
  111433. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  111434. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111435. this._gl.endQuery(glAlgorithm);
  111436. return this;
  111437. };
  111438. BABYLON.Engine.prototype._createTimeQuery = function () {
  111439. var timerQuery = this.getCaps().timerQuery;
  111440. if (timerQuery.createQueryEXT) {
  111441. return timerQuery.createQueryEXT();
  111442. }
  111443. return this.createQuery();
  111444. };
  111445. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  111446. var timerQuery = this.getCaps().timerQuery;
  111447. if (timerQuery.deleteQueryEXT) {
  111448. timerQuery.deleteQueryEXT(query);
  111449. return;
  111450. }
  111451. this.deleteQuery(query);
  111452. };
  111453. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  111454. var timerQuery = this.getCaps().timerQuery;
  111455. if (timerQuery.getQueryObjectEXT) {
  111456. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  111457. }
  111458. return this.getQueryResult(query);
  111459. };
  111460. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  111461. var timerQuery = this.getCaps().timerQuery;
  111462. if (timerQuery.getQueryObjectEXT) {
  111463. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  111464. }
  111465. return this.isQueryResultAvailable(query);
  111466. };
  111467. BABYLON.Engine.prototype.startTimeQuery = function () {
  111468. var caps = this.getCaps();
  111469. var timerQuery = caps.timerQuery;
  111470. if (!timerQuery) {
  111471. return null;
  111472. }
  111473. var token = new BABYLON._TimeToken();
  111474. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111475. if (caps.canUseTimestampForTimerQuery) {
  111476. token._startTimeQuery = this._createTimeQuery();
  111477. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  111478. }
  111479. else {
  111480. if (this._currentNonTimestampToken) {
  111481. return this._currentNonTimestampToken;
  111482. }
  111483. token._timeElapsedQuery = this._createTimeQuery();
  111484. if (timerQuery.beginQueryEXT) {
  111485. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111486. }
  111487. else {
  111488. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111489. }
  111490. this._currentNonTimestampToken = token;
  111491. }
  111492. return token;
  111493. };
  111494. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  111495. var caps = this.getCaps();
  111496. var timerQuery = caps.timerQuery;
  111497. if (!timerQuery || !token) {
  111498. return -1;
  111499. }
  111500. if (caps.canUseTimestampForTimerQuery) {
  111501. if (!token._startTimeQuery) {
  111502. return -1;
  111503. }
  111504. if (!token._endTimeQuery) {
  111505. token._endTimeQuery = this._createTimeQuery();
  111506. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  111507. }
  111508. }
  111509. else if (!token._timeElapsedQueryEnded) {
  111510. if (!token._timeElapsedQuery) {
  111511. return -1;
  111512. }
  111513. if (timerQuery.endQueryEXT) {
  111514. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  111515. }
  111516. else {
  111517. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  111518. }
  111519. token._timeElapsedQueryEnded = true;
  111520. }
  111521. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111522. var available = false;
  111523. if (token._endTimeQuery) {
  111524. available = this._getTimeQueryAvailability(token._endTimeQuery);
  111525. }
  111526. else if (token._timeElapsedQuery) {
  111527. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  111528. }
  111529. if (available && !disjoint) {
  111530. var result = 0;
  111531. if (caps.canUseTimestampForTimerQuery) {
  111532. if (!token._startTimeQuery || !token._endTimeQuery) {
  111533. return -1;
  111534. }
  111535. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  111536. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  111537. result = timeEnd - timeStart;
  111538. this._deleteTimeQuery(token._startTimeQuery);
  111539. this._deleteTimeQuery(token._endTimeQuery);
  111540. token._startTimeQuery = null;
  111541. token._endTimeQuery = null;
  111542. }
  111543. else {
  111544. if (!token._timeElapsedQuery) {
  111545. return -1;
  111546. }
  111547. result = this._getTimeQueryResult(token._timeElapsedQuery);
  111548. this._deleteTimeQuery(token._timeElapsedQuery);
  111549. token._timeElapsedQuery = null;
  111550. token._timeElapsedQueryEnded = false;
  111551. this._currentNonTimestampToken = null;
  111552. }
  111553. return result;
  111554. }
  111555. return -1;
  111556. };
  111557. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  111558. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  111559. };
  111560. // We also need to update AbstractMesh as there is a portion of the code there
  111561. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  111562. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  111563. this._isOccluded = false;
  111564. return;
  111565. }
  111566. var engine = this.getEngine();
  111567. if (engine.webGLVersion < 2) {
  111568. this._isOccluded = false;
  111569. return;
  111570. }
  111571. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  111572. this._isOccluded = false;
  111573. return;
  111574. }
  111575. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  111576. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  111577. if (isOcclusionQueryAvailable) {
  111578. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  111579. this._isOcclusionQueryInProgress = false;
  111580. this._occlusionInternalRetryCounter = 0;
  111581. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  111582. }
  111583. else {
  111584. this._occlusionInternalRetryCounter++;
  111585. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  111586. this._isOcclusionQueryInProgress = false;
  111587. this._occlusionInternalRetryCounter = 0;
  111588. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  111589. // if strict continue the last state of the object.
  111590. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  111591. }
  111592. else {
  111593. return;
  111594. }
  111595. }
  111596. }
  111597. var scene = this.getScene();
  111598. if (scene.getBoundingBoxRenderer) {
  111599. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  111600. if (!this._occlusionQuery) {
  111601. this._occlusionQuery = engine.createQuery();
  111602. }
  111603. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  111604. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  111605. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  111606. this._isOcclusionQueryInProgress = true;
  111607. }
  111608. };
  111609. })(BABYLON || (BABYLON = {}));
  111610. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  111611. var BABYLON;
  111612. (function (BABYLON) {
  111613. /**
  111614. * Class used to generate noise procedural textures
  111615. */
  111616. var NoiseProceduralTexture = /** @class */ (function (_super) {
  111617. __extends(NoiseProceduralTexture, _super);
  111618. /**
  111619. * Creates a new NoiseProceduralTexture
  111620. * @param name defines the name fo the texture
  111621. * @param size defines the size of the texture (default is 256)
  111622. * @param scene defines the hosting scene
  111623. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  111624. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  111625. */
  111626. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  111627. if (size === void 0) { size = 256; }
  111628. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  111629. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  111630. _this._time = 0;
  111631. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  111632. _this.brightness = 0.2;
  111633. /** Defines the number of octaves to process */
  111634. _this.octaves = 3;
  111635. /** Defines the level of persistence (0.8 by default) */
  111636. _this.persistence = 0.8;
  111637. /** Gets or sets animation speed factor (default is 1) */
  111638. _this.animationSpeedFactor = 1;
  111639. _this._updateShaderUniforms();
  111640. return _this;
  111641. }
  111642. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  111643. var scene = this.getScene();
  111644. if (!scene) {
  111645. return;
  111646. }
  111647. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  111648. this.setFloat("brightness", this.brightness);
  111649. this.setFloat("persistence", this.persistence);
  111650. this.setFloat("timeScale", this._time);
  111651. };
  111652. NoiseProceduralTexture.prototype._getDefines = function () {
  111653. return "#define OCTAVES " + (this.octaves | 0);
  111654. };
  111655. /** Generate the current state of the procedural texture */
  111656. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  111657. this._updateShaderUniforms();
  111658. _super.prototype.render.call(this, useCameraPostProcess);
  111659. };
  111660. /**
  111661. * Serializes this noise procedural texture
  111662. * @returns a serialized noise procedural texture object
  111663. */
  111664. NoiseProceduralTexture.prototype.serialize = function () {
  111665. var serializationObject = {};
  111666. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  111667. serializationObject.brightness = this.brightness;
  111668. serializationObject.octaves = this.octaves;
  111669. serializationObject.persistence = this.persistence;
  111670. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  111671. serializationObject.size = this.getSize().width;
  111672. serializationObject.generateMipMaps = this._generateMipMaps;
  111673. return serializationObject;
  111674. };
  111675. /**
  111676. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  111677. * @param parsedTexture defines parsed texture data
  111678. * @param scene defines the current scene
  111679. * @param rootUrl defines the root URL containing noise procedural texture information
  111680. * @returns a parsed NoiseProceduralTexture
  111681. */
  111682. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  111683. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  111684. texture.brightness = parsedTexture.brightness;
  111685. texture.octaves = parsedTexture.octaves;
  111686. texture.persistence = parsedTexture.persistence;
  111687. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  111688. return texture;
  111689. };
  111690. return NoiseProceduralTexture;
  111691. }(BABYLON.ProceduralTexture));
  111692. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  111693. })(BABYLON || (BABYLON = {}));
  111694. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  111695. var __assign = (this && this.__assign) || function () {
  111696. __assign = Object.assign || function(t) {
  111697. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111698. s = arguments[i];
  111699. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111700. t[p] = s[p];
  111701. }
  111702. return t;
  111703. };
  111704. return __assign.apply(this, arguments);
  111705. };
  111706. var BABYLON;
  111707. (function (BABYLON) {
  111708. /**
  111709. * This can helps recording videos from BabylonJS.
  111710. * This is based on the available WebRTC functionalities of the browser.
  111711. *
  111712. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  111713. */
  111714. var VideoRecorder = /** @class */ (function () {
  111715. /**
  111716. * Create a new VideoCapture object which can help converting what you see in Babylon to
  111717. * a video file.
  111718. * @param engine Defines the BabylonJS Engine you wish to record
  111719. * @param options Defines options that can be used to customized the capture
  111720. */
  111721. function VideoRecorder(engine, options) {
  111722. if (options === void 0) { options = null; }
  111723. if (!VideoRecorder.IsSupported(engine)) {
  111724. throw "Your browser does not support recording so far.";
  111725. }
  111726. var canvas = engine.getRenderingCanvas();
  111727. if (!canvas) {
  111728. throw "The babylon engine must have a canvas to be recorded";
  111729. }
  111730. this._canvas = canvas;
  111731. this._canvas.isRecording = false;
  111732. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  111733. var stream = this._canvas.captureStream(this._options.fps);
  111734. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  111735. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  111736. this._mediaRecorder.onerror = this._handleError.bind(this);
  111737. this._mediaRecorder.onstop = this._handleStop.bind(this);
  111738. }
  111739. /**
  111740. * Returns wehther or not the VideoRecorder is available in your browser.
  111741. * @param engine Defines the Babylon Engine to check the support for
  111742. * @returns true if supported otherwise false
  111743. */
  111744. VideoRecorder.IsSupported = function (engine) {
  111745. var canvas = engine.getRenderingCanvas();
  111746. return (!!canvas && typeof canvas.captureStream === "function");
  111747. };
  111748. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  111749. /**
  111750. * True wether a recording is already in progress.
  111751. */
  111752. get: function () {
  111753. return !!this._canvas && this._canvas.isRecording;
  111754. },
  111755. enumerable: true,
  111756. configurable: true
  111757. });
  111758. /**
  111759. * Stops the current recording before the default capture timeout passed in the startRecording
  111760. * functions.
  111761. */
  111762. VideoRecorder.prototype.stopRecording = function () {
  111763. if (!this._canvas || !this._mediaRecorder) {
  111764. return;
  111765. }
  111766. if (!this.isRecording) {
  111767. return;
  111768. }
  111769. this._canvas.isRecording = false;
  111770. this._mediaRecorder.stop();
  111771. };
  111772. /**
  111773. * Starts recording the canvas for a max duration specified in parameters.
  111774. * @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.
  111775. * @param maxDuration Defines the maximum recording time in seconds.
  111776. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  111777. * @return a promise callback at the end of the recording with the video data in Blob.
  111778. */
  111779. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  111780. var _this = this;
  111781. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  111782. if (maxDuration === void 0) { maxDuration = 7; }
  111783. if (!this._canvas || !this._mediaRecorder) {
  111784. throw "Recorder has already been disposed";
  111785. }
  111786. if (this.isRecording) {
  111787. throw "Recording already in progress";
  111788. }
  111789. if (maxDuration > 0) {
  111790. setTimeout(function () {
  111791. _this.stopRecording();
  111792. }, maxDuration * 1000);
  111793. }
  111794. this._fileName = fileName;
  111795. this._recordedChunks = [];
  111796. this._resolve = null;
  111797. this._reject = null;
  111798. this._canvas.isRecording = true;
  111799. this._mediaRecorder.start(this._options.recordChunckSize);
  111800. return new Promise(function (resolve, reject) {
  111801. _this._resolve = resolve;
  111802. _this._reject = reject;
  111803. });
  111804. };
  111805. /**
  111806. * Releases internal resources used during the recording.
  111807. */
  111808. VideoRecorder.prototype.dispose = function () {
  111809. this._canvas = null;
  111810. this._mediaRecorder = null;
  111811. this._recordedChunks = [];
  111812. this._fileName = null;
  111813. this._resolve = null;
  111814. this._reject = null;
  111815. };
  111816. VideoRecorder.prototype._handleDataAvailable = function (event) {
  111817. if (event.data.size > 0) {
  111818. this._recordedChunks.push(event.data);
  111819. }
  111820. };
  111821. VideoRecorder.prototype._handleError = function (event) {
  111822. this.stopRecording();
  111823. if (this._reject) {
  111824. this._reject(event.error);
  111825. }
  111826. else {
  111827. throw new event.error;
  111828. }
  111829. };
  111830. VideoRecorder.prototype._handleStop = function () {
  111831. this.stopRecording();
  111832. var superBuffer = new Blob(this._recordedChunks);
  111833. if (this._resolve) {
  111834. this._resolve(superBuffer);
  111835. }
  111836. window.URL.createObjectURL(superBuffer);
  111837. if (this._fileName) {
  111838. BABYLON.Tools.Download(superBuffer, this._fileName);
  111839. }
  111840. };
  111841. VideoRecorder._defaultOptions = {
  111842. mimeType: "video/webm",
  111843. fps: 25,
  111844. recordChunckSize: 3000
  111845. };
  111846. return VideoRecorder;
  111847. }());
  111848. BABYLON.VideoRecorder = VideoRecorder;
  111849. })(BABYLON || (BABYLON = {}));
  111850. //# sourceMappingURL=babylon.videoRecorder.js.map
  111851. var BABYLON;
  111852. (function (BABYLON) {
  111853. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  111854. if (replace === void 0) { replace = false; }
  111855. // Dispose existing light in replace mode.
  111856. if (replace) {
  111857. if (this.lights) {
  111858. for (var i = 0; i < this.lights.length; i++) {
  111859. this.lights[i].dispose();
  111860. }
  111861. }
  111862. }
  111863. // Light
  111864. if (this.lights.length === 0) {
  111865. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  111866. }
  111867. };
  111868. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  111869. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111870. if (replace === void 0) { replace = false; }
  111871. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111872. // Dispose existing camera in replace mode.
  111873. if (replace) {
  111874. if (this.activeCamera) {
  111875. this.activeCamera.dispose();
  111876. this.activeCamera = null;
  111877. }
  111878. }
  111879. // Camera
  111880. if (!this.activeCamera) {
  111881. var worldExtends = this.getWorldExtends();
  111882. var worldSize = worldExtends.max.subtract(worldExtends.min);
  111883. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  111884. var camera;
  111885. var radius = worldSize.length() * 1.5;
  111886. // empty scene scenario!
  111887. if (!isFinite(radius)) {
  111888. radius = 1;
  111889. worldCenter.copyFromFloats(0, 0, 0);
  111890. }
  111891. if (createArcRotateCamera) {
  111892. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  111893. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  111894. arcRotateCamera.wheelPrecision = 100 / radius;
  111895. camera = arcRotateCamera;
  111896. }
  111897. else {
  111898. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  111899. freeCamera.setTarget(worldCenter);
  111900. camera = freeCamera;
  111901. }
  111902. camera.minZ = radius * 0.01;
  111903. camera.maxZ = radius * 1000;
  111904. camera.speed = radius * 0.2;
  111905. this.activeCamera = camera;
  111906. var canvas = this.getEngine().getRenderingCanvas();
  111907. if (attachCameraControls && canvas) {
  111908. camera.attachControl(canvas);
  111909. }
  111910. }
  111911. };
  111912. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  111913. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111914. if (replace === void 0) { replace = false; }
  111915. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111916. this.createDefaultLight(replace);
  111917. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  111918. };
  111919. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  111920. if (pbr === void 0) { pbr = false; }
  111921. if (scale === void 0) { scale = 1000; }
  111922. if (blur === void 0) { blur = 0; }
  111923. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  111924. if (!environmentTexture) {
  111925. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  111926. return null;
  111927. }
  111928. if (setGlobalEnvTexture) {
  111929. if (environmentTexture) {
  111930. this.environmentTexture = environmentTexture;
  111931. }
  111932. }
  111933. // Skybox
  111934. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  111935. if (pbr) {
  111936. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  111937. hdrSkyboxMaterial.backFaceCulling = false;
  111938. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  111939. if (hdrSkyboxMaterial.reflectionTexture) {
  111940. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111941. }
  111942. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  111943. hdrSkyboxMaterial.disableLighting = true;
  111944. hdrSkyboxMaterial.twoSidedLighting = true;
  111945. hdrSkybox.infiniteDistance = true;
  111946. hdrSkybox.material = hdrSkyboxMaterial;
  111947. }
  111948. else {
  111949. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  111950. skyboxMaterial.backFaceCulling = false;
  111951. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  111952. if (skyboxMaterial.reflectionTexture) {
  111953. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111954. }
  111955. skyboxMaterial.disableLighting = true;
  111956. hdrSkybox.infiniteDistance = true;
  111957. hdrSkybox.material = skyboxMaterial;
  111958. }
  111959. return hdrSkybox;
  111960. };
  111961. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  111962. if (BABYLON.EnvironmentHelper) {
  111963. return new BABYLON.EnvironmentHelper(options, this);
  111964. }
  111965. return null;
  111966. };
  111967. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  111968. if (webVROptions === void 0) { webVROptions = {}; }
  111969. return new BABYLON.VRExperienceHelper(this, webVROptions);
  111970. };
  111971. })(BABYLON || (BABYLON = {}));
  111972. //# sourceMappingURL=babylon.sceneHelpers.js.map
  111973. 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"};
  111974. 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};"};